A Practical Guide to Connecting Hardware to Flex at Flash and the City

I recently gave a talk on using the Flex and the Arduino platform together for the Flash and the City conference in New York.

You can download a PDF of my talk (2 Mb) or view on slide share. The talk was recorded as soon as I get the link I'll add it here as well.

The talk showed how to to turn LEDs connected to an Arduino on and off from Flex, how to control the size of shapes in Flex from an Arduino and to communication with an Arduino XML web server from Flex.

Turn on/off LEDs from Flex

This Flex code runs in a browser and can communicate to an Arduino board (via AS3Glue and Firmata) to turn LEDs on or off.

view plain print about
1<?xml version="1.0" encoding="utf-8"?>
2<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="init()" scaleX="3" scaleY="3">
3
    
4    <mx:Script>

5        <![CDATA[
6            import net.eriksjodin.arduino.events.ArduinoEvent;
7            import net.eriksjodin.arduino.Arduino;
8            
9            private var ledR1:int = 3;
10            private var ledG1:int = 5;
11            private var ledB1:int = 6;
12            private var ledR2:int = 9;
13            private var ledG2:int = 10;
14            private var ledB2:int = 11
15            
16            private var arduino:Arduino = new Arduino();
17            
18            private function init():void {
19                arduino.requestFirmwareVersion();
20                arduino.addEventListener(ArduinoEvent.FIRMWARE_VERSION, initArduino);
21            }
22            
23            private function initArduino(event:Event):void {
24                arduino.setPinMode(ledR1, Arduino.OUTPUT);
25                arduino.setPinMode(ledG1, Arduino.OUTPUT);
26                arduino.setPinMode(ledB1, Arduino.OUTPUT);
27                arduino.setPinMode(ledR2, Arduino.OUTPUT);
28                arduino.setPinMode(ledG2, Arduino.OUTPUT);
29                arduino.setPinMode(ledB2, Arduino.OUTPUT);    
30            }
31            
32            private function turnOn(led:int):void {
33                arduino.writeDigitalPin(led, Arduino.HIGH);
34            }
35            
36            private function turnOff(led:int):void {
37                arduino.writeDigitalPin(led, Arduino.LOW);
38            }            
39        ]]>
40    </mx:Script>
41    
42    <mx:Form>

43        <mx:FormItem label="Red" labelWidth="50" direction="horizontal" color="#FF0000">

44            <mx:Button label="On" click="turnOn(ledR1);turnOn(ledR2)" />

45            <mx:Button label="Off" click="turnOff(ledR1);turnOff(ledR2)" />
                
46        </mx:FormItem>
47        <mx:FormItem label="Green" labelWidth="50" direction="horizontal" color="0x00FF00">
48            <mx:Button label="On" click="turnOn(ledG1);turnOn(ledG2)" />
49            <mx:Button label="Off" click="turnOff(ledG1);turnOff(ledG2)" />                
50        </mx:FormItem>
51        <mx:FormItem label="Blue" labelWidth="50" direction="horizontal" color="0x0000FF">
52            <mx:Button label="On" click="turnOn(ledB1);turnOn(ledB2)" />
53            <mx:Button label="Off" click="turnOff(ledB1);turnOff(ledB2)" />                
54        </mx:FormItem>    
55    </mx:Form>    
56</mx:Application>

Analog input controlling Flex

This Flex code runs in a browser and analog sliders (like volume controls) on a Danger Shield can control (via AS3Glue and Firmata) the size of circles on the screen.

view plain print about
1<?xml version="1.0" encoding="utf-8"?>
2<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx"
3
    creationComplete="
init()">
4    
5    <fx:Script>
6        <![CDATA[
7        import net.eriksjodin.arduino.Arduino;
8        import net.eriksjodin.arduino.events.ArduinoEvent;
9        
10        private const SLIDER1:int = 0;
11        private const SLIDER2:int = 1;
12        private const SLIDER3:int = 2;    
13        
14        [Bindable] private var value1:int = 0;
15        [Bindable] private var value2:int = 0;
16        [Bindable] private var value3:int = 0;
17            
18        private var arduino:Arduino = new Arduino();
19        
20        private function init():void {
21            arduino.requestFirmwareVersion();
22            arduino.addEventListener(ArduinoEvent.FIRMWARE_VERSION, initArduino);
23        }
24        
25        private function initArduino(event:Event):void {
26            arduino.setAnalogPinReporting(SLIDER1, Arduino.ON);
27            arduino.setAnalogPinReporting(SLIDER2, Arduino.ON);
28            arduino.setAnalogPinReporting(SLIDER3, Arduino.ON);
29            
30            arduino.addEventListener(ArduinoEvent.ANALOG_DATA, onReceiveData);
31        }
32        
33        private function onReceiveData(event:ArduinoEvent):void {
34            if (event.pin == SLIDER1) {
35                value1 = event.value/4;
36            }
37            else if (event.pin == SLIDER2) {
38                value2 = event.value/4;
39            }
40            else if (event.pin == SLIDER3) {
41                value3 = event.value/4;
42            }
43        }
44        ]]>
45    </fx:Script>
46    
47    <s:Graphic>
48        <s:Ellipse x="
{this.width/4-value1/2}" y="{this.height/2-value1/2}" width="{value1}" height="{value1}">
49            <s:fill>
50                <s:SolidColor color="
0xFF0000" />
51            </s:fill>
52        </s:Ellipse>
53        <s:Ellipse x="
{this.width/2-value2/2}" y="{this.height/2-value2/2}" width="{value2}" height="{value2}">
54            <s:fill>
55                <s:SolidColor color="
0x00FF00" />
56            </s:fill>
57        </s:Ellipse>
58        <s:Ellipse x="
{3*this.width/4-value3/2}" y="{this.height/2-value3/2}" width="{value3}" height="{value3}">
59            <s:fill>
60                <s:SolidColor color="
0x0000FF" />
61            </s:fill>
62        </s:Ellipse>        
63    </s:Graphic>
64
65</s:Application>

Real time light level graphing in Flex

This Flex code runs in a browser and graphs in real time light levels using HTTP calls to an Arduino running a simple web server.

view plain print about
1<?xml version="1.0" encoding="utf-8"?>
2<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init()">
3
    <mx:Script>

4        <![CDATA[
5            import mx.collections.ArrayCollection;
6            import mx.rpc.events.FaultEvent;
7            import mx.rpc.events.ResultEvent;
8            
9            [Bindable] private var lightData:ArrayCollection = new ArrayCollection();
10            private var sampleno:int = 0;            
11            private var timer:Timer = new Timer(50);
12            
13            private function init():void {
14                arduino.send();
15                timer.addEventListener(TimerEvent.TIMER, callArduino);
16                timer.start();
17            }
18            
19            private function callArduino(event:TimerEvent):void {
20                arduino.send();    
21            }
22            
23            private function gotData(event:ResultEvent):void {
24                var envData:XML = event.result as XML;
25                lightData.addItem({light:envData.analog[4].@value, sample:sampleno++});
26            }
27        ]]>
28    </mx:Script>
29    
30    <mx:HTTPService id="arduino" url="http://10.0.0.20/" resultFormat="e4x" result="gotData(event)" />

31    
32    <mx:Text text="Arduino Ethernet" fontWeight="bold" fontSize="24" />

33 <mx:LineChart showDataTips="true" dataProvider="{lightData}">

34 <mx:series>

35 <mx:LineSeries xField="sample" yField="light" form="curve" displayName="Light" />
36 </mx:series>
37 </mx:LineChart>
38
39</mx:Application>

Arduino Web Server

This Arduino code returns the values of the analog inputs as structured XML. You can make HTTP calls to obtain the analog values and display them. this was used in the real time light level graphing in Flex above.

view plain print about
1/*
2 * Web Server
3 *
4 * A simple web server that shows the value of the analog input pins.
5 */

6
7#include <Ethernet.h>
8#include <SPI.h>
9
10byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
11byte ip[] = { 10,0,0,20 };
12
13Server server(80);
14
15void setup()
16{
17 Ethernet.begin(mac, ip);
18 server.begin();
19}
20
21void loop()
22{
23 Client client = server.available();
24
25 if (client) {
26 // an http request ends with a blank line
27
boolean blankline = true;
28
29 while (client.connected())
30 {
31 if (client.available())
32 {
33 char c = client.read();
34 // if we've gotten to the end of the line (received a newline
35
// character) and the line is blank, the http request has ended,
36
// so we can send a reply
37
if (c == '\n' && blankline) {
38 // send a standard http response header
39
client.println("HTTP/1.1 200 OK");
40 client.println("Content-Type: text/xml");
41 client.println();
42
43 // output the value of each analog input pin
44
client.print("<values>");
45 for (int i = 0; i < 6; i++) {
46 client.print("<analog pin='");
47 client.print(i);
48 client.print("
' value='");
49 client.print(analogRead(i));
50 client.println("
' />");
51 }
52 client.print("</values>");
53 break;
54 }
55 if (c == '\n') {
56 // we're starting a new line
57
blankline = true;
58 }
59 else if (c != '\r') {
60 // we've gotten a character on the current line
61
blankline = false;
62 }
63 }
64 }
65
66 client.flush();
67 client.stop();
68 }
69}

Any questions on my talk just comment below or email me.

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Justin, great meeting you at FATC, thanks again for the excellent talk and conversation afterward. The "Real time light level graphing in Flex" was wonderful and I look forward to replicating it with a few different sensors and via WiFi communication to an Android device in the near future. I was thinking of using the wiFly Shield from Sparkfun. Any recommendations on which WiFi shield I should go with?

Thanks,
Peter (from Miami)
# Posted By Peter Carabeo-Nieva | 6/22/11 1:13 AM
Hi Peter, nice catching up with you also. I've not used the Sparkfun WiFi shield but should do what you need. As far as I can see it doesn't use the standard Ethernet library and you need to use their library so my code may require a few changes, but that's all part of the fun. There's a number of ethernet boards out now (both shields and combo arduino/ethernet) including some that support power over ethernet. Could they be an option?
# Posted By Justin Mclean | 6/22/11 1:30 AM
I definitely like the PoE option if I were to go the wired route and that might work out fine for some applications that I have in mind. But the reason I was mainly interested in WiFi options is because then I can create projects that can be fully mobile and easily shared with anyone who has a flash/AIR-enabled smartphone. The arduino+wifi shield+sensors would act as a sort of extension of their smartphone, giving them access to other sensors/actuators that are not commonly available on smartphones.
# Posted By Peter Carabeo-Nieva | 6/22/11 1:49 AM
Yep WiFi works well with mobile phones. You still need some sort of power source for the Arduino/shield so it may be be possible to totally have it "wireless" for long periods (wifi consumes a bit of power). You could of course plug the Arduino into any router via ethernet and it would still be accessible via WiFi (assuming there's a wifi router about) as long as it has a well known domain name or ip address. (Dynamic DNS and router port forwarding for instance). Guess it comes down to how portable you want the setup.
# Posted By Justin Mclean | 6/22/11 2:00 AM
Hi Justin,

It was nice meetint you at FATC. I was inspired by the ideas and little talk about how to hook up the arduino with other hardware devices. Can you point to me, or do you have a post where I can purchase a big red button type of hardware interface? You mentioned that there are companies in Hong Kong that build such components. I would like to make up a game.

BTW, the arduino kit that you gave my daughter was tickled pink to open it. I plan to take some time this summer with her to get something working.

Ciao, have a nice time in Italy!
# Posted By David Jumeau | 6/22/11 10:42 PM
Hi David it was good catching up with you at FATC. Have fun with your daughter building something cool with the kit!

Actually turns out I obtained the big red buttons from SparkFun (not SeeedStudio as I first thought) you can see them here http://www.sparkfun.com/products/9181.

I ended replacing the 12V lamp with a LED so that it would be easier to control with an arduino.
# Posted By Justin Mclean | 6/23/11 1:04 AM