Serial Communication
Serial (UART) is used to communicate between Raspberry Pi and Arduino for sensor data and motor commands.
Arduino Side
cpp
void setup() {
Serial.begin(115200);
}
void loop() {
// Read command from Pi
if (Serial.available()) {
String cmd = Serial.readStringUntil('\n');
// cmd format: "L150 R150\n"
// parse and drive motors...
}
// Send sensor data to Pi
int dist = readUltrasonic();
Serial.println("DIST:" + String(dist));
delay(50);
}Raspberry Pi Side (Python)
python
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
time.sleep(2) # wait for Arduino reset
# Send command
ser.write(b'L150 R150\n')
# Read response
line = ser.readline().decode('utf-8').strip()
print(line) # e.g. "DIST:34"Find Serial Port
bash
ls /dev/ttyACM* /dev/ttyUSB*
# Plug/unplug Arduino to identify the portGrant Permission
bash
sudo usermod -aG dialout $USER
# Log out and back inWARNING
Always use the same baud rate on both ends. Mismatched baud rates produce garbage data without any error.