November 23, 2024

How to Establish Serial Communication Between Python and Arduino in Linux Ubuntu

In this tutorial, we explain how to establish a serial communication link between a computer running a Python script and Arduino. We explain how to perform this task in Linux Ubuntu. The YouTube tutorial accompanying this webpage is given below.

How to Connect Python and Arduino in Linux

We explain how to send/receive integers. Everything explained in the sequel can be generalized to sending/receiving other data types. The communication diagram is given in the figure below.

Our goal is to send an integer from a computer running a Python script to Arduino. Then, Arduino should receive this integer and perform mathematical operations on the integer, and send back the result to the computer. First, we define an integer in Python. Then, we convert the integer to string, and then string to bytes. Then, we use the pySerial Python library to send the bytes data structure. On the other side, the Arduino accepts the message and converts the message first to a string, and then from string to an integer. Arduino adds number 100 to the received string, and converts the result to a string. Then, the string is sent back through the communication channel to the computer running the Python script. The Python script and the pySerial library accept the message, convert the message to string, and string to integer. Finally, the string is displayed on the computer screen.

To establish this communication interface, we first need to install pySerial. Open a terminal window (Anaconda for example), and install pySerial by typing:

pip install pyserial

Then, connect Arduino to the computer by using a USB cable. Then, open a new terminal and make sure that you can write/read to the Arduino port

sudo chmod a+rw /dev/ttyACM0

Then, open a new Python script and type the following code


# Demonstration of Computer-Arduino communication interface
# by using the pySerial library
# this code explains how to send integer messages to Arduino 
# and receive back modified integer messages 
# Second example

# Author: Aleksandar Haber

# import pySerial
import serial 
# time library for introducing delays
import time

# this is necessary for listing all the port
from serial.tools.list_ports import comports


# printing the port information
for portItem in comports():
    print(portItem)

# adjust the proper port, 
# in my case it is /dev/ttyACM0   
arduinoSerial = serial.Serial(port='/dev/ttyACM0', 
                              baudrate=115200, 
                              timeout=.5)

# check if the port is opened
arduinoSerial.is_open

# close the port
arduinoSerial.close()

This will create a pySerial communication object and define the communication port. We close at the end the communication port since we need to upload the Arduino code. You cannot keep the serial port opened from the Python side and at the same time upload the Arduino sketch. Upload the Arduino code given below.

// Arduino-(Python) Computer Serial Communication Interface
// Author: Aleksandar Haber 
// Second Example
// this is the integer number
int number1;
// this is the received string
String receivedString;
// this is the integer that will be sent back 
String sendBackInteger;

void setup() {
  // put your setup code here, to run once:
  // the baud rate should match the baud rate in the Python file
  Serial.begin(115200);

}

void loop() {
  // this while loop will run until something appears at the Serial communication channel
  while(Serial.available()==0);
  
  // read the string from the communication channel
  receivedString=Serial.readString();

  // convert string to integer
  number1=receivedString.toInt();

  // perform an operation on the received integer 
  number1=number1+100;
   
  // convert the integer to a string that will be sent back
  sendBackInteger=String(number1);

  // print the message to the Serial port - this will be sent back to the computer
  Serial.print(sendBackInteger);
  
}

Then, go back to the original Python script and execute the second part of the code.


# open the port 
arduinoSerial.open()


# write the message 
arduinoSerial.write(bytes('Hello World', 'utf-8'))

# wait for Arduino to process the message
time.sleep(0.01)
# read the message that is available on the Serial port
readLine = arduinoSerial.readline() 

# convert the Byte message to string
stringLine=readLine.decode("utf-8")

print(stringLine)
# close the port
arduinoSerial.close()