在设置函数中,nodemcu 请求你的 WiFi 路由器获得一个 IP 分配。然后在路由器分配 IP 之后启动服务器。串行通信波特率也初始化在安装循环。波特率设置为9600bps。
代码:
/*****************************************************
* Written by : Usman Ali Butt *
* Dated : 4 july 2018 *
* Property off : www.microcontroller-projecct.com *
****************************************************/
#include
#include "DHT.h" // DHT11 temperature and humidity sensor Predefined library
int Raw = A0; //Analog channel A0 as used to measure temperature
int threshold = 16; //Nodemcu digital pin water sensor read-GPIO16---D0 of NodeMCU
int Solenoid = 13; // GPIO13---D7 of NodeMCU--Motor connection
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address on serial monitor
Serial.print("Use this URL to connect: ");
Serial.print("http://"); //URL IP to be typed in mobile/desktop browser
Serial.print(WiFi.localIP());
Serial.println("/");
}
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 request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
float h =0.0; //Humidity level
float t =0.0; //Temperature in celcius
float f =0.0; //Temperature in fahrenheit
float percentage = 0.0; // Calculating percentage of moisture
float reading = 0.0; //Analog channel moisture read
// Match the request
int value = LOW;
if (request.indexOf("/Up=ON") != -1) {
h = dht.readHumidity(); //Read humidity level
t = dht.readTemperature(); //Read temperature in celcius
f = (h * 1.8) + 32; //Temperature converted to Fahrenheit
reading = analogRead(Raw); //Analog pin reading output voltage by water moisture rain sensor
percentage = (reading/1024) * 100; //Converting the raw value in percentage
if (reading<=110){ // If less mositure in soil start the motor otherwise stop
digitalWrite(Solenoid, HIGH);
value = HIGH;
}
else {
digitalWrite(Solenoid, LOW);
value = LOW;
}
}
if (request.indexOf("/Solenoid=ON") != -1) { //Motor ON
digitalWrite(Solenoid, HIGH);
value = HIGH;
}
if (request.indexOf("/Solenoid=OFF") != -1) { //Motor OFF
digitalWrite(Solenoid, LOW);
value = LOW;
}
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("");
client.println("");
client.println("