Monday, March 6, 2017

nodemcu 模擬路燈

網頁


電路圖


程式碼


#include <ESP8266WebServer.h>
int sensorPin = 2;
int value = 0;
const char* ssid = "AP";
const char* password = "123456789";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
// prepare GPIO2
pinMode(0, INPUT);
pinMode(2, OUTPUT);
digitalWrite(2, 0);
// 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.println(WiFi.localIP());
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
// Match the request
int val;
if (req.indexOf("/LED=ON") != -1)
val = 1;
else if (req.indexOf("/LED=OFF") != -1)
val = 0;
else if (req.indexOf("/LED=check") != -1)
val = -1;
else {
Serial.println("invalid request");
client.stop();
return;
}
// Set GPIO2 according to the request
client.flush();
// Prepare the response
client.println("<html>");
client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a>");
client.println("<a href=\"/LED=check\"\"><button>Led Status</button></a><br />");
client.println("</html>");
// Send the response to the client
delay(1);
Serial.println("Client disonnected");
String tmp="";
value = analogRead(0);
//Serial.println(value, DEC);
if(val==1 ){
tmp="Very bright";
digitalWrite(2, val);
}
else if(val==0 ){
tmp="Very Dark";
digitalWrite(2, val);
}
else if (val==-1){
if(value<204){
tmp="Very bright";
Serial.println("Very bright");
digitalWrite(2, 0);
val = 1;
}
else if (value > 204 && value <=408){
Serial.println("Ordinary bright");
tmp="Ordinary bright";
digitalWrite(2, 0);
val = 1;
}
else if (value > 408 && value <=612){
Serial.println("Medium light");
tmp="Medium light";
digitalWrite(2, 0);
val = 1;
}
else if (value > 612 && value <=816){
Serial.println("Dark");
tmp="Dark";
digitalWrite(2, 1);
val = 0;
}
else if (value > 816 && value <=1020){
Serial.println("Very Dark");
tmp="Very Dark";
digitalWrite(2, 1);
val = 0;
}
}
String s = "<html>\r\nGPIO is now ";
s += (val)?"high":"low ";
s += " Light Power:"+tmp;
s += "</html>\n";
client.print(s);
// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}
view raw light.lua hosted with ❤ by GitHub