Serial port programming on Linux using Python and PySerial

RSDevX
3 min readOct 6, 2022

--

Learn how to setup a serial port communication between a Linux PC/Laptop and a Atmega328p Microcontroller or Arduino using PySerial and Python.

The Tutorial deals with

  • Setting up permissions to read and write to a Linux(ubuntu) serial port,
  • How to solve the /dev/ttyUSB0 or /dev/ttyACM0 access denied error.
  • How to add a user to tty and dialout groups.
  • How to solve dmesg :read kernel buffer failed :Operation not permitted

Source Codes

Source codes can be downloaded from the Youtube Video description

How To Install PIP Package Manager On Linux

Check whether PIP is installed on the System,

if not, install with the following command, You can also check the link above to the video.

sudo apt install python3-pip

After installing PIP ,use it to install the latest version of Pyserial

How to install PySerial on Linux (Ubuntu 22–04-LTS) using PIP Package Manager

use the below command or check the above video link ,if you get into trouble while installing Pyserial

python3 -m pip install pyserial

How to Identify the Serial Port Name / Number of Your Device in Linux (ubuntu)

In Linux there is no concept of COM number, instead the

  1. hardware serial ports are numbered as ttyS0,ttyS1 etc ,
  2. USB to Serial Converters as ttyUSB0,ttyUSB1 etc.
  3. Arduino’s as ttyACM0

Connect your Arduino to the USB port and issue a

sudo dmesg | tail

command at the terminal.

You have to use sudo in front of dmesg otherwise you will get a dmesg :read kernel buffer failed :Operation not permitted error.

So in Linux change the second line to

SerialObj = serial.Serial('/dev/ttyACM0')

for Arduino

Making Python Serial Port Code Executable

Before running the python code ,you have to make them executable by using the chmod command

chmod +x yourpythonfile.py

Adding the User to Tty and Dialout Groups for Serial Port Access in Linux (Ubuntu)

On Linux to access the serial port the user must be part of 2 groups

  1. tty
  2. dialout

You should add yourself to these two groups using the usermod command.

Please note that you should have permission to run the sudo command (part of the Sudo group in Ubuntu) or part of the wheel group in Centos/RHEL/Rocky Linux.

Adding a user to tty and dialout groups for serial port access.

sudo usermod -a -G tty [username]
sudo usermod -a -G dialout [username

replace [username] with your username Eg rahul or molly.

The -a makes sure that you are appending the user to the groups .if -a is missing you will get unsubscribed from all other groups except tty and dialout.

After the commands are run,

Logoff from your account and then log back in so that changes are saved.

Running Python Serial Port Communication Code on Linux

Original Article on Serial Port Programming on Linux using Python and Pyserial

--

--