Sunday 21 December 2014

Getting to grips with GPIO

As GPIO is going to be a big part of this project, I wanted to learn a bit more about the library before I start the project for real. The next step was to mess around with a single LED and a couple of buttons to see if I could get them to do fun stuff like changing the flash rate or brightness.  After a bit of messing about and falling foul of the wait_for_edge bug in the GPIO library, I eventually settled on thread based callbacks (another first for me).  I'll spare you the gory details of all the intermediate version of the code, but this script has an LED/resistor attached to GPIO 11 and two switches on 20/21 to act as up and down buttons:




#!/usr/bin/python
import RPi.GPIO as GPIO

# Set the numbering scheme to GPIO numbers
GPIO.setmode(GPIO.BCM)
# LED on GPIO 11, initiall set to off
GPIO.setup(11, GPIO.OUT, initial=GPIO.LOW)
# UP switch on GPIO 20
GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# DOWN switch on GPIO 21
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Set dutycycle to 50%
dc = 50
# Set inital flash frequency to 20Hz
freq = 20

# Create a callback function
def set_freq(gpio_id):
  global freq
  global led

  # If the up switch is pressed, increment freq
  if gpio_id == 20:
    if freq < 50:
      freq += 1
      print "Up switch pressed. Setting freq to %s" % freq
    else:
      print "Up switch pressed. Frequency already at max value!"
  if gpio_id == 21:
    if freq > 1:
      freq -= 1
      print "Down switch pressed. Setting freq to %s" % freq
    else:
      print "Down switch pressed. Frequency already at min value!"
  led.ChangeFrequency(freq)

# Set up the LED
led = GPIO.PWM(11,freq)
led.start(dc)

# Add callbacks for both switches, using the same  callback
# The callback function will be notified which GPIO pin is falling
GPIO.add_event_detect(20, GPIO.FALLING, set_freq, bouncetime=200)
GPIO.add_event_detect(21, GPIO.FALLING, set_freq, bouncetime=200)

try:
  # Wait for a key press
  entry = raw_input("Press something fool!\n")
except KeyboardInterrupt:
  print "Except that!!!"

led.stop()
GPIO.cleanup()

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home