Sunday, May 28, 2017

Python to control GPIO of Raspberry Pi


It's Python example to control GPIO of Raspberry Pi, tested on Raspberry Pi 2 running Raspbian Jessie with PIXEL rel. 2017-04-10, work on both Python 2 and 3.

pyGPIO.py
import RPi.GPIO as GPIO
import time
import platform

print("Raspberry Pi board revision: "
      + str(GPIO.RPI_INFO['P1_REVISION']))
print("Python version: "
      + platform.python_version())
print("RPi.GPIO version: "
      + str(GPIO.VERSION))
print("Ctrl-C to terminate and clean up GPIO")

#mode = GPIO.BCM
#led = 21
mode = GPIO.BOARD
led = 40

GPIO.setmode(mode)
GPIO.setup(led, GPIO.OUT)

try:
    while True:
        GPIO.output(led, True)
        time.sleep(0.5)
        GPIO.output(led, False)
        time.sleep(0.5)
        GPIO.output(led, True)
        time.sleep(0.5)
        GPIO.output(led, False)
        time.sleep(2)
finally:
    print("Clean up")
    GPIO.cleanup()


Connection:


reference:
raspberry-gpio-python - RPi.GPIO module basics

Next:
Python to generate PWM on GPIO of Raspberry Pi

No comments: