code.py
1 # SPDX-FileCopyrightText: 2018 Limor Fried for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 # pylint: disable=multiple-statements,wrong-import-position,wrong-import-order 6 import gc 7 from adafruit_hid.keyboard import Keyboard; gc.collect() 8 from adafruit_hid.keycode import Keycode; gc.collect() 9 from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS; gc.collect() 10 import board 11 import pulseio 12 import adafruit_dotstar 13 import adafruit_irremote 14 import time 15 import usb_hid 16 17 # The keyboard object! 18 time.sleep(1) # Sleep for a bit to avoid a race condition on some systems 19 keyboard = Keyboard(usb_hid.devices) 20 keyboard_layout = KeyboardLayoutUS(keyboard) # We're in the US :) 21 22 led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) 23 decoder = adafruit_irremote.GenericDecode() 24 pulsein = pulseio.PulseIn(board.REMOTEIN, maxlen=100, idle_state=True) 25 26 # Expected pulse, pasted in from previous recording REPL session: 27 key1_pulses = [0] 28 29 key2_pulses = [1] 30 31 print('IR listener') 32 # Fuzzy pulse comparison function: 33 def fuzzy_pulse_compare(pulse1, pulse2, fuzzyness=0.2): 34 if len(pulse1) != len(pulse2): 35 return False 36 for i in range(len(pulse1)): 37 threshold = int(pulse1[i] * fuzzyness) 38 if abs(pulse1[i] - pulse2[i]) > threshold: 39 return False 40 return True 41 42 # Create pulse input and IR decoder. 43 pulsein.clear() 44 pulsein.resume() 45 46 # Loop waiting to receive pulses. 47 while True: 48 led[0] = (0, 0, 0) # LED off 49 # Wait for a pulse to be detected. 50 pulses = decoder.read_pulses(pulsein) 51 led[0] = (0, 0, 100) # flash blue 52 53 print("\tHeard", len(pulses), "Pulses:", pulses) 54 # Got a pulse set, now compare. 55 if fuzzy_pulse_compare(key1_pulses, pulses): 56 print("****** KEY 1 DETECTED! ******") 57 keyboard.press(Keycode.SPACE) 58 keyboard.release_all() 59 60 if fuzzy_pulse_compare(key2_pulses, pulses): 61 print("****** KEY 2 DETECTED! ******") 62 keyboard_layout.write("hello!")