Skip to content

Communication between Arduino and Raspberry Pi

mktk1117 edited this page Jul 28, 2016 · 1 revision

How to communicate between Arduino and Raspberry pi

What you need

  • Arduino
  • Raspberry pi
  • USB cable

Arduino Raspberry

Connect

Connect Arduino and Raspberry pi with a USB cable. arduino_raspberry

Try with minicom

Arduino code

Before connecting Arduino with Raspberry pi, please write some sketch which outputs some serial messages.

void setup() {
    Serial.begin(115200);  
}

void loop() {
    Serial.println("hello world");
    delay(100);
}

Then, connect Arduino to Raspberry Pi and log in to Raspberry Pi.

Install

If you don't have minicom, install it first.

sudo apt-get install minicom

Settings

Use minicom to see serial messages. First, check the port of Arduino. Use the command dmesg and see what port is the Arduino connected.

dmesg | grep USB

The output should be like this.

[12750.917580] usb 1-6: new full-speed USB device number 6 using xhci_hcd
[12751.103351] usb 1-6: New USB device found, idVendor=1a86, idProduct=7523
[12751.103360] usb 1-6: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[12751.103365] usb 1-6: Product: USB2.0-Serial
[12751.403840] usbserial: USB Serial support registered for generic
[12751.405628] usbserial: USB Serial support registered for ch341-uart
[12751.406479] usb 1-6: ch341-uart converter now attached to ttyUSB0

From this, it appeared that Arduino has attached to ttyUSB0.

Then, do settings of minicom.

minicom -s

Set the baudrate to 115200 and set the serial device to what you checked (here, it is ttyUSB0). How to set up minicom

Now the setting is over, let's see messages from Arduino with minicom.

minicom

Script to communicate with Arduino

Then, let's make a simple python script to communicate with Arduino

Install

First, if you don't have pyserial library, install it.

sudo apt-get install python-serial

Write messages

It is easy to write messages.

import serial

# open the serial port 
ser = serial.Serial('/dev/ttyUSB0', 9600)

# write message
ser.write("Hello World")

#close
ser.close()

Receive messages

There are several ways to receive messages.

import serial

# open the serial port and set the timeout(sec)
ser = serial.Serial('/dev/ttyUSB0', timeout=0.1)

# read one word
c = ser.read() 

# read 10 words. numbers can be changed as you wish. 
# with a timeout settings, only the words within the time can be read
str = ser.read(10) 

# read a line
line = ser.readline() 

# close
ser.close()