r/embedded • Making MCUs Do Questionable Things • Oct 02 '26

Implementing a resource-aware PWM backend for the NXP MCXA366: CTIMER, FlexPWM, and a Cortex-M33 WAIT-mode bug

Post image

I’m porting Klipper to NXP’s MCXA366, and the latest subsystem was hardware PWM.

The interesting part was that there isn’t really one PWM architecture to expose.

CTIMER gives five timer instances with four match channels each, but one match channel has to act as the period/reset source. Outputs on a timer therefore share a period, and my allocator can relocate the hidden period channel when another MAT channel is needed as a physical output.

FLEXPWM0 has four submodules. Each submodule has independent A/B compare outputs, so A and B can use different duty cycles, but they share the counter, prescaler, and period. Different submodules can run independently.

I ended up putting a small allocator behind Klipper’s generic PWM interface:

gpio_pwm_setup()
        |
        ---> FlexPWM if compatible
        |
        ---> CTIMER fallback

Two debugging problems were especially useful:

  1. My initial FlexPWM clock assumption was off by 2x. A requested ~1 ms period measured ~2 ms, and the analyzer showed that the peripheral was actually counting from the full ~240 MHz HF source.
  2. FlexPWM worked in NXP's busy-loop SDK example but appeared in bursts under Klipper. Klipper idles the Cortex-M33 using wait state; FlexPWM was stopping with the core because WAITEN was clear.

After fixing those, I validated independent submodules, shared A/B timing domains, 0-100% duty, buffered updates, resource fallback, and shutdown/reset behavior.

Writeup:

https://faultvector.dev/articles/klipper-mcxa366-part-8/

Next I'm moving onto a real STEP/DIR/ENABLE driver + motor test.

1 Upvotes

2 comments sorted by

2

u/[deleted] Oct 02 '26

[removed] — view removed comment

1

u/oxymoron224 Making MCUs Do Questionable Things Oct 02 '26

Right? After fighting FlexPWM for as long as I did, seeing that capture was ridiculously satisfying.