#include <WiFi.h>
#include <HTTPClient.h>
#include <DHTesp.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
const char *ssid = "Wokwi-GUEST";
const char *password = "";
const char *serverUrl = "https://unhallowed-skull-7vw5v97w5wjhx4gq-3133.app.github.dev/api/readings";
DHTesp dht;
const char *sensorId = "ISM-RT-1";
const char *sensorName = "InvenSafeMonitor-1";
#define SCREEN_WIDTH 128 // OLED display Width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
Serial.begin(115200);
// Initialize DHT sensor
dht.setup(4, DHTesp::DHT22);
// Initialize OLED display
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("failed to start SSD1306 OLED"));
while (1); // Loop forever if the display doesn't start
}
oled.clearDisplay(); // Clear display
oled.setTextSize(1); // Set text size
oled.setTextColor(WHITE); // Set text color
oled.setCursor(0, 0); // Set cursor to top left
oled.println("InvenSafe Monitor"); // Initial display message
oled.display(); // Display initial message
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("\nConnected to WiFi");
Serial.println("Server URL: " + String(serverUrl));
}
void sendDataToServer(float temperature, float humidity) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverUrl);
http.addHeader("Content-Type", "application/json");
// Prepare the JSON payload
String jsonPayload = "{\"sensorId\": \"" + String(sensorId) + "\", "
"\"sensorName\": \"" + String(sensorName) + "\", "
"\"temperature\": " + String(temperature) + ", "
"\"humidity\": " + String(humidity) + "}";
// Send the POST request
int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Response Code: " + String(httpResponseCode));
Serial.println("Response: " + response);
} else {
Serial.println("Error in sending POST request");
Serial.println("HTTP Response code: " + String(httpResponseCode));
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}
void loop() {
// Get temperature and humidity readings
float temperature = dht.getTemperature();
float humidity = dht.getHumidity();
// Send data to server
sendDataToServer(temperature, humidity);
// Display temperature and humidity on OLED
oled.clearDisplay(); // Clear the display
oled.setCursor(0, 10); // Set cursor position
oled.print("Temp: ");
oled.print(temperature, 2); // Display temperature
oled.println(" C");
oled.print("Humidity: ");
oled.print(humidity, 1); // Display humidity
oled.println(" %");
oled.display(); // Update the OLED display
delay(10000); // Wait for 10 seconds before the next reading
}