Getting started with electronics: LEDs and switches using Raspberry Pi

By Simon Monk. Posted

In this tutorial, you will learn how to make two simple projects that use LEDs and push-button switches that are controlled by a Python program running on your Raspberry Pi. The first project uses an RGB (red, green, blue) LED to interface to the popular Cheerlights project. Cheerlights (cheerlights.com) allows users all over the internet to set each other’s LEDs to different colours just by tweeting. The second project is a reaction timer using LEDs and push-buttons to test the speed of your reactions.

Install the code and run Mu on Raspberry Pi

Before fetching the code from the internet, you should run Mu, which you will find in the Programming section of your main menu. If it’s not there, update your system to the latest version of Raspbian (magpi.cc/raspbianupdate).

Running Mu ensures that the mu_code directory is created, into which we will now copy the program code. To do this, open a Terminal window and run the commands:

wget http://monkmakes.com/downloads/pb1.sh

sh pb1.sh
This will copy the programs used in this tutorial into the mu_code directory, along with some other programs.

You'll need

  • The Mu Python editor

  • Solderless breadboard

  • 5 × female-to-male jumper wires

  • Male-to-male jumper wire

  • 2 × red LEDs

  • RGB common cathode LED

  • 3 × 470 Ω resistors

  • 2 × tactile push-buttons

Note: These components are all included in a MonkMakes kit.

Place the components onto a breadboard

Using Figure 1 as a reference, push the component legs into the breadboard at the positions shown. Bend the resistor legs so that they fit into the holes.

Each hole in a row of five holes on the breadboard is connected together under the plastic. So, its very important to get the right row for your component leg.

The resistors can go either way around, but the RGB LED must go the right way around, with its longest leg to row 2 (the one without a resistor). The push-button used in the MonkMakes kit has just two legs, but many similar buttons have four legs. If you have a four-legged version, put it on the breadboard in the orientation that leaves just one free row between the pins. You will also need to place a linking male-to-male jumper wire between rows 2 and 10.

Figure 1 The Cheerlights wiring diagram

Connect breadboard to Raspberry Pi

Again, using Figure 1 as a reference, connect the GPIO pins on the Raspberry Pi to the breadboard. A GPIO template will make this easier – if you don’t have one, you will need to carefully count the pin positions. It doesn’t matter what colour jumper leads you use, but if you stick to the colours used in the diagram, it’s easier to check that your wiring is correct.

Running the program

To use this project, your Raspberry Pi must be connected to the internet. Load and run the program 04_cheerlights.py using Mu. After a few seconds, the LED will automatically set itself to the current Cheerlights colour, checking every ten seconds. Pressing the button will turn the LED off until the Cheerlights colour changes.

Click here to download the code

# 04_cheerlights.py
# From the code for the Box 1 kit for the Raspberry Pi by MonkMakes.com

from gpiozero import Button, RGBLED
from colorzero import Color
import time, requests

update_period = 10 # seconds
led = RGBLED(red=18, green=23, blue=24)
button = Button(25)

cheerlights_url = "http://api.thingspeak.com/channels/1417/field/2/last.txt"
old_color = None

def pressed():
    led.color = Color(0, 0, 0)  # LED off
button.when_pressed = pressed

while True:
    try:
        cheerlights = requests.get(cheerlights_url)
        color = cheerlights.content             # the color as text
        if color != old_color:
            led.color = Color(color)            # the color as an object
            old_color = color           
    except Exception as e:
        print(e)
    time.sleep(update_period)           # don't flood the web service

Tweet a new colour

Now that your Raspberry Pi is looking out for changes to the Cheerlights colour, anyone can simply send a tweet mentioning @cheerlights and the name of a colour; your LED should then change to that colour. You can test this out by sending a tweet such as ‘@cheerlights red’ and after a few seconds your LED should change colour. You will find that after a few minutes, the colour probably changes as someone else sets the Cheerlights colour.

A schematic diagram of the Cheerlights project
  1. The RGB LED is actually three LEDs in one: red, green, and blue. Changing the power going to each LED (controlled by a separate GPIO pin) changes the overall colour.

  2. GPIO 24 acts as an output. Current flows out of GPIO 24, through the resistor, through the blue LED and back to Raspberry Pi’s GND (ground connection).

  3. An LED will draw as much current as it can, so each LED needs a resistor to reduce the current, protecting the LED and/or the GPIO pin of Raspberry Pi.

  4. When the switch is pressed, it connects GPIO pin 25 (acting as an input) to GND (0V).

  5. An internal pull-up resistor keeps GPIO 25 at 3.3 V until the switch is pressed – that overrides the effect of the resistor, making GPIO 25 0 V. Without this, GPIO 25 would be a floating input liable to false triggering from electrical noise.

Build a reaction timer

First, pull the jumper leads off the GPIO pins on the Raspberry Pi and then pull all the components and wires off the breadboard so that it is ready for the next project.

Dismantle the breadboard and place the new components

This time, using Figure 2 as a guide, push all the component legs into the breadboard at the positions shown. It doesn’t matter which way round the resistors and buttons go, but the LEDs have a positive and negative end, so must go the correct way around. The positive end of the LED (marked ‘+’ on the diagram) is the longer leg and this should go to the same row on the breadboard as the resistor.

Figure 2 The Reaction Timer wiring diagram

Connect breadboard to Raspberry Pi

Using Figure 2 as a reference, connect the GPIO pins on the Raspberry Pi to the breadboard using five female-to-male jumper wires.

Running the program

To use the reaction timer, load and run the program 07_reactions.py in Mu. When the program starts, you will notice that the bottom part of the Mu window shows a message telling you to ‘Press the button next to the LED that lights up’ (Figure 3).

After a random amount of time, one of the LEDs will light, and you should press the button next to that LED as quickly as possible. You will then get a message telling you how many milliseconds you took to press the button.

The code includes checks to make sure you don’t try to cheat by pressing both buttons at once, or pressing the buttons before an LED has lit.

# 07_reactions.py
# From the code for the Box 1 kit for the Raspberry Pi by MonkMakes.com

from gpiozero import LED, Button
import time, random

left_led = LED(25)
right_led = LED(23)
left_switch = Button(24)
right_switch = Button(18)

# find which buttons pressed 0 means neither, -1=both, 2=right, 1=left
def key_pressed():
    # if button is pressed is_pressed will report false for that input
    if left_switch.is_pressed and 
right_switch.is_pressed:
        return -1
    if not left_switch.is_pressed and not 
right_switch.is_pressed:
        return 0
    if not right_switch.is_pressed and 
left_switch.is_pressed:
        return 1
    if right_switch.is_pressed and not 
left_switch.is_pressed:
        return 2

while True:
    left_led.off()
    right_led.off()
    print(
"Press the button next to the LED that lights up")
    delay = random.randint(3, 7)            # random delay of 3 to 7 seconds
    led = random.randint(1, 2)              # random led left=1, right=2
    time.sleep(delay)
    if (color == 1):
        print("left")
        left_led.on()
    else:
        print("right")
        right_led.on()
    t1 = time.time()
    while not key_pressed():
        pass
    t2 = time.time()
    if key_pressed() != led :               # check the correct button was pressed
        print("WRONG BUTTON")
    else:
        # display the response time
        print("Time: " + str(int((t2 - t1) * 1000)) + " milliseconds")


https://simonmonk.org

From The MagPi store

Subscribe

Subscribe to the newsletter

Get every issue delivered directly to your inbox and keep up to date with the latest news, offers, events, and more.