顯示具有 [Action Script] 標籤的文章。 顯示所有文章
顯示具有 [Action Script] 標籤的文章。 顯示所有文章

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

2011年3月1日 星期二

[Action Script]華攝氏轉換

Action Script3版:

package  
{
import flash.display.Sprite;

/**
* ...
* @author james
*/
public class Temperature extends Sprite
{
public function Temperature()
{
var input:Number=10; //自行改變溫度
var f:Number;
f = convert2F(input)
trace("攝氏溫度:"+input+" = 華氏溫度: "+f);
}
private function convert2F(c:Number):Number{
var f:Number = 0;
f = (9.0 * c) / 5.0 + 32.0;
return f;
}
}
}



Java版:

public class Temperature {

/**
* @param args
*/
static double convert2F(double c){
double f;
f=(9.0*c)/5.0+32.0;
return f;
}
public static void main(String[] args) {
// TODO Auto-generated method stub

java.util.Scanner sc=new java.util.Scanner(System.in);
System.out.println("請輸入攝氏溫度:");
double c=sc.nextDouble();
double f=convert2F(c);
System.out.println("攝氏溫度"+c+"=華氏"+f);
}

}

2011年2月24日 星期四

[Action Script]用timer寫forloop

使用timer來取代for回圈

可以避掉Flash逾時的問題,但出現逾時的情形,就代表程式要重新修正

除非有其他因素

package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* ...
* @author james chang
*/
public class addEventfor extends Sprite {
public var sum:int = 0;
public var i:int = 1;
public var timer:Timer = new Timer(100);
public function addEventfor(){
//for (var i:int= 0; sum <= 10; i++) {
//trace(i);
//sum += 1;
//}
timer.addEventListener(TimerEvent.TIMER, forloop);
timer.start();
}

private function forloop(e:TimerEvent):void {
sum += 1;
if (sum >= 10){
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, forloop);
}
trace(sum);
i++;
}

}

}

2010年12月28日 星期二

[Action Script]Zend Amf安裝

出現

Warning: require_once(Zend/Amf/Server.php) [function.require-once]: failed to open stream: No such file or directory in C:\AppServ\www\ZendAMP\gateway.php on line 2

Fatal error: require_once() [function.require]: Failed opening required 'Zend/Amf/Server.php' (include_path='.;C:\php5\pear') in C:\AppServ\www\ZendAMP\gateway.php on line 2



的解法

其實也就是他找不到這個資料夾

要先到C裡面的php.ini

找到
;include_path = ".;c:\php\includes;

這一行

將;C:\php\library"貼到後面

並將最前面的;拿掉


會變成

;include_path = ".;c:\php\includes;C:\php\library"


要注意一下"的位置

然後再到php打上
<?php
require_once 'Zend/Amf/Server.php';
$server=new Zend_Amf_Server();
$server->addDirectory('AMFApp/');
$response = $server->handle();
echo $response;
?>

執行後即可看見見

Zend Amf Endpoint

2010年12月14日 星期二

[Action Script]load XML註釋資料

平常load XML檔是比較少注意到此功能

因為Action Script預設是為true ,將註釋資料忽略

若今天要將XML資料內的註釋一起load進來該如何做呢?

加上這兩行指令即可


              XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;


以下為完整的範例

先建一個xmldata.xml

內容自己輸入xml格式,以下是我的例子

<?xml version="1.0" encoding="UTF-8"?>
<data>
<!--項目列表1--->
<item>
<name>James</name>
<email>dickfala@gmail.com</email>
<webSite>http://bruce620.blogspot.com/</webSite>
</item>
<!--項目列表2--->
<item>
<name>xxx</name>
<email>xxxx@gmail.com</email>
<webSite>http://www.google.com.tw</webSite>
</item>
<!--項目列表3--->
<item>
<name>ooo</name>
<email>ooo@yahoo.com</email>
<webSite>http://www.yahoo.com.tw</webSite>
</item>
</data>


再使用Action Script外部檔案輸入以下程式

此為外部AS package寫法

package {
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
/**
* @author james
* http://bruce620.blogspot.com/
*/
public class loadxmldata extends Sprite {
private var _urlLoader:URLLoader;
private var _xml:XML;
public function loadxmldata(){
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
_urlLoader = new URLLoader();
_urlLoader.load(new URLRequest("xmldata.xml"));
_urlLoader.addEventListener(Event.COMPLETE, onloadercompletehandler);
}
private function onloadercompletehandler(e:Event):void {
_xml = new XML(e.target.data);
trace(_xml);
}
}
}

輸出後就可以看到

<!--項目列表1--->
<!--項目列表2--->
<!--項目列表3--->


的註釋資料囉~

2010年10月8日 星期五

AS3漸進公式 (August 17, 2009)

漸進公式

移動值=(目標值-現在值)/漸進係數;
現在值=現在值+移動量;

→ 現在值=現在值+(目標值-現在值)/漸進係數

→現在值+=(目標值-現在值)/漸進係數