Can't Figure out random hangs
Posted: Sat Apr 29, 2017 3:33 am
Hi, I'm new to running Arduino code on a nodemcu. I'm making a WiFi thermostat with remote temperature sensor, and the sensor portion hangs randomly and needs to be reset. Right now I'm stumped, here's a copy of my sensor code:
Could I get some pointers and tips to improve this?
Code: Select all
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <DHT.h>
#define DHTPIN D2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "----";
const char* password = "----";
const int connectionTimeout = 3000;
int setPoint = 70;
int currentTemp = 70;
int heatCoolOff = 0; // 0 for off--1 for heat--2 for cool
int onOff = 0;
unsigned long prevMillis = 0;
long interval = 1000 * 60 * 10;
WiFiServer server(80);
void setup() {
Serial.begin(115200);
pinMode(D0, OUTPUT);
digitalWrite(D0, HIGH);
delay(2000);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("\nConnecting to WiFi...");
dht.begin();
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
digitalWrite(D0, LOW);
server.begin();
Serial.println();
Serial.println(WiFi.localIP());
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - prevMillis >= interval)
{
prevMillis = currentMillis;
refresh();
}
WiFiClient client = server.available();
if (!client)
return;
int waitTime = 0;
while (!client.available())
{
delay(10);
waitTime += 10;
if( waitTime >= connectionTimeout)
{
client.stop();
return;
}
}
String request = client.readStringUntil('\r');
client.flush();
if(request.indexOf("LEDOFF") != -1)
digitalWrite(D0, HIGH);
if(request.indexOf("Heat") != -1)
heatCoolOff = 1;
if(request.indexOf("Cool") != -1)
heatCoolOff = 2;
if(request.indexOf("Off") != -1)
heatCoolOff = 0;
request.remove(0, 5);
request.remove(2);
int temp = request.toInt();
if (temp >= 50 && temp <= 80)
setPoint = temp;
refresh();
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
Serial.println(onOff);
client.println(onOff);
client.println(currentTemp);
client.println(setPoint);
client.println(heatCoolOff);
}
void refresh()
{
currentTemp = dht.readTemperature(true);
HTTPClient http;
if(heatCoolOff == 1)
{
if (currentTemp < setPoint - 1 && onOff != 1)
{
http.begin("http://192.168.1.254/HEAT");
http.GET();
onOff = 1;
}
else if (currentTemp > setPoint + 1 && onOff != 0)
{
http.begin("http://192.168.1.254/OFF");
http.GET();
onOff = 0;
}
}
else if(heatCoolOff == 2)
{
if(currentTemp > setPoint + 1 && onOff != 1)
{
http.begin("http://192.168.1.254/COOL");
http.GET();
onOff = 1;
}
else if(currentTemp < setPoint - 1 && onOff != 0)
{
http.begin("http://192.168.1.254/OFF");
http.GET();
onOff = 0;
}
}
else if(heatCoolOff == 0)
{
if(onOff != 0)
{
http.begin("http://192.168.1.254/OFF");
http.GET();
onOff = 0;
}
}
http.end();
}
Could I get some pointers and tips to improve this?