|
| 1 | +# SPDX-FileCopyrightText: 2022 Tod Kurt & John Park for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +# |
| 5 | +# Rotary phone USB keypad |
| 6 | + |
| 7 | +import time |
| 8 | +import board |
| 9 | +import digitalio |
| 10 | +import microcontroller |
| 11 | +import usb_hid |
| 12 | +from adafruit_hid.keyboard import Keyboard |
| 13 | +from adafruit_hid.keycode import Keycode |
| 14 | +from adafruit_debouncer import Debouncer |
| 15 | +import neopixel |
| 16 | + |
| 17 | + |
| 18 | +dial_in = digitalio.DigitalInOut(board.RX) # normally closed pulse dial switch |
| 19 | +dial_in.pull = digitalio.Pull.UP |
| 20 | +dial = Debouncer(dial_in) |
| 21 | + |
| 22 | +receiver_in = digitalio.DigitalInOut(board.D2) # normally open receiver switch |
| 23 | +receiver_in.pull = digitalio.Pull.UP |
| 24 | +receiver = Debouncer(receiver_in) |
| 25 | + |
| 26 | + |
| 27 | +# check if usb_hid has been enabled in boot.py |
| 28 | +if len(usb_hid.devices) == 0: |
| 29 | + on_hook = True |
| 30 | + print("on hook") |
| 31 | +else: |
| 32 | + kbd = Keyboard(usb_hid.devices) |
| 33 | + on_hook = False |
| 34 | + print("off hook") |
| 35 | + |
| 36 | +keymap = [ |
| 37 | + Keycode.ONE, |
| 38 | + Keycode.TWO, |
| 39 | + Keycode.THREE, |
| 40 | + Keycode.FOUR, |
| 41 | + Keycode.FIVE, |
| 42 | + Keycode.SIX, |
| 43 | + Keycode.SEVEN, |
| 44 | + Keycode.EIGHT, |
| 45 | + Keycode.NINE, |
| 46 | + Keycode.ZERO |
| 47 | +] |
| 48 | + |
| 49 | +def read_rotary_dial_pulses(timeout=0.2): # 0.2 is proper timing for pulses |
| 50 | + dial.update() |
| 51 | + if not dial.rose: # NC dial pin is pulled low normally, high when open |
| 52 | + return 0 |
| 53 | + pulse_count = 1 |
| 54 | + last_pulse_time = time.monotonic() |
| 55 | + |
| 56 | + while time.monotonic() - last_pulse_time < timeout: # count pulses that are within 0.2sec |
| 57 | + dial.update() |
| 58 | + if dial.rose: |
| 59 | + pulse_count = pulse_count+1 |
| 60 | + last_pulse_time = time.monotonic() |
| 61 | + |
| 62 | + return pulse_count |
| 63 | + |
| 64 | +pixel = neopixel.NeoPixel(board.NEOPIXEL, 1) |
| 65 | + |
| 66 | + |
| 67 | +print("Rotary phone USB keypad") |
| 68 | + |
| 69 | + |
| 70 | +while True: |
| 71 | + receiver.update() |
| 72 | + if receiver.fell: # only dial when receiver is off hook |
| 73 | + print("Off hook") |
| 74 | + pixel[0] = 0x00ff00 |
| 75 | + microcontroller.reset() # the boot.py enables usb_hid if off hook |
| 76 | + |
| 77 | + if receiver.rose: |
| 78 | + print("On hook") |
| 79 | + pixel[0] = 0xff0000 |
| 80 | + microcontroller.reset() # the boot.py disables usb_hid if on hook |
| 81 | + |
| 82 | + # if not on_hook: |
| 83 | + num_pulses = read_rotary_dial_pulses() |
| 84 | + if num_pulses: |
| 85 | + print("pulse count:", num_pulses) |
| 86 | + if not on_hook: |
| 87 | + kbd.send(keymap[num_pulses-1]) |
0 commit comments