Serial Port Communication via Python

There are many Linux (and Windows) programs ‘out there’ that allow you to do serial port communications.  However, I needed some things that those programs did not provide (on my Linux system) so I came up with my Serial Port Communication via Python script. If you want something that you can learn from and/or customize further this script is for you (if you are using Linux that is). Here is the script:

                                Serial Port Communication via Python

It takes from zero to two parameters. Given no parameters, it defaults to 115200 BAUD and will search for ‘active’ serial ports with the name /dev/ttyUSB* or /dev/ttyACM* and use the first one it finds. If you want to override or specify either the serial port or BAUD rate just give it either or both parameters. If you give it both parameters, they can be in any order as the script can tell what is a port versus what is the rate. When running, the script will ‘echo’ any characters coming from the serial port to the console and ‘echo’ any characters typed in from the console to the serial port. Use a Ctrl-C to exit the script. Note that the comments tell you how to change certain features of the program.

With this script you have basic serial port communications (quite usable) and it can be easily added to for enhanced functionality.

Again, there are other serial communication programs/scripts (which run under Linux). Perhaps the most common one used is minicom. Another quite useful program is screen.  Although screen is primarily used as a terminal multiplexer (i.e. using virtual terminals in a login session), it can be used as a serial terminal communication program too. For example:

screen /dev/ttyUSB0 115200

Also note that the Arduino IDE has a built in serial monitor (the newer versions have a serial plotter too) so that serial communications with your Arduino is relatively easy during code development. The Pinguino IDE does not have a serial monitor built in so my script can be used for that sometimes needed functionality.

You may notice that this script is an updated version of one I wrote about before (here) which I used to communicate with the Arduino MiniPirate sketch.

If you do put my script to use or enhance it, i’d be interested to see what features you add. Leave a comment!

Leave a Reply

Your email address will not be published.