Controlling servo with RPi3B+
Hello, I’m a 14-year-old kid from the Czech Republic interested in programming JavaScript and technology with my dad.
We wanted to try driving a servo motor using hardware PWM from my Raspberry Pi 3B + together with Node JS library node-rpio. I will explain here, how I have done it because there is no good summary for me on this topic now on the internet.
The hardware and software used
- Raspberry PI3b+
- Servo 6g TBD....
- Debian TBD
- Nodejs TBD
- node-rpio library https://www.npmjs.com/package/rpio
Theory
https://www.js4iot.com/2021/05/30/HardwarePWM-RPIO.html there is explained the theory of PWM( Pulse With Modulation).
Nice description how the servos work can be found here: https://www.jameco.com/Jameco/workshop/Howitworks/how-servo-motors-work.html
The Servo motor works on pwm signals long 20ms/50Hz. You must set up your pwm in the Raspberry Pi with the rpio library. The hardware pwm module has 2 modes
- balanced mode - spreads the up and down signasls across the whole cycle Rt uniformly by its smallest units tmin. This is better for audio signals or for LED dimming.
- mark-space mode - that keeps first part Ut of signal up, and the rest of the cycle Rt down. This perfect for controlling the servos. This is the mode enabled by the rpio library and is the only supported by this library.
\[ t_{min} = {D \over (19.2 \times 10^6)}\ [s] \]
\[ U_t = 300 \times t_{min} = 300 \times {128 \over {19.2 \times 10^6} } = 0.002\ [s] = 2\ [ms] \]
Connecting the RPi 3B+
Connect the raspberry according to the following diagram
(Fritzing)
Setting up the Raspberry Pi3B+
- First modify the /boot/config.txt of the raspberry by adding the line
- For some reason the node-rpi does not enable the pwm automatically. You may enable it using the following script. What exactly is needed is still subject of investigation. However, create the following script and execute it:
$ cat /usr/local/bin/enable_pwm.sh
#!/bin/sh
cd /sys/class/pwm/pwmchip0
echo 0 > export
echo 10000000 > pwm0/period
echo 5000000 > pwm0/duty_cycle
echo 1 > pwm0/enable
- Create a systemd service to start the above script after reboot so you don't need to run it every reboot.
# cat /etc/systemd/system/enable_pwm.service
[Unit]
Description=Enable PWM Module
Wants=dev-pwmchip0.device
After=dev-pwmchip0.device
[Service]
Type=oneshot
ExecStart=/usr/local/bin/enable_pwm.sh
RemainAfterExit=Yes
[Install]
WantedBy=multi-user.target
The simple testing node.js program
Experiments with the program
References
- https://www.npmjs.com/package/rpio the rpio library
- https://www.js4iot.com/2021/05/30/HardwarePWM-RPIO.html there is explained the theory of PWM( Pulse With Modulation)


Comments
Post a Comment