Skip to content

Lightswitch

Rolf Rander Næss edited this page Oct 29, 2015 · 5 revisions

First assignment: getting a LED to light.

The LED should really be connected in series with a resistor to protect the LED, but I don't have one, so I just connected the anode to pin 18 and the cathode to ground. (Remember that current, by definition, only flows one way through a diode. Connect the longest connector, the anode, to plus).

There are lots of tutorials available showing basic python code for setting up and controlling the GPIO-pins. However, I have wrapped these in some basic object orientation to make the code a bit nicer to work with. Using the pi-library in this project, you can control a LED like this:

import pi
import time

led = pi.DigitalOutput(18)

led.on()
time.sleep(3)
led.off()

Second assignment: switch

So we have output working, how about input? For reading a digital bit, connect a voltage (1) or ground (0) to an input-pin. Do this with a switch, and you have an input-device. However, due to details of electricity, you don't know the state of a pin that is not connected anywhere, so you use a trick called a pull-up resistor to make sure that the pin is either connected to a voltage or ground. The Pi controller comes with pull-up or pull-down built in. My DigitalInput-class configures input-pins with a pull-up resistor, which means that if the switch is connected, the value is 0.

The RPi.GPIO-module can read changes in input either asynchronously (calling a function when there is a change) or synchronously (blocking until there is a change). This code shows the asynchronous operation:

class MyButton(pi.DigitalInput):
    def __init__(self, pin):
        super(MyButton, self).__init__(pin)
        self.i=0

    def down(self):
        self.i=self.i+1
        print self.i

    def up(self):
        pass

button = MyButton(22)

try:
    while True:
        time.sleep(0.01)

except KeyboardInterrupt:
    # CTRL+C is pressed, exit cleanly
    pi.cleanup()

This increases a counter each time the button is pressed and prints the current value. Note that sometimes a push is counted twice, read up on contact bounce for the details.

Third assignment: controlling the led with the switch

These two can be combined, letting the event-handler of the switch control the led:

import pi
import time

class MyButton(pi.DigitalInput):
    def __init__(self, pin, output):
        super(MyButton, self).__init__(pin)
        self.i=0
        self.output=output

    def down(self):
        self.i=self.i+1
        self.output.toggle()
        print self.i

    def up(self):
        pass

led = pi.DigitalOutput(18)
button = MyButton(22, led)

try:
    while True:
        time.sleep(0.01)

except KeyboardInterrupt:
    pi.cleanup()

Clone this wiki locally