PostHeaderIcon Raspberry Pi Robot – Flashing LEDs – The Code

Below you will find the example Python code that we will be using to flash the two LEDs that we wired up in the previous post.

 

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(16, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)

GPIO.output (16, True)
time.sleep(1.5)
GPIO.output (16, False)

GPIO.output (18, True)
time.sleep(1.5)
GPIO.output (18, False)

GPIO.cleanup()

 

The first two lines of code are to import the Raspberry Pi module and the Time modules to enable us to use the Raspberry Pi and Time related specific functions.

The next line is to set the GPIO pinouts up.  Since we are using the standard Raspberry Pi pinouts we just set this as BOARD.

After that we will define which of the Raspberry Pi GPIO pins we will be using as output pins.  As you may remember from the previous post we will be using pins 16 and 18.

The next block of code will send power to pin 16, wait for one and a half seconds before turning the power off again.  These few lines of code will therefore light our red LED for one and a half seconds before turning it off.

The final block of code is exactly as above but it will light our green LED for one and a half seconds before turning it off.

Finally we will run GPIO.cleanup() which will turn off the pins we have been using and return them back to the default state for next time we want to use them.

Once you have got your code typed up and saved as LEDs.py from within a terminal prompt run the following command and watch your LEDs light up in turn for one and a half seconds.

 

sudo python LEDs.py

 

That is all for this post if you have any issues with this code please leave a comment below.

Leave a Reply