|
| 1 | +# SPDX-FileCopyrightText: 2022 Dan Halbert for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import board |
| 7 | +import digitalio |
| 8 | +import keypad |
| 9 | + |
| 10 | + |
| 11 | +class Interval: |
| 12 | + """Simple class to hold an interval value. Use .value to to read or write.""" |
| 13 | + |
| 14 | + def __init__(self, initial_interval): |
| 15 | + self.value = initial_interval |
| 16 | + |
| 17 | + |
| 18 | +async def monitor_interval_buttons(pin_slower, pin_faster, interval): |
| 19 | + """Monitor two buttons: one lengthens the interval, the other shortens it. |
| 20 | + Change interval.value as appropriate. |
| 21 | + """ |
| 22 | + # Assume buttons are active low. |
| 23 | + with keypad.Keys( |
| 24 | + (pin_slower, pin_faster), value_when_pressed=False, pull=True |
| 25 | + ) as keys: |
| 26 | + while True: |
| 27 | + key_event = keys.events.get() |
| 28 | + if key_event and key_event.pressed: |
| 29 | + if key_event.key_number == 0: |
| 30 | + # Lengthen the interval. |
| 31 | + interval.value += 0.1 |
| 32 | + else: |
| 33 | + # Shorten the interval. |
| 34 | + interval.value = max(0.1, interval.value - 0.1) |
| 35 | + print("interval is now", interval.value) |
| 36 | + # Let another task run. |
| 37 | + await asyncio.sleep(0) |
| 38 | + |
| 39 | + |
| 40 | +async def blink(pin, interval): |
| 41 | + """Blink the given pin forever. |
| 42 | + The blinking rate is controlled by the supplied Interval object. |
| 43 | + """ |
| 44 | + with digitalio.DigitalInOut(pin) as led: |
| 45 | + led.switch_to_output() |
| 46 | + while True: |
| 47 | + led.value = not led.value |
| 48 | + await asyncio.sleep(interval.value) |
| 49 | + |
| 50 | + |
| 51 | +async def main(): |
| 52 | + interval1 = Interval(0.5) |
| 53 | + interval2 = Interval(1.0) |
| 54 | + |
| 55 | + led1_task = asyncio.create_task(blink(board.D1, interval1)) |
| 56 | + led2_task = asyncio.create_task(blink(board.D2, interval2)) |
| 57 | + interval1_task = asyncio.create_task( |
| 58 | + monitor_interval_buttons(board.D3, board.D4, interval1) |
| 59 | + ) |
| 60 | + interval2_task = asyncio.create_task( |
| 61 | + monitor_interval_buttons(board.D5, board.D6, interval2) |
| 62 | + ) |
| 63 | + |
| 64 | + await asyncio.gather(led1_task, led2_task, interval1_task, interval2_task) |
| 65 | + |
| 66 | + |
| 67 | +asyncio.run(main()) |
0 commit comments