#include <WiFi.h>
 
#include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros
#define WIFI_SSID "Wokwi-GUEST"   // replace MySSID with your WiFi network name
#define WIFI_PASSWORD ""  // replace MyPassword with your WiFi password
#define WIFI_CHANNEL 6
#define SECRET_CH_ID 2350557      // replace 0000000 with your channel number
#define SECRET_WRITE_APIKEY "7RCP9BJ1ODDPQPD4"   // replace XYZ with your channel write API Key
#include "DHTesp.h"
 const int DHT_PIN = 17;
 DHTesp dhtSensor;
WiFiClient  client;
 
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
 
int number = 0;
 
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
  Serial.begin(115200);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}
 
void loop() {
 WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
  Serial.print("Connecting to WiFi ");
  Serial.print(WIFI_SSID);
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println(" Connected!");
 
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
 
  // 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.
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");
  delay(2000); // Wait for a new reading from the sensor (DHT22 has ~0.5Hz sample rate)
  int x = ThingSpeak.writeField(myChannelNumber, 1, number, myWriteAPIKey);
  if(x == 200){
    Serial.println("Channel update successful.");
  }
  else{
    Serial.println("Problem updating channel. HTTP error code " + String(x));
  }
 
  // change the value
  number++;
  if(number > 99){
    number = 0;
  }
 
  delay(20000); // Wait 20 seconds to update the channel again
}