Accessing GPIO pinsusing Python
a. Installing GPIO Zero library.
First, update your repositories list:
sudo apt update
Then install the package for Python
sudo apt install python3-gpiozero
b. Blinking an LED connected to one of the GPIO pin
c. Adjusting the brightness of an LED Adjust the brightness of an LED (0 to 100,
where 100 means maximum brightness) using the in-built PWM
wavelength.
3.
b. Blinking anLED connected to one of the GPIO pin
Hardware Required
Raspberry Pi
LED
220Ω or 330Ω resistor
Breadboard and jumper wires
Circuit:
LED positive (+) → GPIO17
LED negative (–) → 220 Ω resistor → GND
6.
Program
from gpiozero importLED
from time import sleep
led = LED(17)
while True:
print("LED ON")
led.on()
sleep(1)
print("LED OFF")
led.off()
sleep(1)
7.
Line of CodeExplanation
from gpiozero import LED Imports the LED class from the GPIO Zero library.
from time import sleep Imports the sleep() function,
led = LED(17) Creates an LED object connected to GPIO pin 17.
while True: Starts an infinite loop so the program keeps running until it is stopped.
led.on() Turns the LED ON by sending a HIGH signal to GPIO pin 17.
sleep(1) Waits for 1 second while the LED remains ON.
led.off() Turns the LED OFF by sending a LOW signal to GPIO pin 17.
sleep(1) Waits for 1 second while the LED remains OFF. Then the loop repeats.
8.
GPIO Zero library:
LEDclass
led.on() → Turns the LED ON.
led.off() → Turns the LED OFF.
led.toggle() → Changes the LED state (ON to OFF or OFF to ON).
led.blink() → Makes the LED blink automatically.
9.
c) Adjusting thebrightness of an LED Adjust the brightness of an LED (0 to 100, where 100 means
maximum brightness) using the in-built PWM wavelength.
from gpiozero import PWMLED
from time import sleep
# Connect LED to GPIO 18
led = PWMLED(18)
while True:
# Increase brightness
for i in range(0, 101, 10):
led.value = i / 100
print(f"Brightness: {i}%")
sleep(0.5)
# Decrease brightness
for i in range(100, -1, -10):
led.value = i / 100
print(f"Brightness: {i}%")
sleep(0.5)