看了一下如何用Arduino跟Server要求資料的部分,筆記一下
1. Stream: 依照官網分類,Stream是被分類在Function的部分,和Serial一樣,主要是用來Communication 按照官網的敘述: Stream is the base class for character and binary based streams. It is not called directly, but invoked whenever you use a function that relies on it. Stream defines the reading functions in Arduino. When using any core functionality that uses a read() or similar method, you can safely assume it calls on the Stream class. For functions like print(), Stream inherits from the Print class. Stream Function沒辦法直接像C language的方式直接使用,使用的方法比較接近OOP使用method的方式(ex: client.fine(str))。在官網的敘述中描述"invoked whenever you use a function that relies on it."指可以被依賴Stream的object所調用 -> 想成被繼承Stream的object使用。
2. Some of the libraries that rely on Stream include: |- Serial |- Wire |- Ethernet Client |- Ethernet Server |- SD
3. 包含的Function: |- available() |- read() -> 用來讀取data |- flush() |- find() -> 搜尋目前list中是否有指定的String |- findUntil() |- peek() |- readBytes() |- readBytesUntil() |- parseInt() -> 用來parse目前list中的Int |- parseFloat() -> 用來parse目前list中的Float |- setTimeout()
4. 這次比較需要注意的是網站response,以下是在瀏覽器用Google搜尋的結果: a.在搜尋的text field打上50 miles (注意網址列:因為是用GET的方式來要求response,所以在網址列的後方會出現search?q=50+miles) b.注意搜尋到結果: 下圖中框起來的部分是用粗體字 -> 在HTML語法中,粗體字是<b>tag,因此我們要利用此tag來得到我們要求的資料
5. Sample Code: 在Sample Code中用到Stream中的find和parseFloat
#include#include byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xED}; char serverName[] = "www.google.com"; EthernetClient client; void setup(){ Serial.begin(9600); if(Ethernet.begin(mac)==0){ Serial.println("Failed configure Ethernet using DHCP!"); while(1); } delay(1000); Serial.println("connecting..."); } void loop(){ if(client.connect(serverName,80)>0){ Serial.println("connected..."); client.println("GET /search?q=50+km+in+miles HTTP/1.0"); client.println(); } else{ Serial.println("connection failed"); } if(client.connected()){ if(client.find("<b>50 km")){ //find data if(client.find(" = ")){ Serial.print("50 km is "); Serial.print(client.parseFloat()); //parse float Serial.println(" miles"); } } else{ Serial.println("result not found"); } client.stop(); delay(10000); //after 10 second search again! } else{ Serial.println(); Serial.println("not connected"); client.stop(); delay(1000); } }
6. run的結果:
沒有留言:
張貼留言