// 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 = "44Z5CC2OR86T0DSQ";
// Set up the DHT sensor
DHT dht(DHTPIN, DHT22);
// Weather station channel details
unsigned long controlChannelNumber = 2244542;
unsigned int lamp1FieldNumber = 3;
// Counting channel details
unsigned long counterChannelNumber = 2242952;
const char * ReadAPIKey = "8BLD6SJBHCTPZRBB";
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
}
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));
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();
//delay(1000);
long Lamp1 = ThingSpeak.readLongField(controlChannelNumber, lamp1FieldNumber, ReadAPIKey);
// Check the status of the read operation to see if it was successful
statusCode = ThingSpeak.getLastReadStatus();
if(statusCode == 200){
Serial.println("control command is " + String(Lamp1) );
if (Lamp1==1)
{
digitalWrite(Led,HIGH);
}
else{
digitalWrite(Led,LOW);
}
}
}
else {
Serial.println("WiFi Disconnected");
}
}