script:
pi@raspberrypi:~/Development $ cd~
pi@raspberrypi:~ $ python3 fade.py
8. Your LED should now be fading up and down!
9. Press Ctrl-C to stop the script and return to the command
line.
If you’re accustomed to using PWM on a microcontrol-
ler like the Arduino, you’ll find that—unlike Arduino—
there is unsteadiness in the PWM pulses from the Rasp-
berry Pi. This is because in this example, you’re using
the CPU to turn the LED on and off. Because that CPU is
used for multiple things at one time, it may not always
keep perfect time. You can always reach for other hard-
ware like Adafruit’s PWM/Servo Driver (www.adafruit.
com/products/815) if you need to have more precise
control.
Taking PWM Further
With the ability to use pulse-width modulation to fade LEDs up and
down, you could also connect an RGB LED and control the color
by individually changing the brightness of its red, green, and blue
elements.
As we mentioned earlier, you can also use pulse-width modulation
to control the speed of a direct current motor that’s connected to
your Raspberry Pi through transistors. The PWM output, when fed
into the transistors, will modulate the amount of power the transis-
tors allow into the motor, and hence its speed.
The position of the shaft on a hobby servo motor (the kind that-
steers RC cars) can also be controlled with specific pulses of elec-
tricity. Though, keep in mind that you may need additional hard-
ware and power to control these motors with a Raspberry Pi.
Analog Input and Output 127
GSW_RASPI_4ED_FIN.indd 127GSW_RASPI_4ED_FIN.indd 127 10/28/21 10:54 AM10/28/21 10:54 AM