How to Access the Serial Port in Python

09/08/2021

Contents

In this article, you will learn how to access the serial port in Python.

Using the serial library

In Python, you can access the serial port using the serial library. This library provides a way to communicate with a serial port using a simple API. To use this library, you need to install it using pip:

pip install pyserial

Once you have installed the library, you can use the following code to open a connection to the serial port:

import serial

ser = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=1)

Here, /dev/ttyS0 is the path to the serial device you want to use, and baudrate is the baud rate you want to use for communication. In this example, the baud rate is set to 9600. You can set the baud rate to any value that is supported by your device.

Once you have opened a connection to the serial port, you can use the following code to send data:

ser.write(b"Hello, World!")

And you can use the following code to receive data:

data = ser.read(1024)
print(data.decode())

Note that the read method will block until data is available or the timeout expires.

Once you are done using the serial port, you should close the connection:

ser.close()

This is a basic example of how to use the serial library to communicate with a serial port in Python. You can find more information and examples in the official documentation: https://pyserial.readthedocs.io/en/latest/