2013年9月13日 星期五

Arduino 與 Flash as3連接


Rich Text Area. 離上次發文章是去年了也  

時間過真快

看來記錄些東西是必要的

之前記錄了Flash 接 arduino也是在去年的事 

那時好像也沒有真的接出來

今年這個時候又要用到結果一直沒有解答

網路找的範例怎都try不出來喏@@~

後來認真的思考自己寫一個  不知是自己進步了還是巧合呢(笑)

其實也沒有很難 囧..但花了我一些時間找資料

arduino  <-------> Flash 要透過中介軟體

因為Flash好像不能讀Serial的資料?! (有錯請指正)

中介軟體找到兩種

一種為 TinkerProxy (紅色背景的中介小程式)  但我一直沒找到這個軟體 =.=

後來死心改回找serproxy  我用0.1.3版的 ,其他0.1.1好像也可以通啦 

然後第一步就是要先傳pde檔到arduino

pde的內容是什麼呢

以下為基本的範例 就是我們用Flash AS3來讀可變電阻的類比數值讓他顯示在Flash上囉

==================先用Arduino程式 upload 這個pde檔=======================



int potPin = 0;    
int val = 0;     

void setup() {
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
  Serial.begin(9600);
}

void loop() {
  val = analogRead(potPin);    
  Serial.print(val,DEC);
  delay(100);
  Serial.print(0,BYTE);
  delay(100);
  
}

===============================================================
網路找的範例很多都是寫printByte 那個要改成Serial.print
Serial.print(val,DEC);
Serial.print(0,BYTE);
好像不能用println的樣子 我忘記了  好像跟那個XML有關

第二步呢  
就是要執行serproxy
如果不是0.1.3版的好像要改裡面的port和net_port的值

我的serproxy.cfg的內容長這樣 0.1.3好像不用改

=====================
# Config file for serproxy
# See serproxy's README file for documentation

# Transform newlines coming from the serial port into nils
# true (e.g. if using Flash) or false
newlines_to_nils=true

# Comm ports used
comm_ports=1,2,3,4

# Default settings
comm_baud=19200
comm_databits=8
comm_stopbits=1
comm_parity=none

# Idle time out in seconds
timeout=300

# Port 1 settings (ttyS0)
net_port1=5331

# Port 2 settings (ttyS1)
net_port2=5332

# Port 3 settings (ttyS2)
net_port3=5333

# Port 4 settings (ttyS3)
net_port4=5334

===============================
也就是說上面只支援到Port 4

你要先看一下裝置管理員裡面 你USB的port到幾
如果超果4的話 
請在裝置管理員COM和LPT的USB Serial Port按右鍵→內容→port setting→advanced→com port number選4以內
這樣後面比較不會麻煩啦

上面燒pde進arduino後
再來開serproxy的軟體 
這個中介軟體不可以關唷

再來就是Flash AS3的部份了!!!

這個as3檔也是網路找的
開一個Arduino.as放以下內容
===============================================================================
/* 
*    Class : Arduino v1.0 - 30-JAN-2008
*      This Actionscript3 class makes it easier to connect Flash to the Arduino Board (www.arduino.cc)
*    And, this script is based on beltran berrocal's ARDUINO CLASS v1.0(written in AS2).
*    # copyleft Mr. Excuse, 2008 - mrexcuse@hotmail.com
*    # visit http://november.idv.tw for more information.
*    If you need AS2 version, see www.progetto25zero1.com/b/tools/Arduino
*
*     # credits must also be given to:
*    Yaniv Steiner and the instant soup crew (instantsoup.interaction-ivrea.it) for generating the original flash client
*
*      # you will also need the serialProxy developed by Stefano Busti(1999) and David A. Mellis(2005)
*    that can be found either on the Arduino Site (www.arduino.cc) or redistributed with this example (see update url)
*
*---------------------------------------------------------------
*
*   # METHODS & DESCRIPTIONS
*
*    @@ CONSTRUCTOR
*    @@ creates the Arduino Object inside Flash 
*                usage:
*                        var var ArduinoInstance:Arduino = new Arduino([port], [host]);
*
*                        // port: default is 5331, read the serialProxy documentation to understand this
*                        // host: default is "127.0.0.1"
*    
*    @@ CONNECT
*    @@ connects to the XMLSocket server, you must have provided a port and a host adress via the constructor
*                usage:
*                        ArduinoInstance.connect()
*    
*    @@ DISCONNECT
*    @@ disconnects from the XMLSocket server
*                usage:
*                        ArduinoInstance.disconnect()
*    
*    @@ SEND
*    @@ sends data to Arduino via the XMLSocket server(the serialProxy)
*                usage:
*                        ArduinoInstance.send("some data here");
*    
*    ## EVENT: onDataReceived
*    ## handler of a listener object that listens to data sent from Arduino through the XMLSocket server(the serial Proxy)
*                usage:
*                        Arduino_Listener = new Object(); //create a listener object
*                        Arduino_Listener.onDataReceived = function() { 
*                                //handle the received data in here
*                        }
*                        ArduinoInstance.addEventListener("onReceiveData",Arduino_Listener); //register to listen to the events
*    
*    ## OTHER EVENTS: onConnect,  onConnectError,  onDisconnect
*                usage: use in the same way as the onDataReceived event
*
*-----------------------------------------------------------------------------
*    LICENCE
*   Copyright (C) 2008 Mr. Excuse  |  mrexcuse@hotmail.com
*   http://november.idv.tw
*
*   This library is free software; you can redistribute it and/or modify it 
*    under the terms of the GNU Lesser General Public License 
*    as published by the Free Software Foundation; either version 2.1 of the License
*    
*   You should have received a copy of the GNU Lesser General Public License along with this library;
*   Alternatively you can find it here http://www.gnu.org/licenses/lgpl.html
*    
*   Brief Explanation of the Licence:
*   - you can you use, redistribute, modify this software for free,
*    - you can put it into commercial projects
*   - but if you modify/enhance this Library you should release it under the same licence or alternatively under the GPL licence
*   - in all cases you should also credit the original author and all contributors
*
*-----------------------------------------------------------------------------
*/
package {
    //import mx.events.EventDispatcher;
    import flash.display.Sprite;
    import flash.net.XMLSocket;
    import flash.events.*;


    //class Arduino extends XMLSocket {
    public class Arduino extends XMLSocket{
        
        private var _connected        :Boolean = false;        // 是否已連結
        private var _host        :String  = "127.0.0.1"; // 主機名稱或是IP位址
        private var _port            :int  = 5332;        // 設定連結埠號
        //private var socket            :XMLSocket;
        
            
    //constructor - provide a port number and a host ip adress
    //read the documentation of the SerialProxy to better understandwhat this means
        public function Arduino(port:int = 5331, host:String = "127.0.0.1") {
            //initialize
            
            //socket = new XMLSocket();
            super();
            //flash.events.EventDispatcher.initialize(this);
            
            if((port < 1024) || (port > 65536)){
                trace("** Arduino ** Port must be from 1024 to 65535 ! read the Flash Documentation and the serProxy config file to better understand");
            }else{
                _port = port;
            }
            
            
            
            //check for host or set default
            //if(strHost != undefined) {
                _host = host;
            //}
            
            //register and override responder functions
            //this.onConnect  = onConnectToSocket;
            //this.onClose    = onDisconnectSocket;
            //this.onData        = onDataReceived;
            
            
            // 重新設定監聽者
            configListener(this);
            
            //autoconnect
            xconnect();
        }
        
        // 重新設定監聽者
        private function configListener(dispatcher:IEventDispatcher):void{
            dispatcher.addEventListener(Event.CLOSE, closeHandler);
            dispatcher.addEventListener(Event.CONNECT, connectHandler);
            dispatcher.addEventListener(DataEvent.DATA, dataHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            //dispatcher.addEventListener('onData', onDataReceived);
            //dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
           // dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
        
        }
        
        //---------------------------------------
        //    CONNECT and DISCONNECT + responders
        //---------------------------------------
        
        //connect to the XMLsocket
        public function xconnect ():void {
            super.connect(_host, _port);
        }
        
        //disconnects from the xmlsocket (not Arduino itself)
        public function disconnect () {
            if (_connected)    {
                super.close();
                _connected = false;
            }
        }
        
        // connect handler
        private function connectHandler(event:Event):void{
            trace("** Arduino ** Connecting to "+_host+":"+_port+" . . .");
        }
        
        // close handler
        private function closeHandler(event:Event):void{
            trace("** Arduino ** disconnected");
        }
        
        // data handler
        private function dataHandler(event:DataEvent):void{
            //trace("dataHandler:" + event.data);
            //dispatchEvent('onData');
            //onDataReceived(event.data);
            //e_onReceiveData(str);
            
        }
        
        // io error handler
        private function ioErrorHandler(event:IOErrorEvent):void{
            trace ("** Arduino ** Connection failed! you must launch the serialProxy first");
        }
        
        
        //---------------------------------------
        //    SEND and receive data from server
        //---------------------------------------
    
        /*
        //sends data to arduino
        override public function send(dataStr:String) {
            trace("** Arduino ** send:" + dataStr)
            if (_connected) {
                if (dataStr.length) {
                    trace("** Arduino ** Sending \""+dataStr+"\"");    
                    super.send(dataStr);
                }
            }            
        }
        */

        //overrides XMLSocket.onData in order to have pure string and not the full XML object
        private function onDataReceived (str:String) {
            //trace("** Arduino ** onDataReceived str:"+str);
            //launch event
            e_onReceiveData(str);
        }

        
        
        /*
        //---------------------------------------
        //    EVENTS
        //---------------------------------------
        
        private function e_connectToSocket(){
            var evt = {target:this, type:"onConnect"};
            dispatchEvent(evt);
        }
        
        private function e_connectToSocketError(){
            var evt = {target:this, type:"onConnectError"};
            dispatchEvent(evt);
        }
        
        private function e_disconnectSocket(){
            var evt = {target:this, type:"onDisconnect"};
            dispatchEvent(evt);
        }
        */
        private function e_onReceiveData (str:String){
            trace("** Arduino ** onDataReceived str:"+str);
            var evt = {target:this, type:"onReceiveData"};
            evt.data = str;
            dispatchEvent(new Event(evt));
        }
        
    }
}

===================================================================
記得  上面有一行 
private var _port            :int  = 5332;        // 設定連結埠號

這個部份要改
像我是Port 2所以是5332

如果你是Port 3 就要改5333唷

再來請開啟你的fla檔囉~
先建一個動態文字欄位
把屬性名稱命名為:arduinoval
然後到影格按F9開啟動作面版
把以下程式打進去
====================================================================
//建立port :port2→5332
//中介軟體也的也要改
var test:int=0;
var a:Arduino = new Arduino(5332); 
a.addEventListener(DataEvent.DATA, receiveData);

//接收Arduino傳的數值
function receiveData(event:DataEvent):void{
    trace(event.data);
    arduinoval.text=event.data;

}

======================================================================
記得上面的5332也要改成你的Port對應的net port號碼
然後按下ctrl enter發佈 
轉轉你的可變電阻就可以看到類比數值囉^___^
至於可變電阻的線路圖就麻煩自己找資料了
我的是插analog in 0
其他就5V和GND
至於深入的部份
就看AS3功力怎麼設計囉:P

沒有留言: