Wednesday, November 13, 2013

Communication between Raspberry Pi and Arduino via USB, using Python

Last post show how to coding in Arduino Due to send out data to USB. In this post, I will show the code of Python on Raspberry Pi side to receive data from USB, and print it on screen.

In this exercise, Raspberry Pi act as host to support power, and Arduino Due act as device. To connect Arduino board to Raspberry Pi, you need a USB cable. It will be the same cable you use to program Arduino board on PC.

Before we start coding, you need to know the actual device port assigned to Arduino, It should be ttyACMx, x may 0, 1, 2... Refer to the post "Arduino recognized as ttyACMx in Raspberry Pi" to check the port assignment.

In Python, we will use the library of pySerial. Check the post "Install pySerial on Ubuntu" in my another blog, the steps is same in Raspberry Pi.

Start idle, the IDE of Python, in Raspberry Pi. Enter the code in new Python module.

import serial
ser = serial.Serial('/dev/ttyACM0', 9600)

while 1:
    print(ser.readline())


Run Module. It should print the received words, "Hello Pi", on Python Shell window.
data output to Python Shell

1 comment:

Unknown said...

May i know how to differentiate the data if i want to capture 3 different sensor data from arduino at the same time?