Raspberry Pi and PWM

The Raspberry Pi has one GPIO line, GPIO18 at Pin 12 on the 26-way P1 or the 40-way J8, depending on the model.

Although there are device driver programs such as servoblaster or some excellent hardware units available for driving several motors and servos at the same time, such as the PCA9685-based Hobbytronics' 16-channel PWM / Servo Controller or Adafruit's DC and Stepper Motor HAT, sometimes only one servo is needed, and then it is quite nice to be able to plug this straight into the GPIO connections with no additional circuitry that takes up space.

Now as it turns out, there are some rather severe limitations here, most notably, that the resolution supported for the PWM is only 32 steps or 5 bits. For a servo where there is a minimum and a maximum limit on the duty cycle, only about 16 of these steps match the requirements.

Back in 2012, Frank Buss made an example program for doing PWM on this line, using /dev/mem to manipulate the registers and allow the control of a servo. I have improved slightly on this, by making the code work right on all the various varieties of Raspberry Pis that I have, which include the B, B+ and 2B. The logic is based on the one from my gpiostates program, where the /proc/cpuinfo is read to determine the version of the CPU and thus where the IO space start address is supposed to be. Then the rest are offsets from that.

Hardware - connect a servo

This is simple: the servo has a 3-conductor cord where the three conductors are +5V, 0V, and control signal in some order or another depending on the make.

The servo I tried this with first is a Futaba S3003 and its color-coding is:

Futaba S3003 HD 1201MGFunction P1 or J8 Pin No
Black Brown 0V 6
Red Red +5V 4
White Orange PWM (GPIO18) 12

Other servos have other color schemes and the plug at the end of the cable might not have the same pin-out. An overview can be found here

Here is a tarball of the program-files as modified. Like the original, this just cycles the servo through the sequence of 0% 25% 50% 75% 100% positions forever. Of the two servos tested above, both have a 90 degrees movement angle between 0% and 100%, but they position in opposite directions: the Futaba S3003 has steps increasing widdershins as seen from the top, while the HD 1201MG steps increasing deasil as seen from the top.