Last modified: Apr 07, 2025 By Alexander Williams

How to Install Pyserial in Python Step by Step

Pyserial is a Python library for serial communication. It helps you interact with serial ports easily. This guide will show you how to install it.

What Is Pyserial?

Pyserial allows Python to communicate with serial devices. It works on Windows, Linux, and macOS. It's useful for Arduino, Raspberry Pi, and other hardware projects.

Prerequisites

Before installing Pyserial, ensure you have Python installed. You can check by running:


python --version

If Python is not installed, download it from the official website. Also, ensure pip is installed. Pip is Python's package manager.

Install Pyserial Using Pip

The easiest way to install Pyserial is using pip. Open your terminal or command prompt and run:


pip install pyserial

This command downloads and installs the latest version of Pyserial. Wait for the installation to complete.

Verify the Installation

After installation, verify it works. Open Python and import the library:

 
import serial
print(serial.__version__)

If no errors appear, Pyserial is installed correctly. You should see the version number.

Common Installation Issues

Sometimes, you may face issues. One common error is ModuleNotFoundError. This means Python can't find Pyserial.

If you see this, check if pip installed it in the correct Python version. For more help, read our guide on how to solve ModuleNotFoundError.

Using Pyserial

Once installed, you can start using Pyserial. Here's a simple example to open a serial port:

 
import serial

# Open serial port
ser = serial.Serial('COM3', 9600)  # Change COM3 to your port
print("Port opened:", ser.name)
ser.close()

This code opens COM3 at 9600 baud rate. Adjust the port name and baud rate as needed.

Reading Data from Serial Port

You can also read data from the serial port. Here's an example:

 
import serial

ser = serial.Serial('COM3', 9600)
while True:
    data = ser.readline().decode('utf-8').strip()
    print("Received:", data)

This code reads data line by line. It decodes the bytes to a string and prints it.

Writing Data to Serial Port

To send data, use the write method. Here's how:

 
import serial

ser = serial.Serial('COM3', 9600)
ser.write(b'Hello, Serial!')  # Send bytes
ser.close()

This sends "Hello, Serial!" to the connected device. Note the b prefix for bytes.

Conclusion

Installing Pyserial is simple with pip. It enables powerful serial communication in Python. Now you can interact with hardware devices easily.

If you face issues, check your Python and pip setup. For more help, refer to our guide on ModuleNotFoundError.

Happy coding with Pyserial!