Skip to content

Refactor waveform_8266 for possibly tighter timings - #3504

Merged
pkendall64 merged 5 commits into
ExpressLRS:masterfrom
CapnBry:esppwm-dotwo
Feb 11, 2026
Merged

pkendall64 merged 5 commits into
ExpressLRS:masterfrom
CapnBry:esppwm-dotwo

Conversation

@CapnBry

@CapnBry CapnBry commented Jan 21, 2026 •

Copy link
Copy Markdown
Member

Rewrites much of the ESP8285's PWM waveform generator to attempt to reduce jitter on the output by removing phase correction and interrupt moderation, as well as adding speculative pin flips. Removes some Arduino core dead code / RAM too.

Possible #3418

Details

Testing using 5ch PWM output with the 1500us test channel at 333Hz and the others at 50Hz and constantly changing, master (and 3.x.x-maint) generates a bit of a spread spectrum of output with an error of -2 to +3us with rare excursions to +10-20us. The mean is great and stable but with a high standard deviation. Here's summary of 1500us output with each line representing 150 pulses (times in nanoseconds, last number is just a recent max)

// Master code
(ns) mean=1500037 min=1500025 max=1500050 range=25 (2625)
(ns) mean=1500037 min=1499087 max=1500512 range=1425 (2625)
(ns) mean=1500037 min=1499612 max=1500050 range=438 (2625)
(ns) mean=1500037 min=1500037 max=1500150 range=113 (2625)
(ns) mean=1500037 min=1500025 max=1500050 range=25 (2625)
(ns) mean=1500037 min=1500037 max=1500050 range=13 (2625)
(ns) mean=1500037 min=1499237 max=1500450 range=1213 (2625)
(ns) mean=1500037 min=1498575 max=1500762 range=2187 (2625)
(ns) mean=1500037 min=1498600 max=1500762 range=2162 (2625)
(ns) mean=1500037 min=1498512 max=1500800 range=2288 (2625)
(ns) mean=1500037 min=1500025 max=1500050 range=25 (2625)
(ns) mean=1500037 min=1500037 max=1500050 range=13 (2625)

To attempt to deal with this, I've modified the interrupt handler significantly

  • Removed phase compensation. This causes the min value above to be well below the desired output. We care more about the length of the pulses and phase compensation will reduce the pulse length to try to maintain phase. None of our pulses are in phase so this won't be missed.
  • Removed interrupt moderation and max interrupt runtime. The old code limited execution to 14us at a time and would just keep running until the next timeout was beyond that, and then schedule the next execution for at least 10us in the future. This could cause way late timings and I believe were responsible for the rare excursions. One pass through all the code with one pin flip takes under 2.4us, and with 6x 333Hz PWMs (which I don't know if I'd recommend on this hardware) it is impractical that the loop would exceed 14us, and impossible for it to run indefinitely.
  • Allow early pin flips. The existing code would wait until after the pin was scheduled to flip-- running through the loop multiple times until it was in the past. A loop of 5x PWM spread across 10 pins takes ~250 clock cycles or ~1.5us. The new code will flip the pin early if it is within half a loop cycle of the expiration time. The code self-profiles to determine the loop duration and starts with a conservative estimate.
  • Disable the timer during the interrupt. Theoretically this shouldn't be an issue but as soon as the timer is reloaded it starts again, so very low timeouts can cause a timer underflow which results in a ~104ms pause.

Results

// esppwm-dotwo updated code
(ns) mean=1500062 min=1500062 max=1500075 range=13 (1512)
(ns) mean=1500062 min=1500050 max=1500075 range=25 (1512)
(ns) mean=1500062 min=1499837 max=1500075 range=238 (1512)
(ns) mean=1500062 min=1499962 max=1500075 range=113 (1512)
(ns) mean=1500062 min=1500062 max=1500075 range=13 (1512)
(ns) mean=1500062 min=1500062 max=1500075 range=13 (1512)
(ns) mean=1500062 min=1500050 max=1500075 range=25 (1512)
(ns) mean=1500062 min=1500050 max=1500075 range=25 (1512)
(ns) mean=1500062 min=1500062 max=1500075 range=13 (1512)
(ns) mean=1500062 min=1499225 max=1500075 range=850 (1512)
(ns) mean=1500062 min=1500062 max=1500075 range=13 (1512)

image image

Code / RAM Size

I also figured out how to finally remove the old waveform generator code and RAM from the binary. In addition this interrupt code is smaller, faster, and has to store less state per pin. In the future the state RAM (496 bytes) can be dynamically allocated by the PWMController controller class when wifi goes hot and all the PWM are shut down. Current savings:

  • 776 bytes of RAM saved (1.6%)
  • 556 bytes of code saved (1.1%)

Backport?

This can be backported to 3.x.x-maint (neverending maint lols) after it goes through proper testing for 4.1

@CapnBry
CapnBry marked this pull request as draft January 21, 2026 20:24
@jurgelenas

Copy link
Copy Markdown
Member

Nice 🚀

@CapnBry

CapnBry commented Jan 21, 2026

Copy link
Copy Markdown
Member Author

This is a standalone test I used for working on this. There's two platformio environments in here. One is the code with a mock of our RX code sorta-- pumping in "new channels" at 333Hz and driving 5x PWM outputs. Pins are defined in GPIO_PIN_PWM_OUTPUTS and you can change the output frequency as well as use 10KHz duty cycle, which also works but I'd hate to see someone trying to run 6x 10KHz outputs and keep the radio link up 😓

The second is for an ESP32 to capture the timing on the pin under test using MCPWM capture. This mostly works but every so often it will report an incorrect pulse length which I do not see on the logic analyzer capturing the same pin, so I think there's a bug somewhere.

ServoTest.zip

@CapnBry

CapnBry commented Jan 22, 2026 •

Copy link
Copy Markdown
Member Author

I've hand tuned the interrupt pre-roll to remove most of the ~0.5us offset found in this PR compared to master. I think this is good to go now but I'd love some independent validation of the output timing as I don't completely trust my own numbers due to the occasional weird value that I'd see but only on the ESP32 capture. My oscilloscope says it is very close to the original with just slightly tighter tolerance (-1.0us to +4.0us vs -2.0 to +4.0us) and no outliers 🫤

I'm not sure what to believe!

@CapnBry
CapnBry marked this pull request as ready for review January 22, 2026 14:42
* No extra interrupt generated when all servos are 50Hz
* Better lastLoopCs estimate
* Fire ISR 3us early, look ahead up to 5us

@mha1 mha1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much much better. Great job!

Image

@CapnBry CapnBry added the enhancement 🪄 New feature or request label Feb 8, 2026
@pkendall64
pkendall64 merged commit 1d548dd into ExpressLRS:master Feb 11, 2026
26 checks passed
CapnBry pushed a commit to CapnBry/ExpressLRS that referenced this pull request Feb 20, 2026
Refactor waveform_8266 for possibly tighter timings
@CapnBry
CapnBry deleted the esppwm-dotwo branch April 3, 2026 14:13
SunjunKim added a commit to SunjunKim/ExpressLRS that referenced this pull request Apr 16, 2026
* Reduce RAM usage (ExpressLRS#3238)

* Move MAVLink buffers into MAVLink serial connector

This reduces RAM usage when not in MAVLink mode.

* Reduce RAM slightly in mavlink mode too

* Change MSP TcpSocket to dynamically allocate its buffers (ExpressLRS#3240)

* Dynamically allocate tcp-crsf buffers, remove client leak

* Move crsf2msp into tcpsocket

* Move msp2crsf to tcpsocket

* Fix flashing backpack via passthrough when its not connected to UART0 (ExpressLRS#3242)

* Double-free on TCPclient timeout (ExpressLRS#3243)

* Double-free on client timeout

* Remove unnecessary send()

* When PWM pins are also defined as serial, default to serial (ExpressLRS#3249)

* Allow 0xE1 LR1121 type for experimental firmware

* Add experimental commands to LR1121 header

* Use WriteBuffer8_SetTx command

* Use GetPacket combined command

* Common code extraction. more deleting :-)

* correct rssi reading for fsk

* Cleanup stats

* LBT implementation for LR1121

Extract EnableLBT function

* Optimise GetRssiInst for LR1121

* Some fixes and debugging changes

* Remove unnecessary `instance->` dereferences

* Fix RX timeout

* Fix transmitter modules

* Adjust LR1121 LBT times to correct (tested) values.

* Fix a couple of nasty bugs in the LR1121 upload code!

* Fix debug logging

* Only get RSSI from "active" radios

* fix domain label

* fix RXnb to use the rxMode passed

* wip

* Bring back the commented out code

* Fix debugging error

* work around possible stack corruption issue

Still need to figure out _how_ this is happening!

* force a minimum period of 30us for very short LBT CCA times

* correct comment placement

* return correct radioNumber

Returning ALL will force gemini mode for 10mW LBT, even when only a single anetnna mode, or switch, has been selected.

* enable LBT for X modes

* fix X mode LBT

* limit 868 to 25mW when using Regulatory_Domain_EU_CE_2400

* fix FHSS for non Regulatory_Domain_ISM_2400

* make power labels clearer

"/" would have been better than "-" but it dose not display correctly in Lua.

* power and lbt labels v2

* Move the LR1121 firmware update routines to the driver library

* Return a struct for the version number

* fixes ExpressLRS#3249

* initial commit

* Update firmware on LR1121 on boot

If it's not the same as in the ELRS firmware

* Allow manually uploaded firmware to override the built-in

Also provides the ability to clear the 'manual' flag and reflash the default on reboot.

* Duh! Fix logic error

* UI cosmetics

- removed LBT Enabled line due to LUA restrictions (can't be updated after packet rate change)
- change & to /

* UI cosmetics

- removed LBT Enabled line due to LUA restrictions (can't be updated after packet rate change)
- change & to /

* Fixes grammer

* Fix VTX commands not being processed

Broken by ExpressLRS#3240

* Fix Serial & Serial1 defaulting to serial output when also defined as PWM pins

* change priority order for baro data from GPS, Vario, ... to Vario, GPS, ...

* Serial1 not available on ESP8285

* Constrain the us value to avoid overflow errors

* ESP32C3 TX module support

For RX as TX and debugging

* Shouldn't have second guessed myself!

* fix HoTT TLM frame definition for ESCs (ExpressLRS#3281)

* Use wifi MAC as default UID for ESP8285 TX

* Fix inverted IQ check.

Fix LR1121 passing wrong value to command

* Fixes found during review & testing

* Remove early initialisation

* Perform servo & dshot initialisation on connection

* Leave Dshot "arming" to the TX

* Constraining PPMHandset ppm value within the CRSF limits (ExpressLRS#3303)

* limit the servo output range to 1100-1900

* limit the ppm range to be within CRSF range.

* Revert "limit the servo output range to 1100-1900"

This reverts commit 712453c.

* fix fmap for the fundamental problem prevention

* limiting contstrain within ppmhandset

* safer fmap to prevent underflow

* Update devServoOutput.cpp -PWM start w/digitalWrite LOW

* Update devServoOutput.cpp -update PWM / DSHOT pin start state note

* Update devServoOutput.cpp -remove pinmode and digital write from start

* Update devServoOutput.cpp -take 4

* backported PK's optimized-tx branch to 3.6

* backport commit

* reinstated alreadyFHSS == true in HandleFHSS

* removed all occurences of bool alreadyFHSS

* cleanup

* fixes excessive packet jitter

* change MODE_RX to MODE_RX_CONT for SX1280 too

* Add PK's commits:

- continuous mode RX (51800d4)
- remove interval since it's no longer used (73097f4)

* reinstate alreadyFHSS logic

* cleanup: deleted unused defines

* cleanup: delete ununsed function and defines

* Lbt interface renames to match master PR

* Fix intermittent RGB LED startup hang

* Update devServoOutput.cpp -removed start()

* Use the Strongest receiving radio for sending in diversity mode

Fix LBT reading second radio when there isn't one

* Remove more feature so we can support Ghost Atto in V3

* Limit the firmware size to the _actual_ available space

* Changes:

- set lr1121 SPI clock rate to max. specified clock rate of 16MHz
- changed WaitOnBusy timeout due to unknown issues in a small percentage of LR1121s that some commands may have extremely long busy times during startup, exceeding 1ms

* STM32 and 8285 do NOT support two RF paths

This caused an issue where the PA was NOT enabled when transmitting because we send Radio_ALL which is not supported

* Fix LR1121 not committing power change when switching band

* Disable backpack in wifi and BLE modes (ExpressLRS#2940)

* Fix crash in CRSF parser with CRSF packet length 0 - V3 (ExpressLRS#3430)

* fixes potential crash due to index out of bounds for CRSF packets with zero length byte

* fix expected min packet length

* fix upper length byte limit too

* as per review comments, broadcast frames may have zero payload length

* Only use the default UART0 for passthrough flashing

* Extend tcpsocket idle timeout

* Extend VTX Admin disconnect debounce

* Merge master elrs.lua changes

* Disable PA in TXRXdisable() whether in rx_enable or tx_enable state

Signed-off-by: ncerzzk <[email protected]>

* Fix issue with latest platform io not allowing a `.` character in the environment name.

* STM32/SX1280 - Add clarity to the SX1280 clock speed divider setting.

* old code said: `DIV4`, but comment read `72 / 8 = 9Mhz`, but using DIV4 would mean a frequency of 18Mhz (72 / 4).
* L432 has a higher system clock (80Mhz) than what was in use when the comment was written (probably F1 @ 72Mhz), so the resulting frequency is 20Mhz on the L4.

* STM32L432/SX1280 - Avoid overclocking the SPI bus.

* communication error failures were observed at 20Mhz, which is out-of-spec.

* Allows updating backpack firmware via USB

Without distinguishing between built-in and external TX

* Merge pull request ExpressLRS#3504 from CapnBry/esppwm-dotwo

Refactor waveform_8266 for possibly tighter timings

* Fix FM30 not enabling the DCDC due to use of an outdated/incorrect `#define`.

---------

Signed-off-by: ncerzzk <[email protected]>
Co-authored-by: Paul Kendall <[email protected]>
Co-authored-by: Bryan Mayland <[email protected]>
Co-authored-by: Jye <[email protected]>
Co-authored-by: Michael <[email protected]>
Co-authored-by: Michael <[email protected]>
Co-authored-by: pitts-mo <[email protected]>
Co-authored-by: ncerzzk <[email protected]>
Co-authored-by: Dominic Clifton <[email protected]>
Co-authored-by: linjieqiang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement 🪄 New feature or request V4.1 🍑

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants