Bird
0
0
Raspberry Piprogramming~5 mins

pyserial library usage in Raspberry Pi

Choose your learning style9 modes available
Introduction

The pyserial library helps your Raspberry Pi talk to other devices using serial ports. It makes sending and receiving data easy.

You want to read data from a sensor connected via serial port.
You need to send commands to a microcontroller like Arduino.
You want to log data from a serial device to your Raspberry Pi.
You are debugging serial communication between devices.
You want to control a device that uses serial communication.
Syntax
Raspberry Pi
import serial

ser = serial.Serial(port, baudrate, timeout=1)

ser.write(data)
data = ser.read(size)
ser.close()

port is the name of the serial port (like /dev/ttyUSB0 on Raspberry Pi).

baudrate is the speed of communication (e.g., 9600).

Examples
Open serial port /dev/ttyUSB0 at 9600 baud, send 'Hello', read 5 bytes, then close.
Raspberry Pi
import serial

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
ser.write(b'Hello')
data = ser.read(5)
ser.close()
Use with to open port /dev/ttyS0 at 115200 baud, send 'Ping', read a line, and print it.
Raspberry Pi
import serial

with serial.Serial('/dev/ttyS0', 115200, timeout=2) as ser:
    ser.write(b'Ping')
    response = ser.readline()
    print(response)
Sample Program

This program opens the serial port, sends a greeting, reads up to 20 bytes from the device, prints what it got, and closes the port.

Raspberry Pi
import serial

# Open serial port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)

# Send a message
ser.write(b'Hello Raspberry Pi')

# Read response (up to 20 bytes)
response = ser.read(20)

# Print the response
print('Received:', response)

# Close the port
ser.close()
OutputSuccess
Important Notes

Always close the serial port after use to free it for other programs.

Use timeout to avoid waiting forever when reading.

Data sent and received must be bytes, so prefix strings with b.

Summary

pyserial lets Raspberry Pi communicate over serial ports easily.

Open a port, send bytes, read bytes, then close the port.

Use timeouts and proper port names for smooth communication.