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 2000The gripper's stops
printf("%u %u\n", servo_compare(900, -300, 450), servo_compare(-900, -300, 450));Expected output:
3500 2667Learn it first
- Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.
More Timers and PWM problems
- Servo pulse width · Turn an angle into the compare value for a hobby servo's pulse.
- 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.