Friday, July 13, 2012

How to read Arduino sensors with Adobe AIR Flex on Android

Android now supports Adobe AIR / Flex apps. The main benefit to using Flex over Java is that it specifically facilitates rapid story boarding of mobile user experiences. Coding Adobe Flex is similar to the Visual Basic observer design pattern of push-based actions. Add a button, right click to edit the action.

I decided to show how one could access the serial port using the Amber Android handheld, ArduinoAMBI light sensor using Adobe Flex.

Arduino Code

Upload this simple sketch to the Arduino.

void setup() {
    Serial.begin(115200);//setup a serial port with a baud of 115200

    pinMode(18, OUTPUT);
    pinMode(19, OUTPUT);
    digitalWrite(18, HIGH);
    digitalWrite(19, LOW);

void loop() {
    int value = analogRead(3); //read arduino analog pin 3 and save it as an int to value
    delay(1000);//delay 1,000ms
    char out[200];//create a 200 integer array

    sprintf(out, "hi\nLight=%d\n", value);//prep the out file
    Serial.print(out);//print the out array

Android Java Code

Android must forward serial messages to a local network socket so Adobe flex can handle the data. This is accomplished using the amber-serial app. 

Get the amber-serial source code on github, import this into a new project in Eclipse. Upload to Amber and keep the it running in the background.

Adobe AIR Flex Code

Create a flex app in the Adobe Flex builder through the wizard. Add a button to window and use the following code to read Arduino messages from a local network socket. I used port 8888, but you can use anything you'd like, just make sure to open the port in your firewall with iptables, if used.

socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket.connect("", 8888);

private function onConnect(e:Event):void {
textarea1.text = textarea1.text + "Connected to server";

private function onSocketData(event:ProgressEvent):void
textarea1.text = textarea1.text + "[" + event.type + "] " + socket.readUTF();

App design tools have come a long way, now you can rapid prototype low-level sensors all the way up to the UI design.

No comments: