This post shows a very simple servo motor design, using NXP's Configurator and driver APIs. It can control the direction and the speed or angle of the servo..
I'm testing it on shabaz' EZ-MCXN dev board.
This can be helpful to work with the stepper(s) of the Rise Of The Robots - Robotics Design Challenge.
Controlling a servo is fairly easy. You need a 20 ms (=50 Hz) PWM signal, and be able to control its duty cycle to +- 1 - 2 ms. An ideal job for a generic timer.
I set up a timer, to pulse at 50 Hz, with a 10000 tick resolution. So I can set the PWM on-time in steps of 20 ms/10000.
A common stepper sets its position to middle at 1.5 ms. -90° at around 1ms and +90° at 2 ms.
If you have a 360° servo, 1 ms will be max speed counterclockwise. 1.5 ms will stop the motor, and 2 ms max speed clockwise.

Steppers aren't that precise though, so you 'll need to find what works for your model. My motor has its middle point aroud 1.552 ms, and min and max are +- 980 µs.
The class I wrote expects ticks. So you have to convert (or ask your code to convert) the mid time and min/max on-time to ticks, using the data above.
While a set of similar motors will have the same settings, their mid-point will not be exact. That's why the class accepts an optional offset in the constructor, that allows you to deal with the 0° angle error.
example code
mcx_servo_driver servo(CTIMER3_PERIPHERAL, CTIMER3_PWM_0_CHANNEL, CTIMER3_PWM_PERIOD,
750U, 490U, +26);
int main(void) {
// ...
servo.set(0);
servo.start_motor();
while (1) {
SDK_DelayAtLeastUs(500000U, SystemCoreClock);
servhttps://community.element14.com/technologies/embedded/b/blog/new#o.set(-490);
SDK_DelayAtLeastUs(250000U, SystemCoreClock);
servo.set(0);
SDK_DelayAtLeastUs(500000U, SystemCoreClock);
servo.set(+490);
SDK_DelayAtLeastUs(250000U, SystemCoreClock);
servo.set(0);
}
driver class
#include "peripherals.h"
#include "fsl_ctimer.h"
class mcx_servo_driver {
public:
mcx_servo_driver(CTIMER_Type *timer_instance, ctimer_match_t pwm_channel, uint32_t resolution, int32_t mid, uint32_t max, int32_t error = 0) :
timer(timer_instance), pwm_channel(pwm_channel), resolution(resolution), mid(mid), max(max), error(error) {}
void init() {
}
void start_motor() {
CTIMER_Reset(timer);
CTIMER_StartTimer(timer);
}
void stop_motor() {
CTIMER_StopTimer(timer);
}
void set(int32_t value) {
if (value < 0 - static_cast<int32_t>(max)) {
value = 0 - static_cast<int32_t>(max);
} else if (value > static_cast<int32_t>(max)) {
value = static_cast<int32_t>(max);
}
CTIMER_UpdatePwmPulsePeriod(timer, pwm_channel, (resolution + 1 - mid + error) + value);
}
private:
CTIMER_Type *timer;
ctimer_match_t pwm_channel;
uint32_t resolution;
int32_t mid;
uint32_t max;
int32_t error;
};
control signal:
Thank you for reading