Tuesday, 10 December 2013

Android to Arduino: the code

In a follow up to the Android to Arduino post, here's the code used. The code currently takes a command from an Android app (a button press), and sends a value to the Arduino over serial. In the mean time the arduino is sending a "nop" string back to the app every second. Not much, but enough to prove input & output over serial.
Video of it working here
Arduino code:

 #include  String inData;
Servo myservo;
int pos=0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 115200 bits per second:

// the loop routine runs over and over again forever:
void loop() {
      while (Serial.available() > 0)
        char recieved = Serial.read();
        inData += recieved; 

        // Process message when new line character is recieved
        if (recieved == '\n')
            Serial.print("Arduino Received: ");
            int dataAsInt=inData.toInt();
            if(dataAsInt>0 && dataAsInt<360 buffer="" clear="" dataasint="" delay="" indata="" myservo.write="" nop="" pre="" recieved="" serial.println="">
The Java app is based on the example from https://github.com/mik3y/usb-serial-for-android/tree/master/UsbSerialExamples but has a button with an onClick function with mSerialIoManager.writeAsync("10\n".getBytes());

Monday, 2 December 2013

Linking Android to Arduino

I've started our latest project (to be unveiled soon). It requires Arduino to receive commands from an Android device. It needs to be as light as possible, so ideally needs to be powered from the USB connection.

I've seen a number of solutions using Android ADK and special Arduinos, but this seems rather unnecessary. The problem seems to be the USB communication on either side, requiring USB sheilds (http://www.freetronics.com/products/usbdroid#.Upz8jx8hG1E). Alternatively there's Bluetooth (http://blog.arduino.cc/2013/07/18/how-to-control-arduino-board-using-an-android-phone/), but that would mean an external power source.

So instead, just use a Serial interface. There are Java libraries that can be used on Android. Everything including examples can be found here: https://github.com/mik3y/usb-serial-for-android

 I've hooked up my arduino Uno to an SIII using an A to B USB cable and OTG cable. It all works nicely. Stay tuned for what we're going to use it for ;-)