Daniel 'MaTachi' Jonsson

Tag Archives: Serial Port

Read Serial Data Transmission in Python

One year ago I wrote a couple of posts about or related to my Arduino board:

I picked it up again from my closet and since I wanted a remote control again. :)

Python script

Since I never stored the Python script that reads the data that the Arduino board outputs from its serial port to the computer’s USB port I had to rewrite it:

#!/usr/bin/python3

from serial import Serial
import subprocess

ser = Serial('/dev/ttyUSB0', 9600, timeout=1)
print("connected to: " + ser.portstr)

while True:
    # Read a line and convert it from b'xxx\r\n' to xxx
    line = ser.readline().decode('utf-8')[:-2]

    if line:  # If it isn't a blank line
        print(line)
        if line == '520':
            subprocess.call(["xte", "key Up"])
        elif line == '620':
            subprocess.call(["xte", "key Down"])
        elif line == '110':
            break

ser.close()

About the script

To install the serial module in Ubuntu for Python 3, run the following line in the terminal:

sudo apt-get install python3-serial

Documentation and installation instructions for other platforms can be found on the module’s site:

The subprocess module and the lines about xte (xautomation) aren’t needed, but read my post Control Keystrokes and Mouse from the Command-Line with Xautomation and you will understand why those lines of code are included. To install Xautomation in Ubuntu, run:

sudo apt-get install xautomation

You can find out which port you should listen to by checking the Arduino IDE’s menu Tools > Serial Port. Or you can check in the /dev folder for something fitting.

Other stuff

How to add a library to Arduino:

If you get an error regarding tying to include WProgram.h if you try to use the infrared remote library, checkout this fix: