How to Communicate Between a Raspberry Pi and an Arduino
This guide will demonstrate how to set up communication between a Raspberry Pi and an Arduino. The Raspberry Pi acts as the primary interface for WiFi communication and processing, while the Arduino serves as the main controller for stepper motors and servos.
Overview
- Raspberry Pi: Used for WiFi communication, processing commands, and sending instructions to the Arduino.
- Arduino: Manages stepper motors and servos based on commands received from the Raspberry Pi.
- Communication: Uses a serial connection (via USB).
1. Steps to Set Up Communication
- USB-to-Serial Communication
- Connect the Raspberry Pi to the Arduino using a USB cable.
- The Pi will recognize the Arduino as a serial device (e.g., /dev/ttyUSB0).
2. Arduino Code
On the Arduino, use the Serial library to receive commands and control hardware. Here’s an example sketch:
#include <Stepper.h>
const int stepsPerRevolution = 200; // Adjust for your stepper motor
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); // Motor pins
void setup() {
Serial.begin(9600); // Start serial communication
myStepper.setSpeed(60); // Set motor speed
Serial.println("Arduino ready");
}
void loop() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
if (command == "up") {
myStepper.step(stepsPerRevolution); // Move motor one revolution
Serial.println("Moved up");
} else if (command == "down") {
myStepper.step(-stepsPerRevolution); // Move motor in reverse
Serial.println("Moved down");
}
}
}
3. Raspberry Pi Code
On the Raspberry Pi, use Python with the pyserial library to send commands to the Arduino.
pip install pyserial
import serial
import time
class ArduinoConnection:
def __init__(self, port="/dev/ttyUSB0", baudrate=9600):
self.serial = serial.Serial(port, baudrate, timeout=1)
time.sleep(2) # Wait for Arduino to initialize
def move_manual(self, direction):
if direction in ["up", "down"]:
self.serial.write(f"{direction}\n".encode())
feedback = self.serial.readline().decode().strip()
print(f"Arduino says: {feedback}")
def close(self):
self.serial.close()
Main Python Script
In the main script, import the ArduinoConnection
class from arduino.py
and use it to communicate with the Arduino:
from arduino import ArduinoConnection
if __name__ == "__main__":
arduino = ArduinoConnection()
arduino.move_manual("up")
arduino.move_manual("down")
arduino.close()
Applications
This Raspberry Pi-to-Arduino communication setup is ideal for:
• Controlling motors, servos, and other actuators via the Arduino.
• Offloading computationally intensive tasks to the Pi while maintaining precise hardware control.