Welcome to DOFBOT-Pi repository
7.Pin output PWM
Pin output PWM
For controlling the Raspberry Pi GPIO pins, our tutorial uses the GPIO Zero library.
1. Driver 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.
2. LED
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 PWMLEDfrom time import sleepled = PWMLED(17)while True:led.value = 0 #offsleep(1)led.value = 0.5 # half brightnesssleep(1)led.value = 1 # full brightnesssleep(1)led.value = 0.5 # half brightnesssleep(1)led.value = 0 #offsleep(1)
Control BCM pin number 17PWM output:
xxxxxxxxxxfrom gpiozero import PWMLEDfrom signal import pauseled = 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).