Skip to content
Search

PySerial

lastmod 2025-02-14created 2022-08-1012 edits

This module encapsulates the access for the serial port. It provides backends for Python running on Windows, OSX, Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named “serial” automatically selects the appropriate backend.

CLI Usage

List ports:

python -m serial.tools.list_ports

Serial connection:

sudo -s
cd /home/your/.pyenv/versions/opy-your-3.9.11/bin
./python -m serial.tools.miniterm --encoding Latin1 /dev/ttyUSB0 115200 | tee /home/your/Downloads/logging

The reason for doing it this way: when using pyenv, running with sudo uses the global python, so you have to move directly into the directory where the pyenv environment is installed and run it from there

Adding serial permissions

See Serial Communication#Adding Linux permissions. In short, sudo adduser $USER dialout

Opening serial ports

Open port at “9600,8,N,1”, no timeout:

>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0')  # open serial port
>>> print(ser.name)         # check which port was really used
>>> ser.write(b'hello')     # write a string
>>> ser.close()             # close port

APIs

serial_for_url

For the kwargs used for a serial connection such as /dev/ttyUSB0, see the __init__ function of #Serial.

Serial

Parameters:

  • port – Device name or None.
  • baudrate (int) – Baud rate such as 9600 or 115200 etc.
  • bytesize – Number of data bits. Possible values: FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
  • parity – Enable parity checking. Possible values: PARITY_NONE, PARITY_EVEN, PARITY_ODD PARITY_MARK, PARITY_SPACE
  • stopbits – Number of stop bits. Possible values: STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO
  • timeout (float) – Set a read timeout value in seconds.
  • xonxoff (bool) – Enable software flow control.
  • rtscts (bool) – Enable hardware (RTS/CTS) flow control.
  • dsrdtr (bool) – Enable hardware (DSR/DTR) flow control.
  • write_timeout (float) – Set a write timeout value in seconds.
  • inter_byte_timeout (float) – Inter-character timeout, None to disable (default).
  • exclusive (bool) – Set exclusive access mode (POSIX only). A port cannot be opened in exclusive access mode if it is already open in exclusive access mode.

See also

Favorite site

author Zer0 sitemap