#include <WiFi.h>
#include <HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* server = "api.thingspeak.com"; // ThingSpeak server address
const String apiKey = "DUHNI50YWHX1Y102"; // ThingSpeak API Key
const int sensorPin = 4; // GPIO pin where the temperature sensor is connected
OneWire oneWire(sensorPin);
DallasTemperature sensors(&oneWire);
void setup() {
Serial.begin(115200);
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop() {
float temperature = readTemperature();
if (!isnan(temperature)) {
Serial.print("Temperature: ");
Serial.println(temperature);
sendToThingSpeak(temperature);
}
delay(60000); // Send data every minute
}
float readTemperature() {
return random(0, 100); // Generate a random temperature value for simulation
}
void sendToThingSpeak(float temperature) {
HTTPClient http;
String url = "http://" + String(server) + "/update?api_key=" + String(apiKey) + "&field1=" + String(temperature);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode == HTTP_CODE_OK) {
Serial.println("Data sent to ThingSpeak successfully");
} else {
Serial.print("Error sending data to ThingSpeak. HTTP error code: ");
Serial.println(httpResponseCode);
}
http.end();
}