Simvik

Robot gripper: servo angle to timer value

Turn a servo angle into the timer's compare value, within the gripper's mechanical limits. A medium embedded C problem (Timers and PWM), run and graded in…

medium · Timers and PWM · servo · pwm · limits · product

Product: Robot gripper (Robotics)

Requirement. A hobby-style servo moves to -90° with a 1000 µs pulse, 0° with 1500 µs and +90° with 2000 µs. The timer counts in 0.5 µs ticks, so a compare value of 3000 gives 1500 µs.

The gripper's jaws hit their stops before the servo's full range: driving past min_deg10 or max_deg10 stalls the servo, which overheats it. Angles are in tenths of a degree.

Limit the angle to min_deg10…max_deg10, then return the compare value, rounded to the nearest tick (halves away from zero).

Starter code

uint16_t servo_compare(int16_t angle_deg10, int16_t min_deg10, int16_t max_deg10) {
  return (uint16_t)(1500 + angle_deg10 * 500 / 900);
}

Example tests

Centre and both ends

printf("%u %u %u\n", servo_compare(0, -900, 900), servo_compare(900, -900, 900), servo_compare(-900, -900, 900));

Expected output:

3000 4000 2000

The gripper's stops

printf("%u %u\n", servo_compare(900, -300, 450), servo_compare(-900, -300, 450));

Expected output:

3500 2667

Learn it first

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

More Timers and PWM problems