2013年2月12日 星期二

Arduino_Ethernet(1)

筆記一下Arduino 如何連接網路:

1. 需要的擴充版:arduino ethernet shield
2. 需要注意的事項(在Arduino-錦囊妙計提到):
   |- SPI.h需要在 Ethernet.h之前include
   |- 宣告client的方法 -> EthernetClient client;
   |- connect的方法 -> if(client.connect(serverName,port)>0)
   |- Server宣告的方法 -> EthernetServer server(port);
   |- DHCP和DNS不需額外include library
   |- 文字和數字的搜尋由Stream來簡化
   |- 增加F(text)struct -> 方便把文字存到flash memroy
arduino ethernet shield長相:

Sample code:
註:MAC address可以隨便設定(板子上完全沒有任何MAC address的標籤!!)
以下是官網的敘述:
Current Ethernet shields come with a sticker indicating the MAC address you should use with them. For older shields without a dedicated MAC address, inventing a random one should work, but don't use the same one for multiple boards.
Arduino官網介紹
#include 
#include 

byte mac[]= {0xDE,0XAD,0xBE,0xEF,0xFE,0xED};
byte ip[] = {192,168,1,50};
byte server[] = {74,125,31,138};

EthernetClient client;
void setup(){
  Serial.begin(9600);  
  Ethernet.begin(mac,ip);  //initializes the ehternet library and network settings
  delay(1000);
  Serial.println("connecting...");
  
  //client.connect(server,80) -> Connects to a specified IP address and port
  if(client.connect(server,80)){ 
    Serial.println("connected");
    //client.println(data) -> Print data  to the server a client is connected
    //ie. send data to server
    client.println("GET /search?q=arduino HTTP/1.0");
    client.println();  // In telnet test, when send get need press enter again
  }
  else{
    Serial.println("connection failed");
  }
}

void loop(){
  if(client.available()){
    char c = client.read();
    Serial.print(c);
  }
  //In telnet test, after we get response, the connection will become disconnect
  //Hence after we get html, we will fall into following if() statement
  if(!client.connected()){
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;);
  }
}



run的結果:

沒有留言:

張貼留言