Skip to content

Commit 4e6c1b3

Browse files
committed
EVENTS.md: Add Keyboard usage example.
1 parent 219c94e commit 4e6c1b3

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

v3/docs/EVENTS.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,7 @@ Constructor optional keyword only args:
528528
* `__getitem__(self, scan_code)` Return the state of a given pin. Enables code
529529
that causes actions after a button press, for example on release or auto-repeat
530530
while pressed.
531-
531+
532532
The `Keyboard` class is subclassed from [Ringbuf queue](./EVENTS.md#7-ringbuf-queue)
533533
enabling scan codes to be retrieved with an asynchronous iterator.
534534

@@ -538,6 +538,36 @@ is not removed from the buffer, on overflow the oldest scan code is discarded.
538538
There is no limit on the number of rows or columns however if more than 256 keys
539539
are used, the `buffer` arg would need to be adapted to handle scan codes > 255.
540540

541+
Usage example. Keypresses on a numeric keypad are sent to a UART with auto
542+
repeat.
543+
```python
544+
import asyncio
545+
from primitives import Keyboard, Delay_ms
546+
from machine import Pin, UART
547+
548+
async def repeat(tim, uart, ch): # Send at least one char
549+
while True:
550+
uart.write(ch)
551+
tim.clear() # Clear any pre-existing event
552+
tim.trigger() # Start the timer
553+
await tim.wait()
554+
555+
async def main(): # Run forever
556+
rowpins = [Pin(p, Pin.OUT) for p in range(10, 14)]
557+
colpins = [Pin(p, Pin.IN, Pin.PULL_DOWN) for p in range(16, 20)]
558+
uart = UART(0, 9600, tx=0, rx=1)
559+
pad = Keyboard(rowpins, colpins)
560+
tim = Delay_ms(duration=200) # 200ms auto repeat timer
561+
cmap = "123456789*0#" # Numeric keypad character map
562+
async for scan_code in pad:
563+
ch = cmap[scan_code] # Get character
564+
rpt = asyncio.create_task(repeat(tim, uart, ch))
565+
while pad[scan_code]: # While key is held down
566+
await asyncio.sleep_ms(0)
567+
rpt.cancel()
568+
569+
asyncio.run(main())
570+
```
541571
##### Application note
542572

543573
Scanning of the keyboard occurs rapidly, and built-in pull-down resistors have a

0 commit comments

Comments
 (0)