Guest User

Untitled

a guest
Apr 20th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. import RPi.GPIO as GPIO
  2. from time import time
  3.  
  4. def setup():
  5. GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
  6. GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
  7.  
  8.  
  9. def binary_aquire(pin, duration):
  10. # aquires data as quickly as possible
  11. t0 = time()
  12. results = []
  13. while (time() - t0) < duration:
  14. results.append(GPIO.input(pin))
  15. return results
  16.  
  17.  
  18. def on_ir_receive(pinNo, bouncetime=150):
  19. # when edge detect is called (which requires less CPU than constant
  20. # data acquisition), we acquire data as quickly as possible
  21. data = binary_aquire(pinNo, bouncetime/1000.0)
  22. if len(data) < bouncetime:
  23. return
  24. rate = len(data) / (bouncetime / 1000.0)
  25. pulses = []
  26. i_break = 0
  27. # detect run lengths using the acquisition rate to turn the times in to microseconds
  28. for i in range(1, len(data)):
  29. if (data[i] != data[i-1]) or (i == len(data)-1):
  30. pulses.append((data[i-1], int((i-i_break)/rate*1e6)))
  31. i_break = i
  32. # decode ( < 1 ms "1" pulse is a 1, > 1 ms "1" pulse is a 1, longer than 2 ms pulse is something else)
  33. # does not decode channel, which may be a piece of the information after the long 1 pulse in the middle
  34. outbin = ""
  35. for val, us in pulses:
  36. if val != 1:
  37. continue
  38. if outbin and us > 2000:
  39. break
  40. elif us < 1000:
  41. outbin += "0"
  42. elif 1000 < us < 2000:
  43. outbin += "1"
  44. try:
  45. return int(outbin, 2)
  46. except ValueError:
  47. # probably an empty code
  48. return None
  49.  
  50.  
  51. def destroy():
  52. GPIO.cleanup()
  53.  
  54.  
  55. if __name__ == "__main__":
  56. setup()
  57. try:
  58. print("Starting IR Listener")
  59. while True:
  60. print("Waiting for signal")
  61. GPIO.wait_for_edge(11, GPIO.FALLING)
  62. code = on_ir_receive(11)
  63. if code:
  64. print(str(hex(code)))
  65. else:
  66. print("Invalid code")
  67. except KeyboardInterrupt:
  68. pass
  69. except RuntimeError:
  70. # this gets thrown when control C gets pressed
  71. # because wait_for_edge doesn't properly pass this on
  72. pass
  73. print("Quitting")
  74. destroy()
Add Comment
Please, Sign In to add comment