phoenixdigital

433Mhz Pi GPIO monitor

Jan 15th, 2015
2,623
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python2.7
  2. # demo of "BOTH" bi-directional edge detection
  3. # script by Alex Eames http://RasPi.tv
  4. # http://raspi.tv/?p=6791
  5.  
  6. import RPi.GPIO as GPIO
  7. from time import sleep     # this lets us have a time delay (see line 12)
  8. from datetime import datetime
  9.  
  10.  
  11. portToUse = 27
  12. lastTime = datetime.now()
  13.  
  14. GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering
  15. GPIO.setup(portToUse, GPIO.IN)    # set GPIO as input (button)
  16.  
  17. # Define a threaded callback function to run in another thread when events are detected
  18. def my_callback(channel):
  19.     global lastTime
  20.     nowTime = datetime.now()
  21.     delta = nowTime - lastTime
  22.     lastTime = nowTime
  23.  
  24.     if GPIO.input(portToUse):     # if port == 1
  25.         print "%d ms Rising on %d " % (delta.microseconds, portToUse)
  26.     else:                  # if port != 1
  27.         print "%d ms Falling on %d " % (delta.microseconds, portToUse)
  28.  
  29. # when a changing edge is detected on port 27, regardless of whatever
  30. # else is happening in the program, the function my_callback will be run
  31. GPIO.add_event_detect(portToUse, GPIO.BOTH, callback=my_callback)
  32.  
  33. print "Program will finish after 30 seconds or if you press CTRL+C\n"
  34. print "Make sure you have a button connected, pulled down through 10k resistor"
  35. print "to GND and wired so that when pressed it connects"
  36. print "GPIO port 27 (pin 22) to GND (pin 6) through a ~1k resistor\n"
  37.  
  38. print "Also put a 100 nF capacitor across your switch for hardware debouncing"
  39. print "This is necessary to see the effect we're looking for"
  40. raw_input("Press Enter when ready\n>")
  41.  
  42. try:
  43.     print "When pressed, you'll see: Rising Edge detected on %d" % portToUse
  44.     print "When released, you'll see: Falling Edge detected on %d"  % portToUse
  45.     sleep(30)         # wait 30 seconds
  46.     print "Time's up. Finished!"
  47.  
  48. finally:                   # this block will run no matter how the try block exits
  49.     GPIO.cleanup()         # clean up after yourself
RAW Paste Data