Wednesday, May 1, 2013

Lighting LEDs on the Raspberry Pi with Python

There are many tutorials available for this already, but I just wanted to collect my observations into a series of steps that I can repeat later.

For reference, I used raspberry-gpio-python, Raspberry Leaf, and How to use your Raspberry Pi like an Arduino.

I connected an LED and an inline resistor to GPIO pin 7 and ground, one side of a momentary pushbutton to ground, and the other side of the pushbutton to a 1 kOhm resistor connected to 3.3 V.

Starting from a fresh install of Raspbian, at the command line (or in LXTerminal) input the following -commands: (edit: the crossed-out commands aren't really necessary)

sudo apt-get update
sudo apt-get install python
sudo apt-get install python-dev
sudo python distribute_setup.py
sudo easy_install pip
sudo apt-get install python-rpi.gpio

sudo python


#!/usr/bin/env python
from time import sleep
import os
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

# define the pins we're using
button1 = 4
LED = 7

set up the pins
GPIO.setup(button1, GPIO.IN)
GPIO.setup(LED, GPIO.OUT)

# turn on the LED
GPIO.output(LED, True)
# wait for half a second
sleep(0.5)
# turn off the LED
GPIO.output(LED, False)
# toggle the LED
GPIO.output(LED, not GPIO.input(4))

# set up some variable to read from the button
input = False
previousInput = True

# loop
while True:
 # read the button state to the variable input
 input = GPIO.input(button1)
 # make sure the button state isn't what it used to be
 if ((not previousInput) and input):
  print("button pushed")
 # copy the button state to the previousInput variable
 previousInput = input
 # wait to "debounce" the input
 sleep(0.05)

# clean things up
GPIO.cleanup()

No comments: