[LinkIt ONE 教學] 透過 Wifi 取得網頁內容
LinkIt One 教學又來囉,這一次是把指定網站的字元讀回來,字元讀回來之後,後面就可以做很多事情啦~ 本文參考LinkIt One 官方使用手冊
只要把 Wifi / 藍牙二合一天線接上去就好,別接錯啊!
本支程式有幾個重點請您注意,完整的程式碼在文末。請慢慢看完以下說明:
以下是截取 www.appinventor.tw" 的執行畫面,但經過測試,有些不是 www 開頭的網站爬不回來,還在測試中。
網路設定,在此輸入無線網路帳密。
#define WIFI_AP "Name_of_your_AP"
#define WIFI_PWD "Password_of_your_AP"
LWiFi.begin();
LWiFi.connect(WIFI_AP); // if the AP is not encrypted
LWiFi.connectWEP(WIFI_AP, WIFI_PWD); // if the AP uses WEP encryption
LWiFi.connectWPA(WIFI_AP, WIFI_PWD); // if the AP uses WPA encryption
連接指定網站
#define SITE_URL "www.appinventor.tw"
LWiFiClient c; //用這個物件來執行網路動作
c.connect(SITE_URL, 80);
送出 Http request
c.println("GET / HTTP/1.1");
c.println("Host: " SITE_URL);
c.println("Connection: close");
c.println();
取得網站內容,透過 c 來將網頁字元逐一讀回來,並顯示於 serial monitor
int v;
while(c.available())
{
v = c.read(); // return one byte at a time
if(v < 0)
break; // no more data
}
以下為完整的 code,歡迎自己玩玩看喔!
[pastacode lang="c" message="LinkIt One 讀取網頁" highlight="" provider="manual"]
本支程式有幾個重點請您注意,完整的程式碼在文末。請慢慢看完以下說明:
以下是截取 www.appinventor.tw" 的執行畫面,但經過測試,有些不是 www 開頭的網站爬不回來,還在測試中。
網路設定,在此輸入無線網路帳密。
#define WIFI_AP "Name_of_your_AP"
#define WIFI_PWD "Password_of_your_AP"
LWiFi.begin();
LWiFi.connect(WIFI_AP); // if the AP is not encrypted
LWiFi.connectWEP(WIFI_AP, WIFI_PWD); // if the AP uses WEP encryption
LWiFi.connectWPA(WIFI_AP, WIFI_PWD); // if the AP uses WPA encryption
連接指定網站
#define SITE_URL "www.appinventor.tw"
LWiFiClient c; //用這個物件來執行網路動作
c.connect(SITE_URL, 80);
送出 Http request
c.println("GET / HTTP/1.1");
c.println("Host: " SITE_URL);
c.println("Connection: close");
c.println();
取得網站內容,透過 c 來將網頁字元逐一讀回來,並顯示於 serial monitor
int v;
while(c.available())
{
v = c.read(); // return one byte at a time
if(v < 0)
break; // no more data
}
以下為完整的 code,歡迎自己玩玩看喔!
[pastacode lang="c" message="LinkIt One 讀取網頁" highlight="" provider="manual"]
#include <LWiFi.h>
#include <LWiFiClient.h>
#define SITE_URL "www.mediatek.com"
#define WIFI_AP "您的 AP 名稱" //請輸入所要連的AP名稱
#define WIFI_PWD "AP 密碼" // 請輸入AP 密碼
LWiFiClient c;
void setup() {
Serial.begin(9600);
LWiFi.begin();
Serial.println();
Serial.print("Connecting to AP...");
if(LWiFi.connectWEP(WIFI_AP, WIFI_PWD) < 0)
{
Serial.println("FAIL!");
return;
}
Serial.println("ok");
Serial.print("Connecting to site...");
if(!c.connect(SITE_URL, 80))
{
Serial.println("FAIL!");
return;
}
Serial.println("ok");
Serial.println("send HTTP GET request");
c.println("GET / HTTP/1.1");
c.println("Host: " SITE_URL);
c.println("Connection: close");
c.println();
}
void loop() {
int v;
while(c.available())
{
v = c.read();
if(v < 0)
break;
Serial.print((char)v);
}
delay(100);
}
[/pastacode]
留言 💬 (0)
還沒有留言,來當第一個。