Tuesday, 5 July 2016

Raspberry Pi: servo motor control via PWM

Following a question raised in response to a recent post on PWM, I hooked up a small servo motor to a Pi.


The motor in question is a 3 wire jobbie that needs a short pulse to control its position.


This short post explains how to drive the servo motor using wiringPi with a touch of Gambas.

Popular "closed loop" servo motors include a control circuit, allowing precise setting/positioning of the rotor.

I have a few Tower Pro SG90 servo motors which are supposed to operate over a +/-90 degree range.


In fact the range seems to vary from motor-to-motor, with some units exceeding 180 while others can only manage 170 degrees.

My servo motors can be controlled from a Raspberry Pi using a PWM output, where the frequency is set to approximately 50Hz and the positive going pulse width is as follows:-

  • 1.5ms = motor mid-way
  • 1ms = 45 deg clockwise
  • 2ms = 45 deg counter clockwise

Using wiringPi and Gambas


Follow my earlier post to install wiringPi and create the Gambas test program.

The pwm frequency = 19200000Hz / pwm clock / pwm range.

The recommended frequency for my motors is 50Hz, so I set the clock divisor to 200 and the range to 1920.

50Hz has a period of 20ms. So to generate a 2ms pulse we set an output value of 192 (i.e. 20ms x 192/1920 = 2ms).

And for 1ms, the output value should be 96 (i.e. 20ms x 96/1920 = 1ms).

Modify the Gambas test program:-
  • set the initial values: Clock= 200, pwm range=1920,  output=144
  • set Mark/space mode: pwmSetMode(0)
  • disable the timer
  • add a button which sets the pwm values (i.e. replaces the timer function)

Motor connections


For small, low power motors:-
  • connect gnd wire to gpio connector physical pin 6
  • connect +V wire to gpio connector physical pin 4
  • connect pwm wire to gpio connector physical pin 12

Now you can run the test program and vary the output value as follows:-
  • 144 = mid position
  • 96 = 45 deg clockwise
  • 192 = 45 deg counter clockwise

Have fun!

No comments:

Post a Comment