2013年5月15日 星期三

Arduino 利用Ethernet傳送及接收

今天要說的不算是照門只說程式,如果有什麼問題還請大家指教

ps 有任何的電子學的問題及關於電子學,我一律沒辦法回答大家(我不是很專業也怕誤人子弟)


測試環境及版本
OSX 10.8.3
Arduino 1.0.4


設備
Mega2560
Ethernet with PoE module



要注意幾個,宣告幾個變數
mac         為你設備的mac號
ip            你這台Ethernet的ip你可以自行設定(網段要一樣才收得到, ip不可跟其他設備衝突)
remote    你想要傳送的ip位置
Listen(x) 你x可以設定你想監聽的port號


EthernetSend()    -  傳送到指定位置
- Deliver():
client.print("GET /");
要設在client起始接著GET /斜線後面接你的目標網址
例如你可以設定成
client.print("GET /save.php?a=123&b=456");


EthernetListen()  -  監聽目標
當去瀏覽這個網頁就會啟動function
裡面的Request為回傳網頁資訊包含瀏覽的路徑, get/post, ....
接下的Control是針對瀏覽路徑知道要怎麼Control 設備(LED亮/滅)


github: https://github.com/jiunjiun/Arduino_Ethernet


下面為程式碼

#include <Ethernet.h>
#include <SPI.h>
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // 乙太網路
IPAddress ip(192, 168, 0, 30); // local IP
IPAddress remote(192, 168, 0, 130); // remote IP
EthernetServer Listen(80); // server
EthernetClient client; // client
int time = 0;
String Request;
void setup() {
Ethernet.begin(mac, ip);
Listen.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
EthernetSend();
EthernetListen();
}
void EthernetSend() {
if(time == 5) {
Deliver();
time = 0;
}
time++;
}
void Deliver() {
Serial.println("connecting...");
if (client.connect(remote, 80)) {
Serial.println("connected");
client.print("GET /"); //
client.print("/");
client.println(" HTTP/1.0");
client.println();
client.stop();
client.flush();
Serial.println("send!!");
} else {
Serial.println("connection failed");
}
}
void EthernetListen() {
// Listen for incoming clients
EthernetClient client = Listen.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Request += c;
if (c == '\n' && currentLineIsBlank) {
Control(Request);
Serial.println(Request);
Request = "";
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
client.stop();
Serial.println("client disonnected");
}
}
void Control(String Request) {
if(Request.indexOf("/do_something1") > -1) {
//do something 1 ....
} else if(Request.indexOf("/do_something2") > -1) {
//do something 2 ....
}
}



沒有留言:

張貼留言