#include <WiFi.h>
#include "ThingSpeak.h"
#include <DHT.h>
// Set up the DHT sensor
DHT dht(4, DHT22);
const char* ssid = "Wokwi-GUEST"; // your network SSID (name)
const char* password = ""; // your network password
WiFiClient client;
unsigned long myChannelNumber = 1;
const char * myWriteAPIKey = "UEZTG08HTBBV59VB";
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 5000;
float temperature, humidity;
void setup() {
Serial.begin(115200); //Initialize serial
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nConnected.");
}
// Get a new temperature reading
temperature = dht.readTemperature(false);
Serial.print("Temperatura (ºC): ");
Serial.println(temperature);
//humidity = dht.readHumidity();
// 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.
int x = ThingSpeak.writeField(myChannelNumber, 1, temperature, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
lastTime = millis();
}
}