0% found this document useful (0 votes)
15 views6 pages

MAIN Code

The document provides a complete code for a smart mirror project using an ESP32 microcontroller, which displays the current time, weather, and news on a 16x2 LCD. It includes setup instructions for Wi-Fi connectivity, API integration for weather and news, and detailed pin connections for the LCD. Additionally, it emphasizes the importance of replacing placeholder credentials and ensuring proper wiring before powering on the device.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

MAIN Code

The document provides a complete code for a smart mirror project using an ESP32 microcontroller, which displays the current time, weather, and news on a 16x2 LCD. It includes setup instructions for Wi-Fi connectivity, API integration for weather and news, and detailed pin connections for the LCD. Additionally, it emphasizes the importance of replacing placeholder credentials and ensuring proper wiring before powering on the device.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

MAIN code

//User define the programme


//Code written by "chaitanya"
//Date of generating 27/07/2025
//At location "yelamanchili city"
#include <WiFi.h>
#include <HTTPClient.h> // For making HTTP requests to APIs
#include <ArduinoJson.h> // For parsing JSON responses from APIs
#include <NTPClient.h> // For getting time from NTP server
#include <WiFiUdp.h> // Required by NTPClient
#include <LiquidCrystal.h> // For LCD 16x2 display

// --- Wi-Fi Credentials (IMPORTANT: REPLACE THESE!) ---


#define WIFI_SSID "YOUR_WIFI_SSID"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"

// --- API Keys and City (IMPORTANT: REPLACE THESE!) ---


// Get your API keys from OpenWeatherMap and NewsAPI
#define OPENWEATHERMAP_API_KEY "YOUR_OPENWEATHERMAP_API_KEY"
#define NEWSAPI_API_KEY "YOUR_NEWSAPI_KEY"
#define CITY "Thadepalli_City" // Your desired city for weather

// --- LCD 16x2 Pin Assignments (Connect to ESP32 GPIOs) ---


// RS, Enable, D4, D5, D6, D7
LiquidCrystal lcd(16, 17, 5, 18, 19, 23);

// --- NTP Client Setup ---


WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 19800, 60000); // GMT+5:30
(19800 seconds), update every 60 seconds

// --- Global variables for display content ---


String currentTime = "";
String currentDate = "";
String weatherInfo = "";
String newsHeadline = "";

// --- Function Prototypes ---


void connectToWiFi();
void updateTime();
void updateWeather();
void updateNews();
void displayOnLCD();

void setup() {
Serial.begin(115200);
lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows
lcd.print("Smart Mirror Init");
connectToWiFi(); // Connect to Wi-Fi
timeClient.begin(); // Start NTP client

Serial.println("Setup complete.");
}

void loop() {
timeClient.update(); // Update NTP time

// Update data periodically


static unsigned long lastUpdateTime = 0;
const unsigned long updateInterval = 60000; // Update every 1 minute
(60000 ms)

if (millis() - lastUpdateTime > updateInterval) {


lastUpdateTime = millis();
updateTime(); // Get current time and date
updateWeather(); // Get weather data
updateNews(); // Get news headline
}

displayOnLCD(); // Always update LCD with latest info


delay(1000); // Small delay to prevent display flicker and rapid
updates
}

/**
* @brief Connects the ESP32 to the specified Wi-Fi network.
*/
void connectToWiFi() {
Serial.print("Connecting to WiFi: ");
Serial.println(WIFI_SSID);
lcd.clear(); lcd.setCursor(0, 0); lcd.print("Connecting WiFi");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
lcd.setCursor(0, 1); lcd.print(".");
}
Serial.println("\nWiFi connected. IP: " + WiFi.localIP());
lcd.clear(); lcd.setCursor(0, 0); lcd.print("WiFi Connected!");
lcd.setCursor(0, 1); lcd.print(WiFi.localIP());
delay(2000);
}

/**
* @brief Updates the global time and date strings from NTP client.
*/
void updateTime() {
currentTime = timeClient.getFormattedTime(); // HH:MM:SS
// Get date: YYYY-MM-DD
unsigned long epochTime = timeClient.getEpochTime();
struct tm *ptm = gmtime ((time_t *)&epochTime);
char dateBuffer[11];
sprintf(dateBuffer, "%04d-%02d-%02d", ptm->tm_year + 1900, ptm-
>tm_mon + 1, ptm->tm_mday);
currentDate = String(dateBuffer);

Serial.println("Time: " + currentTime + ", Date: " + currentDate);


}

/**
* @brief Fetches weather data from OpenWeatherMap API and updates
global weather string.
*/
void updateWeather() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "http://api.openweathermap.org/data/2.5/weather?q=" +
String(CITY) + "&appid=" + String(OPENWEATHERMAP_API_KEY) +
"&units=metric";
http.begin(url);
int httpCode = http.GET();

if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
DynamicJsonDocument doc(512); // Adjust size as needed
deserializeJson(doc, payload);

float temp = doc["main"]["temp"];


String description = doc["weather"][0]
["description"].as<String>();
weatherInfo = String(CITY) + ": " + String(temp, 1) + "C, " +
description;
Serial.println("Weather: " + weatherInfo);
} else {
weatherInfo = "Weather Error!";
Serial.println("Weather Error: " + http.errorToString(httpCode));
}
http.end();
} else {
weatherInfo = "No WiFi for Weather";
}
}
/**
* @brief Fetches news headline from NewsAPI and updates global news
string.
*/
void updateNews() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "https://newsapi.org/v2/top-headlines?
country=in&apiKey=" + String(NEWSAPI_API_KEY);
http.begin(url);
int httpCode = http.GET();

if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
DynamicJsonDocument doc(1024); // Adjust size as needed
deserializeJson(doc, payload);

if (doc["articles"].size() > 0) {
String title = doc["articles"][0]["title"].as<String>();
// Truncate news headline to fit LCD 16x2
if (title.length() > 16) {
newsHeadline = title.substring(0, 15) + "...";
} else {
newsHeadline = title;
}
} else {
newsHeadline = "No News Available";
}
Serial.println("News: " + newsHeadline);
} else {
newsHeadline = "News Error!";
Serial.println("News Error: " + http.errorToString(httpCode));
}
http.end();
} else {
newsHeadline = "No WiFi for News";
}
}

/**
* @brief Displays the current time, weather, and news on the LCD 16x2.
* It cycles through different information on the two lines.
*/
void displayOnLCD() {
static int displayMode = 0; // 0: Time/Date, 1: Weather, 2: News
static unsigned long lastDisplayChange = 0;
const unsigned long displayChangeInterval = 5000; // Change display
every 5 seconds
if (millis() - lastDisplayChange > displayChangeInterval) {
lastDisplayChange = millis();
displayMode = (displayMode + 1) % 3; // Cycle through modes
}

lcd.clear();
switch (displayMode) {
case 0: // Time and Date
lcd.setCursor(0, 0); lcd.print(currentTime);
lcd.setCursor(0, 1); lcd.print(currentDate);
break;
case 1: // Weather
lcd.setCursor(0, 0); lcd.print("Weather:");
lcd.setCursor(0, 1); lcd.print(weatherInfo.substring(0, 16)); //
Ensure it fits
break;
case 2: // News
lcd.setCursor(0, 0); lcd.print("News:");
lcd.setCursor(0, 1); lcd.print(newsHeadline); // Already
truncated
break;
}
}

Components:

 ESP32 Development Board


 LCD 16x2 Display
 Breadboard (recommended for easy wiring)
 Jumper Wires
 10kΩ Potentiometer (for LCD contrast, highly recommended)
 220Ω Resistor (for LCD backlight, recommended)

Connection Details:

1. ESP32 Board: * This is your main microcontroller. Power it via its USB port or a suitable
3.3V/5V power supply.

2. LCD 16x2 Display (Standard Parallel Interface): * VSS (Ground): Connect to ESP32
GND. * VDD (Power): Connect to ESP32 5V (or 3.3V, depending on your specific LCD
module's operating voltage. Check your LCD datasheet). * Vo (Contrast): Connect to the
middle pin of a 10kΩ potentiometer. * One outer pin of the potentiometer goes to 5V (or
3.3V). * The other outer pin of the potentiometer goes to GND. * Adjusting this
potentiometer will change the clarity of the characters on the LCD. * RS (Register Select):
Connect to ESP32 GPIO 16. * RW (Read/Write): Connect to GND (we are only writing
data to the LCD). * Enable: Connect to ESP32 GPIO 17. * D0-D3: Leave these pins
unconnected (the code uses 4-bit mode for data transfer, which only requires D4-D7). * D4
(Data 4): Connect to ESP32 GPIO 5. * D5 (Data 5): Connect to ESP32 GPIO 18. * D6
(Data 6): Connect to ESP32 GPIO 19. * D7 (Data 7): Connect to ESP32 GPIO 23. * A
(Backlight Anode): Connect to 5V (or 3.3V) through a 220Ω resistor. This resistor limits
the current to the backlight LED. * K (Backlight Cathode): Connect to GND.

3. Wi-Fi Module: * The Wi-Fi module is built directly into the ESP32 chip. You do not
need to wire a separate Wi-Fi module. The ESP32 handles all Wi-Fi communication
internally.

Summary of Pin Connections from ESP32 to LCD:

 GPIO 16 -> LCD RS


 GPIO 17 -> LCD Enable
 GPIO 5 -> LCD D4
 GPIO 18 -> LCD D5
 GPIO 19 -> LCD D6
 GPIO 23 -> LCD D7
 GND -> LCD VSS, LCD RW, LCD K (and one side of potentiometer)
 5V (or 3.3V) -> LCD VDD, LCD A (via 220Ω resistor), and other side of
potentiometer

Before powering on:

 Double-check all your connections to ensure they match this description. Incorrect
wiring can damage components.
 Make sure you have replaced the placeholder Wi-Fi credentials and API keys in
the Arduino code.
 Ensure all necessary libraries (HTTPClient, ArduinoJson, NTPClient,
LiquidCrystal) are correctly installed in your Arduino IDE.

You might also like