Servo pulse width
Turn an angle into the compare value for a hobby servo's pulse. An easy embedded C problem (Timers and PWM), run and graded in the browser.
easy · Timers and PWM · pwm · servo · rounding
A hobby servo reads the width of a pulse sent every 20 ms: 1000 us for 0 degrees, 2000 us for 180 degrees, and in proportion between. The timer driving the pin ticks once per microsecond, so the compare value is the pulse width in microseconds.
Return the compare value for angle, rounded to the nearest tick. Angles above 180 must be treated as 180: a servo driven past its end stop stalls and heats up.
Starter code
uint16_t servo_ticks(uint16_t angle) {
return 1000 + angle * 1000 / 180;
}Example tests
End points and centre
printf("%u %u %u\n", servo_ticks(0), servo_ticks(90), servo_ticks(180));Expected output:
1000 1500 2000Angles that do not divide evenly
printf("%u %u\n", servo_ticks(45), servo_ticks(1));Expected output:
1250 1006Learn it first
- Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.
More Timers and PWM problems
- Prescaler and auto-reload · Choose PSC and ARR for a 16-bit timer to hit an update frequency.
- Frequency from input capture · Compute a signal's frequency from two capture timestamps on a 16-bit timer.
- Duty cycle from captures · Measure a PWM signal's duty cycle in tenths of a percent.
- Decode a quadrature encoder · Turn A/B channel transitions into +1, -1 or 0 steps with a lookup table.
- Software PWM · Drive four PWM channels from a timer tick on pins without PWM hardware.
- Fan speed from tach pulses · Compute a fan's RPM from captured tach pulse times, and report 0 when it stalls.
- Fix: long delays end far too early · Delays over about four seconds come out wrong.
- Driver: a millisecond delay on a hardware timer · Program a timer's prescaler and auto-reload, and wait for exactly one period.
- Fix: 100 % brightness still flickers · A duty-cycle conversion uses the auto-reload value instead of the period length.
- Greenhouse: fan speed from temperature · Map a temperature to a PWM duty cycle, without stalling the fan at low speed.
- Robot gripper: servo angle to timer value · Turn a servo angle into the timer's compare value, within the gripper's mechanical limits.