To develop your projects with Arduino or ESP8266 on Raspberry Pi basis, one may need to access the serial port for the update. This tutorial should work on all distributions of Linux and Raspbian in particular. I wrote this tutorial because I needed to access messages from my Gateway MySensors ESP8266 plugged into the USB port of my Raspberry Pi 3.
Install pyserial on Raspbian
Depending on the version of python, there are several commands to install the package pyserial. To know the version of python run
If the pip command is available (run pip to see if return or not command not found bash) run (replace with pip2 and pip3 based on the python version used).
sudo install pyserial pip3
Otherwise through apt-get
sudo apt-get install python-serial python3-serial
Read on the serial port
Free serial port
Before going any further, check that the console is not listening on the serial port. To do this run
Then follow the images
Find the ttyUSB port that corresponds to your device
There are several ways to determine the USB port to which the device is connected. For options go here. The fastest is to connect the unit to the USB port then to immediately run the command dmesg -s 1024.
You’ll get directly the tty port on which it is connected.
Python code to read the serial port
sudo nano read_serial.py
And copy the following code
#!/usr/bin/env python import time import serial ser = serial.Serial( port='/dev/ttyUSB0', baudrate = 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) counter=0 while 1: x=ser.readline() print x
Register with the combination Ctrl + X then Y by giving a name to the file (for example read_serial.py).
Now, launch the program to read messages sent on the serial port from your device (for example an Arduino).
sudo python read_serial.py