import serial
from pynput.keyboard import Controller
def read_from_serial(port, baudrate=9600):
try:
ser = serial.Serial(port, baudrate, timeout=1)
keyboard = Controller()
print(f"Listening on {port} at {baudrate} baud rate.")
while True:
if ser.in_waiting > 0:
data = ser.read(ser.in_waiting).decode('utf-8')
print(f"Data received: {data}")
for char in data:
keyboard.press(char)
keyboard.release(char)
except serial.SerialException as e:
print(f"Serial error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
if ser and ser.is_open:
ser.close()
if __name__ == "__main__":
# Replace 'COM3' with your serial port. On Unix-like systems, it may look like '/dev/ttyUSB0'
read_from_serial('COM20')
it return below error.
C:PythonPython310>”C:PythonPython310python.exe” “C:Shijicom2kbcom2kb.py”
File “C:Shijicom2kbcom2kb.py”, line 16
keyboard.press(char)
IndentationError: expected an indented block after ‘for’ statement on line 15
New contributor
King Sun Ng is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.