Skip to content

Commit 2cc9d2a

Browse files
authored
Merge pull request #2834 from adafruit/ch9328_cpython
adding CH9328 CPython demo
2 parents 56ba6b1 + 72f5880 commit 2cc9d2a

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

CH9328_CPython_Demo/code.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# SPDX-FileCopyrightText: 2024 Liz Clark for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import sys
6+
import serial
7+
import keyboard
8+
9+
port = '/dev/ttyUSB0' # Replace with your actual serial port
10+
11+
# Define a mapping for special characters when shift is pressed
12+
SHIFTED_KEYS = {
13+
'1': '!', '2': '@', '3': '#', '4': '$', '5': '%',
14+
'6': '^', '7': '&', '8': '*', '9': '(', '0': ')',
15+
'`': '~', '-': '_', '=': '+', '[': '{', ']': '}',
16+
'\\': '|', ';': ':', "'": '"', ',': '<', '.': '>',
17+
'/': '?'
18+
}
19+
20+
def send_key(serial_port, key):
21+
"""
22+
Send a key press to the CH9328 via UART.
23+
24+
Parameters:
25+
serial_port (serial.Serial): The serial port connection.
26+
key (str): The key to send.
27+
"""
28+
serial_port.write(key.encode('ascii'))
29+
serial_port.flush()
30+
31+
def send_empty_report(serial_port):
32+
"""
33+
Send an empty HID report to reset the state of the device.
34+
35+
Parameters:
36+
serial_port (serial.Serial): The serial port connection.
37+
"""
38+
try:
39+
empty_report = bytearray([0] * 8)
40+
serial_port.write(empty_report)
41+
serial_port.flush()
42+
except serial.SerialException as e:
43+
print(f"Failed to send empty report: {e}")
44+
45+
def main():
46+
# Configure the serial connection
47+
baudrate = 9600 # Default baud rate for CH9328 in Mode 1
48+
timeout = 1
49+
50+
with serial.Serial(port, baudrate, timeout=timeout) as ser:
51+
52+
print("Listening for keyboard inputs. Press 'ESC' to exit.")
53+
54+
def on_key_event(event):
55+
if event.event_type == 'down':
56+
key = event.name
57+
if len(key) == 1: # Only process single character keys
58+
if keyboard.is_pressed('shift'): # Check if shift is pressed
59+
key = SHIFTED_KEYS.get(key, key.upper())
60+
send_key(ser, key)
61+
elif key == 'space':
62+
send_key(ser, ' ')
63+
elif key == 'enter':
64+
send_key(ser, '\n')
65+
send_empty_report(ser)
66+
67+
# Hook the keyboard event
68+
keyboard.hook(on_key_event)
69+
70+
# Wait for ESC to exit
71+
keyboard.wait('esc')
72+
73+
if __name__ == "__main__":
74+
main()
75+
sys.exit()

0 commit comments

Comments
 (0)