Simvik

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 2000

Angles that do not divide evenly

printf("%u %u\n", servo_ticks(45), servo_ticks(1));

Expected output:

1250 1006

Learn it first

  • Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.

More Timers and PWM problems