#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <HTTPClient.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
const char* ssid = "Upayan";
const char* weatherApiUrl = "https://wttr.in/Vellore?format=%25C+%25t";
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void logToDisplayAndSerial(String message) {
Serial.println(message);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println(message);
display.display();
}
void setup() {
Serial.begin(115200);
if (!display.begin(SSD1306_PAGEADDR, 0x3C)) {
logToDisplayAndSerial("OLED Init Failed");
while (1);
}
display.clearDisplay();
logToDisplayAndSerial("OLED Initialized");
logToDisplayAndSerial("Connecting to WiFi...");
WiFi.begin(ssid);
int retries = 0;
while (WiFi.status() != WL_CONNECTED && retries < 20) {
delay(1000);
retries++;
logToDisplayAndSerial(".");
}
if (WiFi.status() == WL_CONNECTED) {
logToDisplayAndSerial("WiFi Connected!");
logToDisplayAndSerial("IP: " + WiFi.localIP().toString());
} else {
logToDisplayAndSerial("Failed to connect");
}
logToDisplayAndSerial("Waiting 15 seconds...");
delay(15000);
}
void loop() {
logToDisplayAndSerial("Fetching weather...");
fetchWeatherData();
delay(60000);
}
void fetchWeatherData() {
HTTPClient http;
http.begin(weatherApiUrl);
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
String payload = http.getString();
String weatherMessage = "Weather: " + payload;
logToDisplayAndSerial(weatherMessage);
} else {
String errorMessage = "HTTP Error: " + String(httpResponseCode);
errorMessage += "\n" + http.errorToString(httpResponseCode);
String headers = http.getString();
logToDisplayAndSerial(errorMessage);
logToDisplayAndSerial("Response Headers: " + headers);
if (httpResponseCode == 301) {
String location = http.header("Location");
logToDisplayAndSerial("Redirected to: " + location);
}
}
http.end();
}