/*
* Update the DATABASE_URL below with your Firebase project URL
* Run the simulation!
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <Adafruit_Sensor.h> // Required for DHT library
// -- Sensor Configuration --
#define DHTPIN 15 // The pin the DHT22 is connected to
#define DHTTYPE DHT22 // We are using the DHT22 sensor
DHT dht(DHTPIN, DHTTYPE);
// -- IMPORTANT --
// 1. Get this from your Firebase "Realtime Database"
// 2. It should look like: https://your-project-name-default-rtdb.firebaseio.com/
// 3. Make sure to add "sensor_readings.json" to the end!
const char* DATABASE_URL = "https://prac5-ee5c2-default-rtdb.firebaseio.com/sensor_readings.json";
// Wokwi simulates this WiFi network automatically
const char* ssid = "Wokwi-GUEST";
const char* password = "";
void setup() {
Serial.begin(115200);
dht.begin(); // Initialize the DHT sensor
// Connect to Wi-Fi
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" Connected!");
}
void loop() {
// Read sensor data
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if reads failed
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
delay(2000);
return;
}
// Create a JSON payload
String payload = "{\"timestamp\": " + String(millis()) +
", \"temp\": " + String(temperature) +
", \"humidity\": " + String(humidity) + "}";
// Send data to Firebase
Serial.println("Sending data to Firebase:");
Serial.println(DATABASE_URL);
Serial.println(payload);
HTTPClient http;
http.begin(DATABASE_URL);
http.addHeader("Content-Type", "application/json");
// Firebase Realtime Database uses POST to create a new record
int httpResponseCode = http.POST(payload);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
// Get the response payload (which includes the unique key)
String responsePayload = http.getString();
Serial.println("Response payload:");
Serial.println(responsePayload);
http.end();
// Wait 10 seconds before sending the next reading
delay(10000);
}