PS/2 Keyboard as STDIN

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
czarnikjak
Posts: 2
Joined: Fri Nov 26, 2021 1:15 pm

PS/2 Keyboard as STDIN

Post by czarnikjak » Fri Nov 26, 2021 1:24 pm

I created a simple script to read scan codes from PS/2 Keyboard, like this:

Code: Select all

from machine import UART
import os
import sys
import time
os.dupterm(None, 1)

keyCodes = {
  139: 'Q', 207: 'W', 194: 'E', 199: 'R', 134: 'T', 203: 'Y', 203: 'U', 161: 'I', 226: 'O', 231: 'P', 
  142: 'A', 205: 'S', 145: 'D', 213: 'F', 154: 'G', 217: 'H', 157: 'J', 224: 'K', 224: 'K', 229: 'L', 
  140: 'Z', 208: 'X', 209: 'C', 148: 'V', 152: 'B', 153: 'N', 204: 'M', 225: ',', 165: '.', 149: '_', 164: '?', 
  138: '1', 206: '2', 146: '3', 147: '4', 214: '5', 218: '6', 159: '7', 158: '8', 162: '9', 163: '0'
}

uart = UART(0, baudrate=10000,bits=8, parity=None, stop=1)
dataList = []

while True:
    if uart.any():
        data = bytearray(1)
        uart.readinto(data, 1)
        dataList.append(data[0])
        if len(dataList) == 3:
            if dataList[0] in keyCodes:
                sys.stdout.write(letter)
            elif data[0] == 220:
                sys.stdout.write("\n")
            dataList = []
            time.sleep_us(1000)

It works well and prints pressed characters from the keyboard.

However, I am not sure how can I feed the keypresses to STDIN, so they are treated by Python Interpreter in the same way as letters typed via WebRepl for example.

Any help would be appreciated.

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: PS/2 Keyboard as STDIN

Post by dhylands » Fri Nov 26, 2021 6:16 pm

You should be able to use os.dupterm: https://docs.micropython.org/en/latest/ ... os.dupterm to implement this.
Caveat - I haven't tried this myself.

czarnikjak
Posts: 2
Joined: Fri Nov 26, 2021 1:15 pm

Re: PS/2 Keyboard as STDIN

Post by czarnikjak » Fri Nov 26, 2021 8:30 pm

Talking about dupterm, the code i pasted above is working on ESP8266.

I am not sure why dupterm seems to be behaving differently on ESP32. Any dupterm command with Index value different to 0 results in an error:
ValueError: invalid dupterm index

Post Reply