My Python script running is connected to COM1 and the Arduino serial monitor connected to COM2. I am using the pySerial library's command '.readline' to send the serial communication bytes to my Python script. According to the pySerial docs. The.readline command will return a string after it receives a ' ' character. Install Pyserial. Before installing Pyserial, we need to get pip: sudo apt install python-pip. Now we can go on to install Pyserial: python -m pip install pyserial Test installation and read console. To read our console, we need to connect the Raspberry Pi USB port to Arduino one. For testing purposes, I'll show you results from my weather system. Do also have a look at the example files in the examples directory in the source distribution or online. Note: The eolparameter for readlineis no longer supported when pySerial is run with newer Python versions (V2.6+) where the module iois available.
- Python 3 Serial Readline Example
- Pyserial Readline Example
- Python Pyserial Readline Examples
- Pyserial Example Windows
It’s useful to be able to read and plot serial data in real time (for example, you might want to monitor the output of a laser scanner or IMU). While this is a trivial task in MATLAB or LabVIEW, I wondered if there was a low effort way to do it for free.
I’ve known for a while that Python has an easy-to-use serial library, but I wasn’t sure what kinds of plotting/graphing options might exist for Python. A quick search turned up Matplotlib – a MATLAB-like plotting API for Python. As it turns out, Matplotlib includes an animation API and a function called FuncAnimation, which can be used to animate data over time (or update a graph with some sensor data over time).
I’m using this page to document my attempt(s) to use Matplotlib to create a real time graph of data read from a serial port. For a proper introduction to Matplotlib, I’d recommend sentdex’s Matplotlib video series.
Items used
- Laptop or PC running Ubuntu 18
- Python 3.x
- Matplotlib
- pyserial
- Arduino (or any programmable device with a serial port)
Installing matplotlib and pyserial on Ubuntu 18
Generating some fake serial data with an Arduino
To test my code, I used an Arduino to put some data on the serial port. In the example code below, the arduino simulates a coin toss using the function random.
On each iteration of the main loop, a random integer between 0 and 1 is generated, and the relative frequency of getting one side of the coin or the other is updated. This data is then sent to the serial port as comma delimitted line, where the termination character is ‘/n’. That is, the serial data looks like this:
The idea is that I’m putting some data on a serial port over time, and now I can write a python script to read and plot it.
Creating the real time plot
References
- https://pythonhosted.org/pyserial/shortintro.html
- https://www.youtube.com/watch?v=ZmYPzESC5YY
- https://matplotlib.org/
- https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html#matplotlib.animation.FuncAnimation
Python 3 Serial Readline Example
Miniterm¶
Miniterm is now available as module instead of example.see serial.tools.miniterm for details.
- miniterm.py
- The miniterm program.
- setup-miniterm-py2exe.py
- This is a py2exe setup script for Windows. It can be used to create astandalone
miniterm.exe
.
TCP/IP - serial bridge¶
This program opens a TCP/IP port. When a connection is made to that port (e.g.with telnet) it forwards all data to the serial port and vice versa.
This example only exports a raw socket connection. The next examplebelow gives the client much more control over the remote serial port.
- The serial port settings are set on the command line when starting theprogram.
- There is no possibility to change settings from remote.
- All data is passed through as-is.
- tcp_serial_redirect.py
- Main program.
Single-port TCP/IP - serial bridge (RFC 2217)¶
Simple cross platform RFC 2217 serial port server. It uses threads and isportable (runs on POSIX, Windows, etc).
- The port settings and control lines (RTS/DTR) can be changed at any timeusing RFC 2217 requests. The status lines (DSR/CTS/RI/CD) are polled everysecond and notifications are sent to the client.
- Telnet character IAC (0xff) needs to be doubled in data stream. IAC followedby another value is interpreted as Telnet command sequence.
- Telnet negotiation commands are sent when connecting to the server.
- RTS/DTR are activated on client connect and deactivated on disconnect.
- Default port settings are set again when client disconnects.
New in version 2.5.
- rfc2217_server.py
- Main program.
- setup-rfc2217_server-py2exe.py
- This is a py2exe setup script for Windows. It can be used to create astandalone
rfc2217_server.exe
.
Multi-port TCP/IP - serial bridge (RFC 2217)¶
This example implements a TCP/IP to serial port service that works withmultiple ports at once. It uses select, no threads, for the serial ports andthe network sockets and therefore runs on POSIX systems only.
- Full control over the serial port with RFC 2217.
- Check existence of
/tty/USB0...8
. This is done every 5 seconds usingos.path.exists
. - Send zeroconf announcements when port appears or disappears (usespython-avahi and dbus). Service name:
_serial_port._tcp
. - Each serial port becomes available as one TCP/IP server. e.g.
/dev/ttyUSB0
is reachable at<host>:7000
. - Single process for all ports and sockets (not per port).
- The script can be started as daemon.
- Logging to stdout or when run as daemon to syslog.
- Default port settings are set again when client disconnects.
- modem status lines (CTS/DSR/RI/CD) are not polled periodically and the servertherefore does not send NOTIFY_MODEMSTATE on its own. However it responds torequest from the client (i.e. use the
poll_modem
option in the URL whenusing a pySerial client.)
Requirements:
- Python (>= 2.4)
- python-avahi
- python-dbus
- python-serial (>= 2.5)
Installation as daemon:
- Copy the script
port_publisher.py
to/usr/local/bin
. - Copy the script
port_publisher.sh
to/etc/init.d
. - Add links to the runlevels using
update-rc.dport_publisher.shdefaults99
- That’s it :-) the service will be started on next reboot. Alternatively run
invoke-rc.dport_publisher.shstart
as root.
New in version 2.5: new example
Pyserial Readline Example
- port_publisher.py
- Multi-port TCP/IP-serial converter (RFC 2217) for POSIX environments.
- port_publisher.sh
- Example init.d script.
Python Pyserial Readline Examples
wxPython examples¶
A simple terminal application for wxPython and a flexible serial portconfiguration dialog are shown here.
- wxTerminal.py
- A simple terminal application. Note that the length of the buffer islimited by wx and it may suddenly stop displaying new input.
- wxTerminal.wxg
- A wxGlade design file for the terminal application.
- wxSerialConfigDialog.py
- A flexible serial port configuration dialog.
- wxSerialConfigDialog.wxg
- The wxGlade design file for the configuration dialog.
- setup-wxTerminal-py2exe.py
- A py2exe setup script to package the terminal application.
Unit tests¶
The project uses a number of unit test to verify the functionality. They allneed a loop back connector. The scripts itself contain more information. Alltest scripts are contained in the directory test
.
The unit tests are performed on port loop://
unless a different devicename or URL is given on the command line (sys.argv[1]
). e.g. to run thetest on an attached USB-serial converter hwgrep://USB
could be used orthe actual name such as /dev/ttyUSB0
or COM1
(depending on platform).
Pyserial Example Windows
- run_all_tests.py
- Collect all tests from all
test*
files and run them. By default, theloop://
device is used. - test.py
- Basic tests (binary capabilities, timeout, control lines).
- test_advanced.py
- Test more advanced features (properties).
- test_high_load.py
- Tests involving sending a lot of data.
- test_readline.py
- Tests involving
readline
. - test_iolib.py
- Tests involving the
io
library. Only available for Python 2.6 andnewer. - test_url.py
- Tests involving the URL feature.