Arduino – Send Serial Commands from Raspbery Pi

You can send commands to an Arduino from an Raspberry Pi using a USB cable and Serial Communication.

Prerequisites:

Functional Parts in the Project:

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

Leave a Reply