#include <WiFi.
h>
#include <HTTPClient.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ArduinoJson.h>
// WiFi credentials
const char* ssid = //yourssid;
const char* password = //yourpsd;
// OpenWeatherMap API
const char* apiKey = //yourapikey;
const char* location = //your location;
const char* apiUrl = //your url;
// OLED display setup
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Button setup
const int buttonPin = 0; // GPIO for the button
int buttonState = 0;
int lastButtonState = 0;
int displayMode = 0; // 0: Temperature, 1: Humidity, 2: Wind Speed
// Weather data variables
float temperature = 0.0;
int humidity = 0;
float windSpeed = 0.0;
void setup() {
// Initialize serial
[Link](115200);
// Initialize button pin
pinMode(buttonPin, INPUT_PULLUP);
// Initialize OLED display
if () {
[Link]("SSD1306 allocation failed");
while (1);
}
[Link]();
[Link]();
// Connect to WiFi
connectToWiFi();
// Fetch initial weather data
fetchWeatherData();
}
void loop() {
// Read button state
buttonState = digitalRead(buttonPin);
// Check if the button was pressed
if (buttonState == LOW && lastButtonState == HIGH) {
displayMode = (displayMode + 1) % 3; // Cycle through modes
displayWeatherData();
}
lastButtonState = buttonState;
// Fetch weather data every 10 minutes (600000 ms)
static unsigned long lastUpdate = 0;
if (millis() - lastUpdate > 600000) {
fetchWeatherData();
lastUpdate = millis();
displayWeatherData();
}
}
void connectToWiFi() {
[Link]("Connecting to WiFi");
[Link](ssid, password);
while ([Link]() != WL_CONNECTED) {
delay(1000);
[Link](".");
}
[Link](" Connected!");
}
void fetchWeatherData() {
if ([Link]() == WL_CONNECTED) {
HTTPClient http;
[Link](apiUrl);
int httpCode = [Link]();
if (httpCode > 0) {
String payload = [Link]();
[Link](payload); // Debugging: Print raw JSON response
StaticJsonDocument<1024> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
temperature = doc["main"]["temp"].as<float>();
humidity = doc["main"]["humidity"].as<int>();
windSpeed = doc["wind"]["speed"].as<float>();
} else {
[Link]("JSON parsing failed: ");
[Link](error.c_str());
}
} else {
[Link]("HTTP GET failed: ");
[Link]([Link](httpCode));
}
[Link]();
} else {
[Link]("WiFi not connected");
}
}
void displayWeatherData() {
[Link]();
switch (displayMode) {
case 0:
[Link](1);
[Link](WHITE);
[Link](0, 0);
[Link]("Weather in Karachi");
[Link](2);
[Link](0, 20);
[Link]("Temp: ");
[Link](temperature);
[Link](" C");
break;
case 1:
[Link](1);
[Link](WHITE);
[Link](0, 0);
[Link]("Weather in Karachi");
[Link](2);
[Link](0, 20);
[Link]("Hum: ");
[Link](humidity);
[Link](" %");
break;
case 2:
[Link](1);
[Link](WHITE);
[Link](0, 0);
[Link]("Weather in Karachi");
[Link](2);
[Link](0, 20);
[Link]("Wind: ");
[Link](windSpeed);
[Link](" m/s");
break;
}
[Link]();
}