How to Use Serial Communication on Raspberry Pi Easily
To use
serial communication on Raspberry Pi, enable the serial interface via raspi-config and use the pyserial Python library to send and receive data through the serial port /dev/serial0. This allows your Pi to communicate with other devices like microcontrollers over UART.Syntax
Serial communication on Raspberry Pi typically uses the pyserial library in Python. The main parts are:
serial.Serial(port, baudrate, timeout): Opens the serial port with the specified settings.port: The device name, usually/dev/serial0or/dev/ttyAMA0.baudrate: Communication speed, e.g., 9600 bits per second.timeout: How long to wait for data before giving up.write(data): Sends data to the serial device.read(size): Reads data from the serial device.
python
import serial ser = serial.Serial('/dev/serial0', 9600, timeout=1) ser.write(b'Hello') data = ser.read(5) ser.close()
Example
This example shows how to send the message Hello Pi over the serial port and read a response. It assumes the serial interface is enabled and connected to another device.
python
import serial import time # Open serial port ser = serial.Serial('/dev/serial0', 9600, timeout=1) # Give some time for connection time.sleep(2) # Send data ser.write(b'Hello Pi') # Read response (up to 10 bytes) response = ser.read(10) print('Received:', response.decode('utf-8', errors='ignore')) # Close port ser.close()
Output
Received:
Common Pitfalls
- Serial interface disabled: You must enable it using
sudo raspi-configunder Interface Options > Serial Port. - Console conflict: Disable the serial console to free the port for your program.
- Wrong port: Use
/dev/serial0for the primary UART, not/dev/ttyAMA0or/dev/ttyS0directly. - Baudrate mismatch: Both devices must use the same baudrate.
- Permissions: Run your script with proper permissions or add your user to the
dialoutgroup.
python
import serial # Wrong way: Using disabled serial console port ser = serial.Serial('/dev/ttyAMA0', 9600) # Right way: Use /dev/serial0 after enabling serial interface ser = serial.Serial('/dev/serial0', 9600)
Quick Reference
Summary tips for serial communication on Raspberry Pi:
- Enable serial interface via
raspi-config. - Disable serial console to free the port.
- Use
/dev/serial0as the device path. - Match baudrate on both devices.
- Use
pyseriallibrary in Python for easy communication. - Check user permissions or run with
sudo.
Key Takeaways
Enable the serial interface and disable the serial console using raspi-config before use.
Use the /dev/serial0 device path for UART communication on Raspberry Pi.
Match baudrate settings on both communicating devices to avoid data errors.
Use the pyserial Python library to easily send and receive serial data.
Ensure your user has permission to access the serial port or run scripts with sudo.