簡單記錄一下Ethernet library該注意的事項:
1. Ethernet library主要有5個class
|- Ethernet Class -> 主要是用來初始化設定
|- IPAddress Class -> 即IP Address的class
|- Server Class -> 用來建立Server使用
|- Client Class -> 用來建立Client使用
|- EthernetUDP class -> 收發UDP的message
2. Ethernet Class:
依照官網的敘述:
With version 1.0, the library supports DHCP. Using Ethernet.begin(mac) with the proper network setup, the Ethernet shield will automatically obtain an IP address. This increases the sketch size significantly.
如果區網中有配置DHCP,直接使用Ethernet.begin(mac)即完成初始化的動作,Ethernet shield會自動獲得IP address
Ethernet Class包含的method:
|- begin() -> 初始化Ethernet object
|- localIP() -> return the local IP
|- maintain()
3. IPAddress Class:
依照官網的敘述:
Defines an IP address. It can be used to declare both local and remote addresses.
所以IPAddress Class是用來定義IP address
註:官網中描述的使用方法:
IPAddress ip(192,168,1,1);
Ethernet.begin(mac, ip, gateway, subnet);
4. 自動取得IP Address的Sample Code:
#include
#include
byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xED};
byte server[] = {173,194,72,138};
EthernetClient client;
void setup(){
Serial.begin(9600);
if(Ethernet.begin(mac)==0){
Serial.println("Failed to configure Ethernet usin DHCP!");
while(1);
}
delay(1000);
Serial.print("IP Address: ");
//Ethernet.localIP() -> Obtains the IP address of the Ethernet shield.
//Useful when addres is auto assigned through DHCP
IPAddress myIPAddress = Ethernet.localIP();
Serial.print(myIPAddress);
if(client.connect(server,80)){
Serial.println("connected...");
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
}
else{
Serial.println("connection failed!");
}
}
void loop(){
if(client.available()){
char c = client.read();
Serial.print(c);
}
if(!client.connected()){
Serial.println();
Serial.println("disconnecting");
while(1);
}
}
run的結果:
沒有留言:
張貼留言