Controlling A Servo With PWM
in this notebook we will be controlling a servo on a raspberry pi with the
Pigpiox library which uses the pigpio library under the hood. You will need an SG90 servo motor or something similar.
Try it out
Lets set a variable so that we don’t have to choose the GPIO pin every time.
First, refer to the GPIO ports for your Nerves device. In this example, we will be using pin 12 on the raspberry pi platform.
Wire everything up like in the diagram below. Servos have 3 wires: ground, vcc and pwm. In this case the black is ground the red is vcc and the yellow is pwm. Hook it up to pin 12 of the raspberry pi.
Lets set the pin as a variable so we don’t have to choose the GPIO pin every time.
pin = 12
Now we can set the servo to neutral or 90 degrees with the following command.
Pigpiox.Socket.command(:set_servo_pulsewidth, pin, 1500)
Here we can set it to 0 degrees.
Pigpiox.Socket.command(:set_servo_pulsewidth, pin, 500)
And now 180 degrees.
Pigpiox.Socket.command(:set_servo_pulsewidth, pin, 2500)
Refer to the data sheet for your servo. You may need to change the values.You can learn more about how servos work here.