Following a query from Naomi Dickerson, I was playing around with my SerialSend program, which I often use for sending arbitrary bytes or characters to a connected microcontroller circuit. Sometimes, it’s convenient to send keystrokes in real time i.e. each keystroke is sent as soon as the user strikes the key. This could be done in a Windows console using something like getch(), but in this case I’ve chosen to use Python and Tkinter instead, supported by the PySerial module. Python is absolutely great for automating serial port chit chat. I’ve never found anything better for opening, reading, writing and closing a serial port in just a few lines of code.
Here’s what my ultra simple GUI (if you can even call it that) looks like:
Here’s the full Python code, which I saved as the file “keysender.py”:
# import libraries for serial port and Tkinter GUI import serial import Tkinter # Open serial port ser = serial.Serial('/dev/ttyUSB0', baudrate=9600, timeout=1) # Create the root window root = Tkinter.Tk() root.geometry('400x200+100+100') root.title('Serial Keystoke Sender') # Create a keystroke handler def key(event): if (event.char == 'q'): root.quit() elif event.char >= '0' and event.char <= '9': print 'keystroke:', repr(event.char) ser.write(event.char) # Create a label with instructions label = Tkinter.Label(root, width=400, height=300, text='Press 0-9 to send a number, or "q" to quit') label.pack(fill=Tkinter.BOTH, expand=1) label.bind('<Key>', key) label.focus_set() # Hand over to the Tkinter event loop root.mainloop() # Close serial port ser.close()
The above code should be cross-platform compatible apart from the serial port name ‘/dev/ttyUSB0’, which is what my USB-to-serial converter appears as here in Crunchbang Linux. In Windows, I think you can either replace ‘/dev/ttyUSB0’ with your COM port name in inverted commas (e.g. ‘COM23’) , or even just a device number (0, 1, 2 or whatever).
Python itself is installed by default in Crunchbang, but I needed to install PySerial and Tkinter:
sudo apt-get install python-tk sudo apt-get install python-serial
I ran my code as root so that I would have access to the serial port device:
sudo python keysender.py
There are more elegant ways to handle this by configuring file permissions or whatever, but for this kind of hardware hacking I’m happy enough to just sudo it.
Hi Burke,
First of all, you have a very nice blog. Thanks for sharing your knowledge!
I don’t have a clue about the version of python used. Is it version 3 for default?
Thank you!
Hi Fernando,
Thanks for your kind words! When I wrote this post, I was using still Crunchbang Linux (I’m using Xubuntu now that Crunchbang has disappeared) and I was presumably using the default installed Python version which was either 2.6 or 2.7.
Ted