ตัวอย่างนี้เป็นการ อ่านค่าสวิตช์ด้วย NodeMCU ที่ทำงานเป็น Server
#include <ESP8266WiFi.h> const char* ssid = "Tenda_3EF910"; const char* password = "gift4321"; int sw = D2; WiFiServer server(80); void setup() { Serial.begin(115200); delay(10); pinMode(sw,INPUT_PULLUP); // Connect to WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // Start the server server.begin(); Serial.println("Server started"); // Print the IP address Serial.print("Use this URL to connect: "); Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/SW"); } void loop() { // เช็คถ้า client มีการเชื่อมต่อ WiFiClient client = server.available(); if (!client) { return; } // รอจนกระทั่ง มีการร้องขอข้อมูลจาก client Serial.println("new client"); while(!client.available()){ delay(1); } // อ่านข้อมูลการร้องขอ String request = client.readStringUntil('\r'); Serial.println(request); client.flush(); // ทำตามคำสั่งที่ client ร้องขอมา int value = LOW; if (request.indexOf("/SW") != -1) { value = digitalRead(sw); } // ส่งค่าตอบกลับไปยัง client client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // do not forget this one client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<meta http-equiv='refresh' content='3' >"); //client.println("<script>alert('ArduinoALL');</script>"); client.print("Switch is now: "); if(value == LOW) { client.println("ON <img src = 'https://www.arduinoall.net/arduino-tutor/wp-content/uploads/2016/11/001.jpg'>"); } else { client.println("OFF <img src = 'https://www.arduinoall.net/arduino-tutor/wp-content/uploads/2016/11/002.jpg'>"); } client.println("<p>Auto Refresh 3 secion "); client.println("</html>"); delay(1); Serial.println("Client disonnected"); Serial.println(""); }
เปิดโปรกรม Serial Monitor เมื่อ NodeMCU เชื่อมต่อกับแลนได้แล้ว จะแสดง IP Address ให้ทดสอบ
ยังไม่มีคอมเมนต์
คุณสามารถเป็นคนแรกที่คอมเมนต์