RGB-LED Lesson 0 – The Absolute Basics GPIO
This lesson is directly based on the supplied material contained within the User Manual of the RGB-LED Kit.
If you have the kit and have already completed the manual, then you may wish to skip to the bottom and try the “extra credit” exercises and move onto Lesson 1.
Basic Programming:
Within these instructions, we shall only cover some very basic programming, more detailed examples and tutorials will be made available from the “Meltwater Raspberry Pi Hardware” site (https://pihw.wordpress.com/) in the learning section.
It is highly recommended that you take the time to type coding examples in yourself (even if the source is available). By doing so you will become familiar with the syntax and format of the commands and you will learn it far quicker than if you cut and pasted it.
Setup:
Hardware Connections:
Unless specified otherwise, the guides and tutorials will assume you have your board wired up as follows (although we should always aim to make it easy in our programs to adapt the wiring if required).
See the photo for the correct orientation of the GPIO Port (P1) depending on the Raspberry Pi model you own.
SD Card Image:
The guides will assume a clean, up to date system image. To obtain the latest Raspbian “wheezy” SD Card image, and for details on how to write it to your SD Card see the Raspberry Pi Homepage download section (http://www.raspberrypi.org/downloads).
At the time of writing, the latest image is 12-12-16-wheezy-raspbian. Please refer to the following Adafruit guides on writing your SD-Card (http://goo.gl/Rht2v) and setting up a Raspberry Pi for the first time (http://goo.gl/Gf2f5) if you need help.
Using Bash (controlling LEDs using basic scripting):
First we will write a short program script using Bash. Bash is a common shell used with Linux, it allows you to write basic commands, and importantly for us to write and run scripts (a long list of commands).
The example here only shows controlling one LED but hopefully if you look at it carefully you can see how to extend it to control more than one (and perhaps how to produce different colours).
Create the file by typing the following from the terminal (command prompt) on your Raspberry Pi.
nano rgbledtest.sh
Type in the following script and then save and exit (Ctrl+x,y and enter).
Run the script:
sudo bash rgbledtest.sh
If you get any errors, then use nano again and examine your script for errors.
Script: rgbledtest.sh
#!/bin/sh # Bash uses BCM GPIO numbers (i.e. the pin names of the Broadcom Chip itself) # These are detailed in the Raspberry Pi wiki pages. # Therefore to make life easier we will map them to the Raspberry Pi GPIO # Pin Numbers. PIN12=18 PIN16=23 PIN18=24 PIN22=25 PIN7=4 PIN11=17 PIN13_REV1=21 PIN13_REV2=27 PIN15=22 #Setup Pins LED01=$PIN12 LED02=$PIN16 LED03=$PIN18 LED04=$PIN22 LED05=$PIN7 LED_RED=$PIN11 LED_GREEN=$PIN13_REV2 #Rev2.0 (Ensure you use correct one for your board) LED_BLUE=$PIN15 #Setup Active states #Common Cathode RGB-LEDs (Cathode=Active Low) LED_ENABLE=0 LED_DISABLE=1 RGB_ENABLE=1 RGB_DISABLE=0 #Set up GPIO to Outputs # Set up GPIO Pin, to output and put in disable state echo "$LED01" > /sys/class/gpio/export echo "$LED_RED" > /sys/class/gpio/export echo "$LED_GREEN" > /sys/class/gpio/export echo "$LED_BLUE" > /sys/class/gpio/export echo "out" > /sys/class/gpio/gpio$LED01/direction echo "out" > /sys/class/gpio/gpio$LED_RED/direction echo "out" > /sys/class/gpio/gpio$LED_GREEN/direction echo "out" > /sys/class/gpio/gpio$LED_BLUE/direction echo "$LED_DISABLE" > /sys/class/gpio/gpio$LED01/value echo "$RGB_DISABLE" > /sys/class/gpio/gpio$LED_RED/value echo "$RGB_DISABLE" > /sys/class/gpio/gpio$LED_GREEN/value echo "$RGB_DISABLE" > /sys/class/gpio/gpio$LED_BLUE/value # Setup End ############################################################ #Switch on LED with RED/GREEN/BLUE echo "$RGB_ENABLE" > /sys/class/gpio/gpio$LED_RED/value echo "$RGB_ENABLE" > /sys/class/gpio/gpio$LED_GREEN/value echo "$RGB_ENABLE" > /sys/class/gpio/gpio$LED_BLUE/value echo "$LED_ENABLE" > /sys/class/gpio/gpio$LED01/value #Wait sleep 1s #Switch each LED off echo "$LED_DISABLE" > /sys/class/gpio/gpio$LED01/value echo "$RGB_DISABLE" > /sys/class/gpio/gpio$LED_RED/value echo "$RGB_DISABLE" > /sys/class/gpio/gpio$LED_GREEN/value echo "$RGB_DISABLE" > /sys/class/gpio/gpio$LED_BLUE/value ############################################################ # Clean Up echo "$LED01" > /sys/class/gpio/unexport echo "$LED_RED" > /sys/class/gpio/unexport echo "$LED_GREEN" > /sys/class/gpio/unexport echo "$LED_BLUE" > /sys/class/gpio/unexport #End
Script Details:
By using the = sign we are able to assign values to “variables”, this gives us an easy way to make our script easy to modify (for instance if we change the wiring). To reference a “variable” the $ sign is used, this tells Bash to look for a variable and put whatever it is value is in its place.
For instance:
PIN12=18 LED01=$PIN12
Is the same as:
LED01=18
The script includes the mapping for all the pins used by the RGB LED board, so you can continue to set-up the rest of the pins and try the other LEDs.
To use a GPIO pin in Bash, you have to do the following:
1. Export the pin number:
echo "$LED01" > /sys/class/gpio/export
2. Set the direction of the pin (input = “in” or output = “out”):
echo "out" > /sys/class/gpio/gpio$LED01/direction
3. Initialise it to a safe/default state:
echo "$LED_DISABLE" > /sys/class/gpio/gpio$LED01/value
4. Use it, by setting it to a value 0 or 1:
echo "$LED_ENABLE" > /sys/class/gpio/gpio$LED01/value
5. Return it to a safe/default state (not required but good practise):
echo "$LED_DISABLE" > /sys/class/gpio/gpio$LED01/value
6. Release the pin when you are done with it:
echo "$LED01" > /sys/class/gpio/unexport
Finally, we use sleep to provide a 1s (1 second) delay between actions.
That covers the very basics! I’ll extend this example and demonstrate some additional methods next time.
Using Python (controlling LEDs using RPi.GPIO):
Before you start you will need to ensure you have the latest RPi.GPIO library installed.
To do this, connect your Raspberry Pi to the internet and run the following commands from the terminal:
sudo apt-get update sudo apt-get install python-dev python-rpi.gpio
As for the bash example above, create the file by typing the following from the terminal (command prompt) on your Raspberry Pi.
nano rgbledtest.py
Type in the following script and then save and exit (Ctrl+x, y and enter).
Run the script:
sudo python rgbledtest.py
If you get any errors, then use nano again and examine your script for errors.
Script: rgbledtest.py
#!/usr/bin/python import time import RPi.GPIO as GPIO # RGB LED Module (TEST) #Setup Active states #Common Cathode RGB-LEDs (Cathode=Active Low) LED_ENABLE = 0 LED_DISABLE = 1 RGB_ENABLE = 1 RGB_DISABLE = 0 #LED CONFIG - Set GPIO Ports LED1 = 12 #B4 LED2 = 16 #B18 LED3 = 18 #B23 LED4 = 22 #B24 LED5 = 7 #B25 LED = [LED1,LED2,LED3,LED4,LED5] RGB_RED = 11 #B22 RGB_GREEN = 13 #B21 Rev1 B27 Rev2 RGB_BLUE = 15 #B17 RGB = [RGB_RED,RGB_GREEN,RGB_BLUE] def led_setup(): #Set up the wiring GPIO.setmode(GPIO.BOARD) # Setup Ports for val in LED: GPIO.setup(val, GPIO.OUT) for val in RGB: GPIO.setup(val, GPIO.OUT) def led_activate(led,colour): GPIO.output(led,LED_ENABLE) GPIO.output(colour,RGB_ENABLE) def led_deactivate(led,colour): GPIO.output(led,LED_DISABLE) GPIO.output(colour,RGB_DISABLE) def led_clear(): for val in LED: GPIO.output(val, LED_DISABLE) for val in RGB: GPIO.output(val, RGB_DISABLE) def main(): led_setup() led_clear() led_activate(LED1,RGB_RED) time.sleep(5) led_deactivate(LED1,RGB_RED) led_clear() GPIO.cleanup() main() #End
Script Details:
At the top of this file we “import” 2 libraries:
- time – which allows us to use the time.sleep() command (just like the bash script this gives us an easy way to put in delays – the value is in seconds, 0.5 would be a ½ second, 0.001 is 1ms)
- RPi.GPIO – the installed library allows python to access the GPIO pins (to use this we need to ensure we use sudo)
Next we define our pins and signals, so that as before we can quickly change things around if needed without changing in multiple places.
Now, we define 5 basic functions:
- led_setup(): This sets the pin reference and each of the pins to outputs.
- led_activate(led, colour): Basic function to switch on a specific LED and activate the specified colour.
- led_deactivate(led, colour): Function to switch the LED off again.
- led_clear(): Function to return the LEDs to a known deactivated state.
- main():This function called on start, makes calls to each of the above to setup, clear and then activate the required LED for a set period of time. It then uses GPIO.cleanup() to release the pins before exiting.
Extra Credit:
The following exercises can be performed using both Bash and Python.
To create a loop using Bash, the following code can be used:
for i in 1 2 3 4 5 6 7 8 9 10 do #write output echo "$RGB_ENABLE" > /sys/class/gpio/gpio$LED_RED/value echo "$RGB_DISABLE" > /sys/class/gpio/gpio$LED_RED/value done
To create a loop using Python, the following code can be used:
for i in range(10): led_activate(LED1,RGB_RED) time.sleep(5) led_deactivate(LED1,RGB_RED) time.sleep(1)
- Try extending each of the examples to cycle through the colours and each LED in turn.
- Try using a combination of RGB to create more colours.
[…] See RGB-LED Lesson 0 – The Absolute Basics GPIO […]
I have the RGB-LED kit and assembled it with no real trouble, for a beginner and found it most informative. However, I cannot get GREEN to work using Python, but it works correctly using Bash. Is Python assuming the wrong pin by any chance?
I would expect it the other way, working with python but not bash, since the Green pin numbers are dependent on the boards revision (rev 1 does not have mounting holes and P5 holes).
The python code should match the pin numbers of the header (regardless of the rev since we use GPIO.BOARD). Just ensure you are using up to date RPi.GPIO!
Let me know if you still have problems and I can take a closer look at your code.
I am impressed by the quality of information on this website. There are a lot of good resources here. I am sure I will visit this place again soon.
You need to fix your Bash code to use ” and > instead of " and > – the characters have been double-escaped somewhere! (in fact, I think you could probably get away with removing most of the quotes – bash has a very relaxed syntax)
Also, in your Python it’s much easier to just use:
for val in LED:
GPIO.setup(val, GPIO.OUT)
instead of:
for idx, val in enumerate(LED):
GPIO.setup(val, GPIO.OUT)
and then you won’t need to “import array” either 🙂
Doh, WordPress automatically changed & quote ; (without the spaces) into “
Thanks for spotting it and letting me know. I think the quote thing changed when I last edited the page, unfortunately WordPress does lots of nasty things to the code when you drop it in.
I’ll test without the quotes, then decide which looks clearer.
As for the python code, I was wondering that myself, and will probably remove the enumerate part as suggested (it is clear from the code used in lesson 1, that it isn’t really needed). Just a hang-up from how I was using it in some previous code (where I was using the idx value).
Thanks for the feedback, I’m always keen to keep improving things as much as possible.
All updated and hopefully corrected (found some more helpful wordpress junk inserted too)!
Hello, nice work. Can you please cite a few sources of your information please?
Are you just referring to this particular page? The tutorial has been constructed from the scripts I’ve been using for testing while making the kit, other than the basic information available on how to control the GPIO specifically on the Raspberry Pi available in the wiki pages (http://elinux.org/Rpi_Low-level_peripherals) the rest has come from general reading and understanding. If you are after more specific examples of GPIO control, then the MagPi Magazine (http://www.themagpi.com) contains lots of excellent examples.
Hope that helps.
Can I used python IDLE 3 instead of nano?
That should work fine as an editor (I even use it on my windows computer by sharing the Pi’s home directory on the network). A tip for nano users, run with “nano -c script.py” and it will give you line numbers which is helpful for debugging.
You may need to be aware of some differences between Python 3 and 2.7 which I may have missed though if you run it with Python 3 (I’ve typically used python 2.7, which will run with the “sudo python script.py” command as described).
Thanks for your response. I have updated the Pi today, which did not help. One anomaly is that Python complains about GPIO.cleanup() – no such function! Does that throw any light – ie, should I have mentioned that the first time?
no clean up function suggests that RPi.GPIO it’s out of date. Perhaps it wasn’t installed via apt-get.
Alternatively you can use the bash pin numbers with GPIO.BCM
Looks like I need to check up on RPi.GPIO. I believe that everything has been installed via apt-get. How do I delete it, prior to a re-install, because if that is wrong, it would presumably explain the problem.
Problem solved! I had a mixture of Python 2.7 and v3 installed, which means I probably updating v3 and using 2.7. I removed 2.7 and the board now works as it should using Python3, even my own attempts to construct an example. Thanks for the kit and your help – I shall look forward to your future kits.
Excellent, glad you got it working.
I’ve yet to update things for Python3, but I’ve switched to using it else-where so will be updating the examples at some point.
Thanks for the support.
Hi. I have followed your tutorial and everything is working like a dream although i must admit some of it is above me still. I just have a quick question. I have some common-annode leds. Is it possible to amend the script to allow for these? Compared to the two types i have here they appear to be a little brighter and would suit my project better. I have had a go but somehow keep tripping up.
Is this do-able?
Many Thanks
Jon
No worries the more you do and experiment the more it should make sense to you.
Yes common anode will work, simply reverse the logic. Wiring the RGB legs as before and the anodes to the LED 1, 2, 3, 4 and 5 pins.
i.e use:
LED_ENABLE=1
LED_DISABLE=0
RGB_ENABLE=0
RGB_DISABLE=1