Bird
0
0
Raspberry Piprogramming~7 mins

Communicating with Arduino over UART in Raspberry Pi

Choose your learning style9 modes available
Introduction

UART lets your Raspberry Pi and Arduino talk to each other using simple wires. It helps them share data easily.

You want your Raspberry Pi to get sensor data from an Arduino.
You want to control Arduino devices from your Raspberry Pi.
You want to send commands from Raspberry Pi to Arduino for projects.
You want to debug Arduino by reading messages on Raspberry Pi.
You want to connect devices that use serial communication simply.
Syntax
Raspberry Pi
import serial

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

# Write data
ser.write(b'Hello Arduino')

# Read data
line = ser.readline().decode('utf-8').rstrip()

# Close port
ser.close()

Use the correct serial port name for your Raspberry Pi (often '/dev/serial0').

Set the baud rate to match Arduino's UART speed (commonly 9600).

Examples
This sends 'Ping' to Arduino and prints the reply.
Raspberry Pi
import serial
ser = serial.Serial('/dev/serial0', 9600)
ser.write(b'Ping')
response = ser.readline().decode().strip()
print(response)
ser.close()
Using a faster baud rate and a timeout, this reads one line from Arduino.
Raspberry Pi
import serial
with serial.Serial('/dev/serial0', 115200, timeout=2) as ser:
    ser.write(b'Start')
    data = ser.readline().decode().strip()
    print(f'Received: {data}')
Sample Program

This program opens UART, waits a bit for Arduino to be ready, sends 'Hello Arduino', reads one line back, and prints it.

Raspberry Pi
import serial
import time

# Open UART serial connection
ser = serial.Serial('/dev/serial0', 9600, timeout=1)

# Give Arduino time to reset
time.sleep(2)

# Send a message
ser.write(b'Hello Arduino\n')

# Read response
response = ser.readline().decode('utf-8').strip()
print(f'Arduino says: {response}')

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

Make sure UART is enabled on Raspberry Pi via raspi-config.

Connect Raspberry Pi TX to Arduino RX and Raspberry Pi RX to Arduino TX.

Use a common ground wire between Raspberry Pi and Arduino.

Summary

UART is a simple way for Raspberry Pi and Arduino to exchange data.

Use Python's serial library to open, send, and receive data over UART.

Match baud rates and wiring for successful communication.