The General Purpose Input/Output pins (GPIO) give you power to interact with the real world using your Raspberry Pi. This project will get you comfortable with using the GPIO pins, which will form the backbone of the final project.
Traditionally the ‘Hello World’ program for electronics prototyping is simply turning a light on and off. We’re going to go one better than that here though, by simulating candlelight.
To do this we’re going to use the Random and Time modules from Python’s standard library to continually change the brightness of the light while using the RPi-GPIO library to control the LED with Pulse Width Modulation (PWM).
What you’ll need
Small LED (any colour)
2x male-to-female prototyping cables
Step 01 Prepare your circuit
Before we turn on our Raspberry Pi we’ll make all the physical cable connections to it. This requires us to place a male-to-female cable on the first ground pin on the GPIO port and another male-to-female cable on the PWM pin (pin 18). Connect it to the breadboard along with the LED and resistor as shown, ensuring the short leg of the LED goes to ground.
Step 02 Power up the Pi
With the circuit complete we can power up the Pi. Open Leafpad and we’ll start creating the script (found to the right) we need to control the LED light. The first thing we do is import the modules we need. The RPi.GPIO library is key to our project – we use it to read and write to pins and control their functionality. We’re also using Random and Time modules in order to help simulate the effect of candlelight.
Step 03 Configure the GPIO module
Next we assign a name to the LED pin and set up the GPIO module for our project. Notice we’re using ‘setmode’ and calling it BCM. This means we’re using the Broadcom naming scheme. We then assign the LED pin to OUTPUT, which means we’ll be outputting to that pin (as opposed to reading from it). If we simply wanted to turn the light on and off, at this point we could use GPIO.output(led,GPIO. HIGH) and GPIO.output(led,GPIO.LOW). Instead we’re using PWM, so we assign a variable PWM to control it.
Step 04 Basic functions
Next we create two very basic functions that we can call in our main program loop to randomly control the physical brightness of the LED and the amount of time that the light pauses on a set brightness. To do this we first use the random.randint method. The numbers 5 and 100 represent the lowest and highest brightness (in per cent) – the function will then pick a number between these percentages during each loop through the program. random.random picks a floating point number between 0 and 1 – we divide this by WIND to help achieve our flicker effect.
Step 05 The main loop
Finally, we use a while loop to activate the light with PWM and then change the brightness of the light with the ChangeDutyCycle method, which calls our brightness function. We do similar with time.sleep next to get the brightness to maintain for a short, random, amount of time by calling the flicker function. When we want to quit this otherwise infinite loop, we can raise a KeyboardInterrupt by pressing Ctrl+C. When we do, we need to free up the pins so that they can be used again, by calling pwm.stop and GPIO.cleanup respectively.
Step 06 Test your project
Once your script has been written, save it as candle_light.py. The ‘.py’ informs your Pi that this is a Python script. To run it, simply open the Terminal and type the following:
sudo python candle_light.py
You need to call sudo here since you need to have admin privileges to access the GPIO port on your Raspberry Pi. Assuming you’ve set up the breadboard and copied the script correctly, your LED light should start flickering as if it’s a candle in a light breeze. Take some time to experiment with the variables in the brightness and flicker functions to achieve a more desirable effect.
Full code listing
#!/usr/bin/env python # Import the modules used in the script import random, time import RPi.GPIO as GPIO # Assign the hardware PWM pin and name it led = 18 # Configure the GPIO to BCM and set it to output mode GPIO.setmode(GPIO.BCM) GPIO.setup(led, GPIO.OUT) # Set PWM and create some constants we'll be using pwm = GPIO.PWM(led, 100) RUNNING = True WIND = 9 def brightness(): """Function to randomly set the brightness of the LED between 5 per cent and 100 per cent power""" return random.randint(5, 100) def flicker(): """Function to randomly set the regularity of the'flicker effect'""" return random.random() / WIND print "Candle Light. Press CTRL + C to quit" # The main program loop follows. # Use 'try', 'except' and 'finally' to ensure the program # quits cleanly when CTRL+C is pressed to stop it. try: while RUNNING: # Start PWM with the LED off pwm.start(0) # Randomly change the brightness of the LED pwm.ChangeDutyCycle(brightness()) # Randomly pause on a brightness to simulate flickering time.sleep(flicker()) # If CTRL+C is pressed the main loop is broken except KeyboardInterrupt: running = False print "nQuitting Candle Light" # Actions under 'finally' will always be called, regardless of # what stopped the program (be it an error or an interrupt) finally: # Stop and cleanup to finish cleanly so the pins # are available to be used again pwm.stop() GPIO.cleanup()