I am working on a simple project to take temperature and humidity from a DHT22 and post it to Thingspeak.
The code is intended to do the following:
- Every 60 seconds, check to see if it's still connected to WiFi, and reconnect if not
- Every hour, pull data from the DHT22 and Post that to Thingspeak
- Reset the board
Problem:
Everything seems to run fine for 2 - 5 days and then it will just stop sending updates. If I reset the board, it jumps right back into things and goes along its merry way. I can't figure out any rhyme or reason for why it stops working.
Ask:
I have been bashing my head into a wall now for weeks trying to figure this out! Can anyone see something I'm missing or how I might go about troubleshooting this? I can't really leave it plugged into my computer with the serial monitor up for a week at a time to see why it fails. Is there another way to go about this?
My experience level:
I am an armature hobbyist, with some (but limited) programing experience. This project seemed like it would be pretty straight forward given my knowledge level . . . looks like I was wrong. :o
Hardware:
- DHT22
- 22k resistor
- ESP32 Dev Board
Schematic:
(borrowed from Microcontrollerslab.com - thank you!)
#include <WiFi.h>
#include <HTTPClient.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
// Get ESP32Ping.h library here --> https://github.com/marian-craciunescu/ESP32Ping
#include <ESP32Ping.h>
const char* ssid = "*******";
const char* password = "*********";
// Service API Key
String apiKey = "*********************************";
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
float t;
float h;
DHT dht(DHTPIN, DHTTYPE);
// Domain Name with full URL Path for HTTP POST Request
const char* serverName = "http://api.thingspeak.com/update";
// Check the humidity/temp every 1 hour (3600000 milliseconds)
unsigned long timerDelay = 3600000 ;
// Initially set to ensure a forced read as soon as first plugged in
unsigned long lastTime = 10;
//check wifi every 60 seonds
unsigned long check_wifi = 60000;
unsigned long last_wifi = 10000000;
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(ssid, password);
Serial.println("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network, with Local IP address:");
Serial.println(WiFi.localIP());
WiFi.setAutoReconnect(true);
WiFi.persistent(true);
bool success = Ping.ping("www.google.com", 3);
if (!success) {
Serial.println("\nPing failed");
return;
}
Serial.println("\nPing successful.");
Serial.print("Humidity/Temp timer set to ");
Serial.print(timerDelay);
Serial.println("milliseconds using the [timerDelay] variable.");
getReadings();
sendReadings();
// Random seed is a number used to initialize a pseudorandom number generator
randomSeed(analogRead(33));
delay(500);
}
void loop() {
//Check WiFi connection status
if (((millis() - last_wifi) > check_wifi)) {
Serial.println("Q: is the device connected to your wifi?");
//If not connected, try to reconnect
if (WiFi.status() != WL_CONNECTED) {
Serial.println("A: No. Trying to reconnect now . . . ");
WiFi.reconnect();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Reconnected to wifi with Local IP:");
Serial.println(WiFi.localIP());
}
//If wifi is connected, reset last_wifi to millis() and keep going
Serial.println("A: Yes.");
last_wifi = millis();
//Send an HTTP POST request every [timerDelay] seconds
if ((millis() - lastTime) > timerDelay) {
//Check the DHT22
getReadings();
//Send temp and humid to thingspeak
sendReadings();
//restart the timer
lastTime = millis();
delay(500);
//rest the ESP32
ESP.restart();
}
}
}
void getReadings() {
t = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
}
else {
Serial.println(t);
}
h = dht.readHumidity();
// Check if any reads failed and exit early (to try again).
if (isnan(h)) {
Serial.println("Failed to read from DHT sensor!");
}
else {
Serial.println(h);
}
}
void sendReadings() {
//Before sendting data to thingspeak, doublecheck that you're still connected
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
String httpRequestData = "api_key=" + apiKey + "&field1=" + String(t) + "&field2=" + String(h);
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
// Free resources
http.end();
}
}