Friday, November 15, 2013

Send and receive from Raspberry Pi to and from Arduino, with 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()

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

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

Cross post with my another blog: Arduino-er

No comments: