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());

No comments: