For controlling the Raspberry Pi GPIO pins, our tutorial uses the GPIO Zero library.
If users have used the RPi.GPIO library and wirinPi library before, they will find that the GPIO Zero library and the RPi.GPIO library/wirinPi library handle pins differently:
Driver library | Control pin mode |
---|---|
GPIO Zero Library | Device Class: LED (Output) |
RPi.GPIO library/wirinPi library | Output status |
The GPIO Zero library has more control methods associated with the device, while the RPi.GPIO library and wirinPi library control pins directly.
In the GPIO Zero library, we can use the LED interface to control the PWM output of the pin.
Control BCM pin number 17PWM output: Manually set brightness
xfrom gpiozero import PWMLED
from time import sleep
led = PWMLED(17)
while True:
led.value = 0 #off
sleep(1)
led.value = 0.5 # half brightness
sleep(1)
led.value = 1 # full brightness
sleep(1)
led.value = 0.5 # half brightness
sleep(1)
led.value = 0 #off
sleep(1)
Control BCM pin number 17PWM output:
xxxxxxxxxx
from gpiozero import PWMLED
from signal import pause
led = PWMLED(17)
led.pulse(3,1)
pause()
led.pulse can set the fade-in and fade-out time: in the code, it takes 3 seconds from off to on (fade in), and 1 second from on to off (fade out) (if no parameters are used, the default is 1 second).