我打算用NodeMCU接上DHT22溫溼度感測器、土壤濕度傳感器、5V的繼電器控制水泵開關,然後把資料用無線網路的方式傳到樹梅派資料庫,可是不曉得是NodeMCU效能不夠還是程式問題出現了一個狀況,就是執行預計每隔5,6秒出來的功能是正常的,可是有時候會變成卡個十幾二十秒沒運作(不知道是不是跑不動,好像有可能是資料遺失沒傳送而導致跳過幾筆資料),我是用Arduino IDE開發,接線使用杜邦線
請問有可能是哪裡出問題導致有時候會有延遲?
還有有時候DHT22回傳的值會怪怪的例如:溫度12度可是濕度會有3000度可能會是甚麼問題?
NodeMCU程式碼
#include <ESP8266WiFi.h>
#include <DHT.h>
#define DHTPIN D1 //DHT22感測器 D1
#define soilPin A0 //土壤溼度感測器A0
#define motornow D4 //馬達
#define HOST "192.168.0.16"
const char* ssid = "myssid";
const char* password = "mypassword";
String Motor;
int soilValue;//存儲中間值
int soilMoisture;//定義土壤濕度
DHT dht(DHTPIN, DHT22);
void setup() {
Serial.begin(115200);
delay(10);
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");
// Print the IP address
Serial.print("Your NodeMCU IP is : ");
Serial.print(WiFi.localIP());
}
void loop() {
float t = dht.readTemperature();
float h = dht.readHumidity();
while (isnan(h)){
yield();
h = dht.readTemperature();
//return;
}
while (isnan(t)){
yield();
t = dht.readTemperature();
//return;
}
soilValue = analogRead(soilPin); //讀取土壤感測器上的電壓值
soilMoisture = map(soilValue,0,1023,100,0);//把電壓值按照[0,1023]映射到[100,0]
Serial.println("-------------------");
Serial.print("溫度:");
Serial.println(t);
Serial.print("濕度:");
Serial.println(h);
Serial.print("土壤濕度: ");
Serial.print(soilMoisture);
Serial.println("%");
if (soilValue > 500) { //抽水馬達控制
digitalWrite(motornow, LOW);
Motor ="on";
Serial.println("Relay is turned on.");
} else {
digitalWrite(motornow, HIGH);
Motor ="off";
Serial.println("Relay is turned off.");
}
delay(1000);
WiFiClient client;
while(!client.connect(HOST,80)) {
Serial.println("connection failed");
Serial.println("wait 5 sec...");
delay(1000);
}
String dbserver = HOST;
String getStr = "GET /AddData.php?";
getStr +="Temp=";
getStr += String(t);
getStr +="&Humidity=";
getStr += String(h);
getStr +="&Soilhumidity=";
getStr += String(soilMoisture);
getStr +="Motor=";
getStr += String(Motor);
getStr += " HTTP/1.1\r\n";
getStr += "Host: " + String(dbserver) \
+ "\r\n"+ "Connection: close\r\n\r\n";
client.print(getStr);
delay(10);
client.stop();
delay(5000);
}