Serial Communication between Raspberry Pi & Arduino

From ESE205 Wiki
Revision as of 17:25, 10 December 2017 by Sycstudent (talk | contribs) (From Arduino to Raspberry Pi)
Jump to: navigation, search

From Arduino to Raspberry Pi

Arduino code
A sample arduino code is created below. The code is very simple—printing “Hello World!” every two seconds.

void setup(){

void loop(){
  Serial.println("Hello World!");   
Figuring out the port
Example of new port name

Then, we need to figure out the port that connects Raspberry Pi & Arduino. Type in the following command in your terminal without Arduino plugged into Raspberry Pi. The command means to list out all the ports with the beginning of "tty".
pi@raspberrypi $ ls /dev/ttty*
Then connects the two devices with your USB cable, and type in the command above again. There shall be a new port appears; if that is the case, the new name is the port name of your Arduino. The picture on the right is a demo of what should be like.

Python Code
Now, we open a new sketch of python program on your Raspberry Pi.

import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
while 1: 
    if(ser.in_waiting >0):
        line = ser.readline()
Sample output of RPi Python console

The first line is to import the module named serial. Then we are creating an object with port name of "/dev/ttyUSB0" (the port name you just found out)and baud rate of 9600. In the while loop, our program will print each line it reads from the stream. Also, there are many other functions for the serial module; you can check the documentation.
Now you can first upload your Arduino program you just wrote, and then run the python program. If everything works well, you will see the python console printing " Hello World!" every two seconds, just like the picture on the right shows.

From Raspberry Pi to Arduino