At our last Hull Raspberry Jam, one of our budding Python coders asked me how she could detect keyboard input in a Python script and perform different actions dependent upon which key was pressed.
We both did a bit of searching around and found a few sample pieces of code, but none of them quite did what we wanted. As we were leaving I said that I would research it a bit more, and if she had not found out how to do it before the next Hull Raspberry Jam, I would have some working code for her to use.
I don’t want to ruin the surprise about what her plan is, but needless to say, it will be a very cool project if she completes what she wants to do, more on that later!
I was rather fortunate in that Michael Horne send some sample code around about how to remote control CamJam’s fabulous Robot Kit including a piece of code that would allow you to control a robot with a bluetooth keyboard or the like. Now this was doubly of interest to me, as I also have a team from my school entering the PiWars robot challenge, but that’s for another post!
So using that code as my starting point, here is a fairly simple bit of Python that will react to keyboard presses.
#!/usr/bin/python3 # adapted from https://github.com/recantha/EduKit3-RC-Keyboard/blob/master/rc_keyboard.py import sys, termios, tty, os, time def getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch button_delay = 0.2 while True: char = getch() if (char == "p"): print("Stop!") exit(0) if (char == "a"): print("Left pressed") time.sleep(button_delay) elif (char == "d"): print("Right pressed") time.sleep(button_delay) elif (char == "w"): print("Up pressed") time.sleep(button_delay) elif (char == "s"): print("Down pressed") time.sleep(button_delay) elif (char == "1"): print("Number 1 pressed") time.sleep(button_delay)
It should be quite easy to adjust this for whichever keyboard presses you need to detect and then add in the functions you want to trigger from each key press!
Happy hacking!
I still worry about buffer overflow problems. How can we make sure that does not happen? I have not figured that part out yet…..
just add bytes like messag. sendall(b, “data” ). encode(“utf-8” )
bytes=1024
message. receive(bytes).decode(“”utf-8)
what do i need the start for?
is termios only for unix?
Very helpful, been searching for a long time. How can one detect a return key or space key entry – ASCII?
Hi! This is a great post!
I wanted to display the input from a keyboard on a 2004 LCD as they’re being typed in. Could anyone here point me in the right direction on how I could achieve that?
Would be of great help.
Thanks!