Show toolbar

2014年4月29日 星期二

Touch events example

標題:觸控事件範例
JavaScript (index.html):
Start: <div id="t1"></div>
Move: <div id="t2"></div>
End: <div id="t3"></div>
<script type="text/javascript">
document.ontouchstart = function(e) {
    var px = e.changedTouches[0].clientX;
    var py = e.changedTouches[0].clientY;
    e.preventDefault();
    document.getElementById('t1').innerHTML = '(' + px + ', ' + py + ')';
};
document.ontouchmove = function(e) {
    var px = e.changedTouches[0].clientX;
    var py = e.changedTouches[0].clientY;
    e.preventDefault();
    document.getElementById('t2').innerHTML = '(' + px + ', ' + py + ')';
};
document.ontouchend = function(e) {
    var px = e.changedTouches[0].clientX;
    var py = e.changedTouches[0].clientY;
    e.preventDefault();
    document.getElementById('t3').innerHTML = '(' + px + ', ' + py + ')';
};
</script>

說明:
觸控事件取得座標範例。

2014年4月13日 星期日

Servo Motor Control with an Arduino

標題:使用Arduino控制伺服馬達


Arduino (servo_motor):
#include <Servo.h> 
Servo myservo;
const int umin = 500, umax = 2400, umid = (umin + umax)/2;
const int buttonPin = 2;
int buttonState = 0, buttonDownState = 0, motorState = 0;

void setup() {
    pinMode(buttonPin, INPUT);
    myservo.attach(9, umin, umax);
    myservo.writeMicroseconds(umid);
    delay(3000);
}

void loop() {
    buttonState = digitalRead(buttonPin);
    if (buttonState == HIGH) {
        buttonDownState = 1;
    } else {
        if(buttonDownState == 1) {
            if(motorState == 0) {
                myservo.writeMicroseconds(umin);
                motorState = 1;
            } else if(motorState == 1) {
                myservo.writeMicroseconds(umid);
                motorState = 2;
            } else if(motorState == 2) {
                myservo.writeMicroseconds(umax);
                motorState = 3;
            } else {
                myservo.writeMicroseconds(umid);
                motorState = 0;
            }
            buttonDownState = 0;
        }
    }
}

Arduino Diecimila
電阻 - 10kΩ
伺服機 - GWS S03T

說明:
按鈕依序輸出脈衝寬度最小、中間、最大,以控制依序移動伺服機位置。

2014年3月26日 星期三

C# POST using WebRequest

標題:C#使用WebRequest POST後取得回傳資料
C# (Program.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; //WebRequest WebResponse
using System.IO; //Stream

public class Global
{
    public static string server = "http://127.0.0.1:1337";
}

namespace WebPostRequest
{
    class Program
    {
        static string login(string email, string password)
        {
            //宣告送出資料
            string param = "email=" + email + "&password=" + password;
            byte[] byteArray = Encoding.UTF8.GetBytes(param);

            //Request資料
            WebRequest request = WebRequest.Create(Global.server + "/login");
            request.Credentials = CredentialCache.DefaultCredentials;
            ((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";
            request.Method = "POST";
            request.ContentLength = byteArray.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            //處理資料流
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //Response資料
            WebResponse response = request.GetResponse();
            string rawJsonString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            response.Close();

            return rawJsonString;
        }

        static void Main(string[] args)
        {
            Console.WriteLine( login("test@gmail.com", "abcd1234") );

            Console.WriteLine("\r\nPress enter key to continue....");
            Console.Read();
        }
    }
}

說明:
簡單使用WebRequest POST送出email、password後回傳字串資料的作法。

2014年3月11日 星期二

Dynamic get jsonp

標題:動態取得Jsonp資料
JavaScript (index.html):
<div id="output_getjsonp"></div>
<script type="text/javascript">
var getjsonp = function() {
    this.head = document.getElementsByTagName('head')[0] || document.documentElement;
    this.current = null;
    this.queue = [];
};
getjsonp.prototype.request = function(q) {
    var fid = (q.fid||'_getjsonp') + new Date().getTime();
    console.log(fid);
    var script = document.createElement('script');
    script.src = q.url.replace('callback=?', 'callback=' + fid);
    this.queue.push({
        fid : fid,
        script : script,
        load : q.load
    });
    if(!this.current) this.action();
};
getjsonp.prototype.action = function() {
    var self = this;
    this.current = null;
    if(this.queue.length) {
        this.current = this.queue.shift();
        window[this.current.fid] = function(data) {
            self.head.removeChild(self.current.script);
            self.current.load && self.current.load(data);
            self.action();
        };
        this.head.appendChild(this.current.script);
    }
};

var jsonp = new getjsonp();
jsonp.request({
    fid : '_myjsonp',
    url : 'http://codeboxy.blogspot.com/feeds/posts/default?alt=json&callback=?',
    load : function(data) {
        document.getElementById('output_getjsonp').innerHTML = data.feed.entry[0].title.$t;
    }
});
</script>

範例結果:

說明:
動態使用jsonp取得json資料,測試支援版本:
  • Google Chrome 33.0.1750.146 m
  • Firefox 27.0.1
  • IE 11.0.9600.16518

2014年3月10日 星期一

JavaScript Advanced Logical Operators

標題:JavaScript邏輯運算子進階用法
JavaScript (main.js):
function foo() {
    console.log('Hello');
    return true;
}
function bar() {
    console.log('World');
    return false;
}
foo() && bar(); //Hello World
bar() && foo(); //World
foo() || bar(); //Hello
bar() || foo(); //World Hello

說明:
1. foo()為true 則會繼續執行bar()
2. bar()為false不會繼續執行foo()
3. foo()為true 不會繼續執行bar()
4. bar()為false則會繼續執行foo()