#include <WiFi.h>
#include <ThingSpeak.h> // always include thingspeak header file after other header files and custom macros
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define SECRET_CH_ID 2524249 // replace 0000000 with your channel number
#define SECRET_WRITE_APIKEY "YJAM654SOI4LC19K" // replace XYZ with your channel write API Key
int keyIndex = 0; // your network key Index number (needed only for WEP)
WiFiClient client;
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
float pinval;
float temp=0.00;
#include "DHTesp.h"
const int DHT_PIN = 15;
DHTesp dhtSensor;
void setup()
{
Serial.begin(115200); //Initialize serial
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo native USB port only
}
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
wifiConnect();
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.macAddress());
}
void wifiConnect() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void loop()
{
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
ThingSpeak.setField(1, data.temperature);
ThingSpeak.setField(2, data.humidity);
int x = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(x == 200)
{
Serial.println("Channel update successful.");
}
else
{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
delay(16000); // Wait 15 seconds to update the channel again
}