GPIO python examples
Project configuration
Give access to gpio
chmod 777 -R /sys/class/gpio
Install prerequisite packages
apt-get install python3-venv
Create new python environment
mkdir pin_blink
cd pin_blink
python3 -m venv
source bin/activate
Install required library called gpio
python3 -m pip install gpio
1. Blink led
import time
import gpio
GPIO_PINS = {
"GPIO1_B1": 41,
"GPIO4_C3": 147,
"GPIO0_A0": 0,
"GPIO0_B7": 15,
"GPIO0_C4": 20,
"GPIO0_C7": 23,
"GPIO1_B2": 42
}
# GPIO pin number
pin = GPIO_PINS['GPIO1_B1']
blink_time = 0.5
# Set pin as output
pin_obj = gpio.GPIOPin(pin, gpio.OUT)
# Blink LED
while True:
pin_obj.write(gpio.HIGH)
time.sleep(blink_time)
pin_obj.write(gpio.LOW)
time.sleep(blink_time)
2. Read button state
import time
import gpio
GPIO_PINS = {
"GPIO0_A6": 6,
"GPIO1_B1": 41,
"GPIO4_C3": 147,
"GPIO0_A0": 0,
"GPIO0_B7": 15,
"GPIO0_C4": 20,
"GPIO0_C7": 23,
"GPIO1_B2": 42
}
# GPIO pin number
pin = GPIO_PINS['GPIO0_A6']
polling_time = 0.5
# Set pin as input
pin_obj = gpio.GPIOPin(pin, gpio.IN)
last_state = pin_obj.read()
while True:
current_state = pin_obj.read()
if(current_state != last_state):
last_state = current_state
print("State changed to: " + str(current_state))
time.sleep(polling_time)