Friday, November 15, 2013

Communication between Arduino and Raspberry Pi (in Python)

This example show how to write a simple Python program on Raspberry Pi to get keyboard input and send to Arduino via USB. In Arduino, send back the received chars to Raspberry Pi, then print on screen in Pi side.



In this example, Raspberry Pi act as host and Arduino Due act as device, and connect with USB on Programming USB Port.

Python code in Raspberry Pi:
import serial
ser = serial.Serial('/dev/ttyACM1', 9600)

name_out = raw_input("Who are you?\n")
ser.write(name_out + "\n")
name_return = ser.readline()
print(name_return)

Code in Arduino side:
int pinLED = 13;
boolean ledon;

void setup() {
  Serial.begin(9600);
  pinMode(pinLED, OUTPUT);
  ledon = true;
  digitalWrite(pinLED, ledon = !ledon);
}
 
void loop() {
  if(Serial.available() > 0){
    Serial.print("Hello ");
    
    while(Serial.available()>0){
      char charIn = (char)Serial.read();
      Serial.print(charIn);
      if (charIn == '\n')
        break;
    }
    
    digitalWrite(pinLED, ledon = !ledon);
  }
}

Cross-post with my another blog: Hello Raspberry Pi

No comments:

Post a Comment