Connecting Raspberry PI 3 with Android Things to Arduino

Markiyan Antonyuk
2 min readJan 5, 2017

--

This tutorial will show how to connect Raspberry Pi 3 with Android Things to Arduino. RPi will send 0 or 1 bytes to Arduino each second, and Arduino will set a led to HIGH or LOW, depending on data.

Android Things version: developer preview 0.1

Purpose:

Raspberry PI 3 as well as Android Things platform don’t have any analog input/output. It is a real mess to connect ADC/DAC converters, find workarounds, use I2C to do such work. In this tutorial I’d like to cover how you can connect to Raspberry PI 3 with Android Things to Arduino board and get all needed analog reads/writes to the sensors you require.

The main pro of this approach is that you will use only 2 pins on RPi and 2 pins on Arduino to handle the connection, but you’ll get almost twice more pins (depends on Arduino board) and it’s really easy to do this. From the other side biggest con is that it will require more code from 2 sides.

Pinout:

Pinout is really simple, you should connect your RPi TXD to Arduino 0(RX) pin and RPi RXD to Arduino 1(TX) pin.

Android Things code

I’ve removed all the try/catches so the code would be more readable.

private PeripheralManagerService mPeripheralManagerService;
private UartDevice mArduino;
private byte[] mData = new byte[1];

public void conversateWithArduino() {
mPeripheralManagerService = new PeripheralManagerService();
mArduino = mPeripheralManagerService.openUartDevice("UART0");
//set baudrate to 9600, or whatever allowed value as set on Arduino
mArduino.setBaudrate(9600);
//submit repeatable operation of sending data Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//trigger sending data
mData[0] = (byte) (mData[0] == 0 ? 1 : 0);
//write data to UART device
mArduino.write(mData, mData.length);
}
}, 0, 1, TimeUnit.SECONDS);
}

Arduino code

#include <Arduino.h>void setup() {
//Set the same baudrate as on RPi
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop() {
//hold while there is nothing on serial
while (Serial.available() == 0);
//read data from UART
int data = Serial.read();
if (data) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
}

--

--