How to turn on a LED with a Raspberry Pi

By | October 2, 2015

I have been wanting to do this for quite some time but had absolutely no idea how it was even possible. But with the power of the internet and lots of background reading, I managed to turn on and off an LED that was connected to the GPIO pins of my raspberry pi.

This blog was inspired by: http://visualgdb.com/tutorials/raspberry/LED/

Step 1: Get an LED

LEDThis can be a bit tricky if you don’t have the gear. You’ll need an LED, a resistor of around 100Ω-500 Ω, soldering wire and a soldering iron and some metal terminations. It’s important to make sure you reduce the risk of shorting the GPIO pins on the raspberry pi at all cost. Unless you can afford to buy another one.

Note that the longer leg of the LED is the +ve and the shorter leg is -ve.

Step 2: Know your GPIO pin configurations

53bc258dc6c0425cb44870b50ab30621

Do a search on Google for “raspberry pi pin configuration” and you’ll get lots of images like the one above. With the pi powered on, connect the red end to pin 1 (3.3v) and the black end to pin 6 (GND). This should light LED continuously. This means all connectivity is good so far.

Next, I used GPIO 27 which corresponded to pin 13 for the red wire and any pin with GND can be used for the black. It doesn’t actually matter. GPIO 27 is used because this pin can be set “high”, ie send +3.3v to the pin via software.

This is what it should look like:

led with pi

led1

Now comes the fun part.

Step 3: Turning on the LED with some funky commands

Log into the pi and run this command:

sudo su
cd /sys/class/gpio
echo 27 > export
cd gpio27
echo out > direction
echo 1 > value

The last command will actually turn the LED on. To turn it off, type:

echo 0 > value

That is really all there is to it. Not that hard eh?

Step 4: Getting fancy

Kitt-67595No, I don’t mean making it blink or making Knight Rider lights.

You can put the commands into a script called turnon.sh and turn off.sh

nano turnon.sh
echo 1 > /sys/class/gpio/gpio27/value

and do the same for turnoff.sh changing the echo 1 to echo 0.

Then you can execute the script by running:

./turnon.sh

or

./turnoff.sh

See the video below to see the LED in action. You’ll have to look carefully else you’ll miss it because the LED is not super bright.

 

Leave a Reply

Your email address will not be published. Required fields are marked *