You can send commands to an Arduino from an Raspberry Pi using a USB cable and Serial Communication.
Prerequisites:
- Raspberry Pi – How to Begin Coding Python on Raspberry Pi
- Arduino – Send Commands with Serial Communication
Functional Parts in the Project:
- Arduino Uno – https://store.arduino.cc/usa/arduino-uno-rev3
- Breadboard Kit – https://amzn.to/2Xih5ei
- LED Kit – https://amzn.to/2Rjhs2N
- 220 Ohm Resistors – https://amzn.to/2RiiMD9
- 560 Piece Jumper Wire Kit – https://amzn.to/2MsCLjL
- Raspberry Pi 4 B
- USB Cable
Python Script
import serial
import time
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyACM1',9600, timeout=1)
ser.flush()
while True:
ser.write(b"red\n")
time.sleep(1)
ser.write(b"white\n")
time.sleep(1)
ser.write(b"blue\n")
time.sleep(1)
ser.write(b"all\n")
time.sleep(1)
ser.write(b"off\n")
time.sleep(1)
Arduino Sketch
String command;
#define blueLed 8
#define whiteLed 9
#define redLed 10
void setup() {
Serial.begin(9600);
pinMode(blueLed, OUTPUT);
pinMode(whiteLed, OUTPUT);
pinMode(redLed, OUTPUT);
delay(2000);
Serial.println("Type Command (white, blue, red, all, off)");
}
void loop() {
if (Serial.available()) {
command = Serial.readStringUntil('\n');
command.trim();
if (command.equals("white")) {
digitalWrite(whiteLed, HIGH);
digitalWrite(blueLed, LOW);
digitalWrite(redLed, LOW);
}
else if (command.equals("blue")) {
digitalWrite(whiteLed, LOW);
digitalWrite(blueLed, HIGH);
digitalWrite(redLed, LOW);
}
else if (command.equals("red")) {
digitalWrite(whiteLed, LOW);
digitalWrite(blueLed, LOW);
digitalWrite(redLed, HIGH);
}
else if (command.equals("all")) {
digitalWrite(whiteLed, HIGH);
digitalWrite(blueLed, HIGH);
digitalWrite(redLed, HIGH);
}
else if (command.equals("off")) {
digitalWrite(whiteLed, LOW);
digitalWrite(blueLed, LOW);
digitalWrite(redLed, LOW);
}
else {
Serial.println("bad command");
}
Serial.print("Command: ");
Serial.println(command);
}
}
Be the first to comment