// This project implements the simulation of the reading a DHT sensor using an ESP32
// The source code is available on my git repo at : https://github.com/Bamamou/DHT11_ESP32.git
// the only difference is the sensor, Here; we use a DHT11 while in Platform io we use a DHT22
#include <DHT.h>
#include <WiFi.h>
#include "ThingSpeak.h"
#include <HTTPClient.h>
#define Led 4
#define DHTPIN 5
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Domain Name with full URL Path for HTTP POST Request
const char* serverName = "http://api.thingspeak.com/update";
// write API Key provided by thingspeak
String writeapiKey = "UJ96XBMRZC9BNN61";
// Set up the DHT sensor
DHT dht(DHTPIN, DHT22);
// Weather station channel details
unsigned long controlChannelNumber = 2244498;
unsigned int lamp1FieldNumber = 3;
// Counting channel details
unsigned long counterChannelNumber = 2244498;
const char * ReadAPIKey = "W3GQW1MWIEOPLHCP";
int keyIndex = 0; // your network key Index number (needed only for WEP)
WiFiClient client;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Hello, ESP32!");
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 IP Address: ");
Serial.println(WiFi.localIP());
pinMode(Led, OUTPUT);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
// ... (existing code)
void loop() {
int statusCode = 0;
if (WiFi.status() == WL_CONNECTED) {
WiFiClient client;
HTTPClient http;
delay(10000); // wait for 10 seconds
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.println("Temperature: " + String(t) + " °C");
Serial.println("Humidity: " + String(h) + " %");
// Your Domain name with URL path or IP address with path
http.begin(client, serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
String httpRequestData = "api_key=" + writeapiKey + "&field1=" + String(t) + "&field2=" + String(h);
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
long Lamp1 = ThingSpeak.readLongField(controlChannelNumber, lamp1FieldNumber, ReadAPIKey);
// Check the status of the read operation to see if it was successful
statusCode = ThingSpeak.getLastReadStatus();
Serial.print("ThingSpeak Status Code: ");
Serial.println(statusCode);
if (statusCode == 200) {
Serial.println("Control command is: " + String(Lamp1));
if (Lamp1 == 0) {
digitalWrite(Led, HIGH);
Serial.println("LED is ON");
} else {
digitalWrite(Led, LOW);
Serial.println("LED is OFF");
}
}
} else {
Serial.println("WiFi Disconnected");
}
}