Tags

, ,

I never think about connecting Arduino to Raspberry Pi directly through the USB until recently I were stressed up by servo problems and having to integrate all sorts of boards and programming language together.

Thank God!

According to Dr. Monk’s article here (part1) and here (part2), Raspberry Pi should be able to communicate with Arduino through Python serially. Moreover, I have already installed Arduino IDE in my Raspberry Pi, which by right means I can upload sketch to Arduino from Raspberry Pi!

First of all, upload the following sketch to Arduino using a normal laptop which has Arduino IDE.

const int ledPin = 13;

void setup()
{
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  Serial.println("Hello Pi");
  if (Serial.available())
  {
     flash(Serial.read() - '0');
  }
  delay(1000);
}

void flash(int n)
{
  for (int i = 0; i < n; i++)
  {
    digitalWrite(ledPin, HIGH);
    delay(100);
    digitalWrite(ledPin, LOW);
    delay(100);
  }
}

Then download pyserial-2.7.tar.gz and save it on your laptop or R-Pi directly. I transferred the file over to R-Pi afterwards. Go to the directory (home/pi in this case) and unzip the gz file:

cd ~
gunzip pyserial-2.7.tar.gz
tar -xvf pyserial-2.7.tar

Install PySerial:
cd pyserial-2.7
sudo python setup.py install

Connect Arduino to Raspberry Pi via the USB port.
Open up Python IDLE and type the following to test the connectivity with Arduino.

import serial
ser = serial.Serial('/dev/ttyACM0', 9600) #to select the serial port used.
while 1 :
    ser.readline() #to listen to the message from Arduino

/dev/ttyAMC0 is the name of the USB interface to the Arduino UNO. Last time i used /dev/ttyAMA0 for the direct serial connection (tx and rx). To discover the port name, type the following in the terminal without connecting UNO
ls /dev/tty* – list all devices

The above lines will return “Hello Pi” endlessly until you press CTRL+C to interrupt the message. Then you can also write to Arduino.

ser.write('5') 

In Part 2, the main idea is to control 2 servos using Arduino and Python. In the Arduino program, there are some if-else cases to set the position of the servo. In the Python, Tkinter was used to create a user interface. But basically the interface will send serial command (a character to match that in the if-else cases) to the Arduino.

I think there should not be a problem if I were to control the servo movement with my web app as I could send serial command from a HTML/Javascript web app through Python.

Next up is to redesign the web app and make it work! đŸ™‚

Advertisements