Raspberry PI + Python = Blinking LED

While we wait for our components to arrive for our PIC project, let’s play with Raspberry PI.
Raspberry PI is not a microcontroller it’s fully functional computer.

Prerequisite to this topic is connected and running Raspberry PI.

Next we will need to build the same schematics as we did in our Arduino project
The only difference is that we connect black wire to #9 on Raspberry PI GPIO and white wire to #11 on Raspberry PI GPIO:

Now open your favorite Vi and type the program:

import RPi.GPIO as GPIO
import time

LED = 11

def init():
	GPIO.setmode(GPIO.BOARD)    
	GPIO.setup(LED, GPIO.OUT)   
	GPIO.output(LED, GPIO.HIGH) 

def doit():
	while True:
		GPIO.output(LED, GPIO.LOW)  
		time.sleep(1)
		GPIO.output(LED, GPIO.HIGH) 
		time.sleep(1)

def cleanup():
	GPIO.output(LED, GPIO.HIGH)     
	GPIO.cleanup()                  

if __name__ == '__main__':     
	init()
	try:
		doit()
	except KeyboardInterrupt:  # Ctrl+C
		cleanup()

save it as blink.py and start

python blink.py

You should see LED start blinking with 1 second interval. Close it by entering Ctrl+C.

We used RPi.GPIO a Python based library for Raspberry Pi to control GPIO pins. It should be installed by default, if it not just run:

sudo apt-get install python-rpi.gpio python3-rpi.gpio

We are done!

Leave a Reply