Search code examples
craspberry-pipwm

Controlling a servo with raspberry pi using the hardware PWM with wiringPi


I tried controlling the servo with softPwm using the wiringPi Library but this made the servo stutter. Therefore I want to use the hardware PWM pin on the Raspberry Pi (GPIO18) with the wiringPi library. But I don't understand how to set the frequency to 50 Hz and change the duty cycle to have a pulse width ranging from 0.8 ms to 2.5 ms.

I found the following relationship on the internet (i dont know if it is correct):

pwmFrequency in Hz = 19.2e6 Hz / pwmClock / pwmRange.

i know the clock divisor max value is something around 4000 and the Raspberry Pi PWM clock has a base frequency of 19.2 MHz. so this gives me ~4,8KHz.

i already got these settings which should give me ~50Hz using the following relationship:

//put PWM in mark-space mode, which will give you 
//the traditional (and easily predictable) PWM    
pwmSetMode(PWM_MODE_MS);
//setting ping GPIO 18 as a pwm output
pinMode(18,PWM_OUTPUT);
//Set clock divisor to 4000
pwmSetClock(4000);
pwmSetRange (10) ;

I dont got a oscilloscope to test the output signal to check what setting changes what. this makes it hard to find it out myself.

Long story short: Can anyone tell me how I can achieve a duty cycle with a pulse width of 0,8ms to 2,1ms for controlling a servo using the hardware PWM on the Raspberry Pi.


Solution

  • How about using RPIO instead? Here's the link to the library: http://pythonhosted.org/RPIO/index.html

    Here's the PWM example: http://pythonhosted.org/RPIO/pwm_py.html And you may also use the C source directly: https://github.com/metachris/RPIO/tree/master/source/c_pwm