GPIO python examples
Project configuration
Give access to gpio
chmod 777 -R /sys/class/gpio
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 pin number
pin = 6 # GPIO0_A6
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 pin number
pin = 6 # 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)