The MagPi Issue 3

Page 9

When you have had enough press the CTRL+C keys to stop the program. Having the LED light up when the switch is pressed is not terribly useful as it just gives us the same result that we had before when the LED was directly connected to the switch. Let’s make something a bit more interesting.

Electronic Die Because the LED and switch are now independent, we have a great deal more flexibility. We will now write a program that will flash a random number between 1 and 6 when the button is pressed. #!/usr/bin/python import RPi.GPIO as GPIO import time import random GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.IN) GPIO.setup(12, GPIO.OUT)

Program Description The program runs a continuous while loop waiting for the button to be pressed. Once the button press is detected we generate a random integer value between 1 and 6. An integer means a whole number rather than a floating point number, so we get numbers like 2 and 3 rather than 2.45678. Once the random number has been generated, we wait for the button to be released before continuing, to prevent cheating. When the button is released we enter a countdown loop that flashes the LED and reduces the count by 1 after each flash, until it reaches 0. The program then returns to the main loop where it waits for the next button press to start the process again.

Conclusion

while True: if not GPIO.input(11): flash = random.randint(1,6) while not GPIO.input(11): GPIO.output(12, True) while flash > 0: GPIO.output(12, False) time.sleep(.5) GPIO.output(12, True) time.sleep(.5) flash ­= 1 else: GPIO.output(12,True)

We have now covered the basics of how to monitor an input and switch things on and off using an output. With just this simple set-up of one switch and one LED we can already make something useful. Why not try modifying the pushbutton.py program so that the LED is on but goes off when the button is pressed. There is more than one way of doing it. Can you see two or more possibilities? Many people have asked about how to control something that requires more power than a small LED. In the next instalment we will look at the various options available. I

This article is sponsored by Tandy.

All the components mentioned in this series and much more are available from the new Tandy online shop. Many new components being added daily.

9


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.