https://gist.github.com/clive520/2372dcfd2b080c37d867aa7a7eb3e540
#include <WiFi.h>
#include <WiFiMulti.h> //多個SSID自動連接library
WiFiMulti wifiMulti;
#define LED_BUILTIN 2
WiFiServer server(80);
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW) ;
Serial.begin(9600);
delay(1000);
//寫入常用的SSID和密碼
wifiMulti.addAP("clive_lef", "12345678");
wifiMulti.addAP("clive_1F", "12345678");
wifiMulti.addAP("book", "12345678");
// 開始連接WIFI
Serial.println("Connecting Wifi...");
if (wifiMulti.run() == WL_CONNECTED) { //連接多個WIFI
delay(50);
Serial.println("");
Serial.print("Successful Connecting to Access Point:");
Serial.println(WiFi.SSID());
Serial.print("SSID Signal strength:");
Serial.println(WiFi.RSSI());//WiFi.RSSI()訊號強度
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());//WiFi.localIP()連接到的IP
for (int count = 0; count < 5; count++) { //成功時亮內建的LED,閃爍5次
digitalWrite(LED_BUILTIN, HIGH) ;
delay(500);
digitalWrite(LED_BUILTIN, LOW) ;
delay(500);
}
}
server.begin(); //啟動web server
}
int value = 0;
void loop() {
WiFiClient client = server.available(); // 監聽是否有人連網
if (client) { // 如果有人連入,
Serial.println("New Client."); // 列印有人連入訊息
String currentLine = ""; // 建立文字字串currentLine存放客戶端的傳入數據
while (client.connected()) { // 當客戶端還在連接時不斷重複
if (client.available()) { // 如果有要從客戶端有其他訊息 讀取其訊息,
char c = client.read(); // 將訊息存入字串c
Serial.write(c); // 列印出來
if (c == '\n') { // if the byte is a newline character
//建立網頁上可以看到的內容
if (currentLine.length() == 0) {
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
if (digitalRead(2) == LOW) {client.print(" LED OFF .<br>");}
else {client.print(" LED ON .<br>");} //判斷LED適量或熄滅,並於網頁顯示
client.print("Click <a href=\"/H\">here</a> to turn the LED on GPIo 2 on.<br>");
client.print("Click <a href=\"/L\">here</a> to turn the LED on GPIo 2 off.<br>");//製作兩個連結去開關LED
client.println();
break;
} else {
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
//提取訊息,判斷要做的事情
if (currentLine.endsWith("GET /H")) {
digitalWrite(LED_BUILTIN, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
digitalWrite(LED_BUILTIN, LOW); // GET /L turns the LED off
}
}
}
// 關閉網頁連結
client.stop();
Serial.println("Client Disconnected.");
}
}
沒有留言:
張貼留言