Selaa lähdekoodia

Initial Commit

svalavuo 1 kuukausi sitten
vanhempi
sitoutus
6d5c44ca64
6 muutettua tiedostoa jossa 905 lisäystä ja 1 poistoa
  1. 163 1
      README.md
  2. 167 0
      info.txt
  3. 17 0
      platformio.ini
  4. 299 0
      schematics.md
  5. BIN
      weather_station_diagram.jpg
  6. 259 0
      weatherstation.ino

+ 163 - 1
README.md

@@ -1,2 +1,164 @@
-# esp32weatherstation
+# ESP32 Weather Station
+
+A comprehensive weather monitoring system built on ESP32 with multiple sensors and MQTT connectivity for IoT integration.
+
+## Features
+- Temperature and humidity monitoring (DHT11)
+- Atmospheric pressure measurement (BMP180)
+- Rain detection sensor (analog)
+- Light detection (LDR) with LED indicator
+- Real-time 16x2 I2C LCD display
+- WiFi connectivity with automatic reconnection
+- MQTT data publishing with JSON format
+- Automatic MQTT reconnection with random client ID
+- Non-blocking timer-based sensor readings
+- Error handling and status indication
+- Serial debugging output (115200 baud)
+
+## Hardware Requirements
+- ESP32 development board
+- DHT11 temperature/humidity sensor
+- BMP180 pressure sensor
+- Rain sensor module (analog output)
+- LDR (Light Dependent Resistor)
+- 16x2 I2C LCD display (0x27 address)
+- LED (for light status indication)
+- Breadboard and jumper wires
+
+## Software Dependencies
+- DHT sensor library
+- LiquidCrystal I2C
+- SFE BMP180 Breakout Library
+- PubSubClient
+
+## Configuration
+Update the following constants in `weatherstation.ino`:
+- `ssid`: Your WiFi network name
+- `password`: Your WiFi password
+- `mqtt_server`: Your MQTT broker address
+- `mqtt_port`: MQTT broker port (default 1883)
+- `mqtt_topic`: MQTT topic for data publishing (default: weather/station)
+
+## Pin Configuration
+- DHT11 Sensor: Pin 4
+- LDR Sensor: Pin 35 (input only)
+- Rain Sensor: Pin 34 (analog)
+- Status LED: Pin 2
+- I2C LCD (SDA): Pin 21
+- I2C LCD (SCL): Pin 22
+
+## MQTT Data Format
+The station publishes JSON data to the configured topic:
+```json
+{
+  "temperature": 23.45,
+  "humidity": 67.89,
+  "pressure": 1013.25,
+  "rainLevel": 15,
+  "lightDetected": true
+}
+```
+
+## LCD Display Format
+```
+Line 1: T:23.4C H:67%
+Line 2: R:15% P:1013
+```
+
+## Serial Output Format
+```
+Temp: 23.45°C, Humidity: 67.89%, Rain: 15%, Pressure: 1013.25 hPa, Light: YES
+```
+
+## Installation
+1. Install PlatformIO
+2. Set up MQTT broker (Mosquitto, HiveMQ, AWS IoT, etc.)
+3. Connect hardware according to pin configuration
+4. Update WiFi and MQTT credentials in sketch
+5. Run `pio run` to build
+6. Run `pio run --target upload` to flash
+7. Run `pio device monitor` to view serial output
+8. Subscribe to MQTT topic to receive weather data
+
+## MQTT Broker Setup
+1. Install Mosquitto broker or use cloud service
+2. Configure broker for client connections on port 1883
+3. Create topic structure: weather/station (or custom)
+4. Test broker connectivity with MQTT client tools
+5. Configure firewall if using local broker
+6. Verify broker allows anonymous connections or add authentication
+
+## Operation Schedule
+- **Sensor readings**: Every 2 seconds (2000ms)
+- **MQTT data publishing**: Every 30 seconds (30000ms)
+- **LCD display updates**: Every 2 seconds
+- **LED status updates**: With each sensor reading
+- **WiFi connection attempts**: 20 attempts (10 seconds timeout)
+- **MQTT reconnection**: Every 5 seconds if disconnected
+
+## Troubleshooting
+- **Sensor errors**: Check wiring connections and power supply
+- **WiFi connection**: Verify SSID and password credentials
+- **MQTT connection**: Ensure broker is accessible and running
+- **LCD display**: Check I2C address (default 0x27) and connections
+- **DHT11 readings**: Look for NaN values in serial output
+- **BMP180 sensor**: Verify initialization and I2C connection
+- **Rain sensor**: Check analog pin assignment (Pin 34)
+- **LDR/LED**: Verify digital pin assignment (Pin 35 for LDR, Pin 2 for LED)
+
+## Code Architecture
+- **Modular design**: Separate functions for each sensor
+- **Non-blocking operations**: Timer-based without delays
+- **Structured data**: WeatherData struct for sensor values
+- **Error handling**: Validation and status reporting
+- **Automatic recovery**: WiFi and MQTT reconnection logic
+
+## Technical Specifications
+- **Microcontroller**: ESP32 (Dual Core, 240MHz)
+- **Memory**: 520KB SRAM, 4MB Flash
+- **Wireless**: WiFi 802.11 b/g/n
+- **Sensors**: DHT11 (±2°C, ±5%RH), BMP180 (±1hPa), Rain sensor, LDR
+- **Display**: 16x2 Character LCD with I2C interface
+- **Power**: 5V via USB or external supply
+- **Communication**: I2C, WiFi, MQTT
+
+## Schematics and Wiring
+
+### Quick Reference Diagram
+```
+ESP32 Weather Station Wiring
+┌─────────────────────────────────────┐
+│ ESP32                              │
+│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐   │
+│ │GPIO2│ │GPIO4│ │GPIO21│ │GPIO22│   │
+│ │ LED │ │DHT11│ │ SDA │ │ SCL │   │
+│ └─────┘ └─────┘ └─────┘ └─────┘   │
+│ ┌─────┐ ┌─────┐                     │
+│ │GPIO34│ │GPIO35│                     │
+│ │Rain │ │ LDR │                     │
+│ └─────┘ └─────┘                     │
+└─────────────────────────────────────┘
+```
+
+### Complete Wiring Guide
+- **DHT11 Sensor**: Pin 4 (Data), 3.3V, GND
+- **BMP180 Sensor**: SDA→GPIO21, SCL→GPIO22, 3.3V, GND
+- **Rain Sensor**: AO→GPIO34, 3.3V, GND
+- **LDR**: GPIO35 with 10kΩ pull-down, 3.3V
+- **LED**: GPIO2 with 220Ω resistor, GND
+- **LCD Display**: SDA→GPIO21, SCL→GPIO22, 5V, GND
+
+### Detailed Schematics
+For complete circuit diagrams, component layouts, and assembly instructions, see [schematics.md](schematics.md).
+
+### Bill of Materials
+- ESP32 Development Board
+- DHT11 Temperature & Humidity Sensor
+- BMP180 Pressure Sensor
+- Rain Sensor Module (analog)
+- LDR (Light Dependent Resistor)
+- 16x2 LCD Display with I2C Module
+- LED (5mm) + 220Ω resistor
+- 10kΩ resistor (for LDR)
+- Breadboard and jumper wires
 

+ 167 - 0
info.txt

@@ -0,0 +1,167 @@
+ESP32 Weather Station Project Information
+==========================================
+
+Project Overview:
+-----------------
+This is a comprehensive weather monitoring system built on ESP32 microcontroller
+with multiple environmental sensors and MQTT connectivity for IoT integration.
+
+Hardware Components:
+-------------------
+- ESP32 Development Board (main controller)
+- DHT11 Temperature & Humidity Sensor
+- BMP180 Atmospheric Pressure Sensor  
+- Rain Sensor Module (analog)
+- LDR (Light Dependent Resistor)
+- 16x2 I2C LCD Display
+- LED (Status Indicator for light detection)
+- Breadboard and Jumper Wires
+
+Pin Configuration:
+------------------
+- DHT11 Sensor: Pin 4
+- LDR Sensor: Pin 35 (input only pin)
+- Rain Sensor: Pin 34 (analog pin)
+- Status LED: Pin 2
+- I2C LCD (SDA): Pin 21
+- I2C LCD (SCL): Pin 22
+
+Software Features:
+-----------------
+- Real-time sensor data collection with timed intervals
+- Temperature, humidity, pressure, rain, and light monitoring
+- Live LCD display of weather data
+- WiFi connectivity for network access
+- MQTT client for data publishing
+- Automatic MQTT reconnection with random client ID
+- JSON data format for MQTT messages
+- Error handling and status indication
+- Serial output for debugging (115200 baud)
+- LED status indicator synchronized with LDR readings
+
+Code Structure:
+--------------
+- Modular sensor reading functions
+- Structured WeatherData for data management
+- Non-blocking timer-based operations
+- Automatic WiFi connection with timeout
+- MQTT client with reconnection logic
+- LCD display formatting and error messages
+
+MQTT Configuration:
+------------------
+- Broker: Configurable server address
+- Port: 1883 (default)
+- Topic: weather/station (configurable)
+- Data Format: JSON
+- Client ID: Auto-generated (ESP32WeatherStation-XXXX)
+- Authentication: None (configurable)
+
+Sensor Reading Schedule:
+------------------------
+- All sensors read: Every 2 seconds (2000ms)
+- MQTT data published: Every 30 seconds (30000ms)
+- LCD display updated: Every 2 seconds
+- LED status: Updated with each sensor read
+- Serial output: With each sensor reading
+
+Technical Specifications:
+------------------------
+- Microcontroller: ESP32 (Dual Core, 240MHz)
+- Memory: 520KB SRAM, 4MB Flash
+- Wireless: WiFi 802.11 b/g/n
+- Sensors: DHT11 (±2°C, ±5%RH), BMP180 (±1hPa), Rain sensor, LDR
+- Display: 16x2 Character LCD with I2C interface (0x27)
+- Power: 5V via USB or external supply
+- Communication: I2C, WiFi, MQTT
+
+Development Environment:
+----------------------
+- PlatformIO with ESP32 framework
+- Arduino IDE compatible
+- Libraries: DHT, LiquidCrystal_I2C, SFE_BMP180, PubSubClient
+
+MQTT Data Format:
+-----------------
+```json
+{
+  "temperature": 23.45,
+  "humidity": 67.89,
+  "pressure": 1013.25,
+  "rainLevel": 15,
+  "lightDetected": true
+}
+```
+
+LCD Display Format:
+------------------
+Line 1: "T:23.4C H:67%"
+Line 2: "R:15% P:1013"
+
+Serial Output Format:
+-------------------
+"Temp: 23.45°C, Humidity: 67.89%, Rain: 15%, Pressure: 1013.25 hPa, Light: YES"
+
+Installation Instructions:
+------------------------
+1. Connect hardware according to pin configuration
+2. Set up MQTT broker (Mosquitto, HiveMQ, AWS IoT, etc.)
+3. Update WiFi credentials (ssid, password) in sketch
+4. Update MQTT broker settings (mqtt_server, mqtt_port, mqtt_topic)
+5. Upload firmware using PlatformIO or Arduino IDE
+6. Monitor serial output at 115200 baud rate
+7. Subscribe to MQTT topic to receive weather data
+
+MQTT Broker Setup:
+-----------------
+1. Install Mosquitto broker or use cloud service
+2. Configure broker for client connections on port 1883
+3. Create topic structure: weather/station (or custom)
+4. Test broker connectivity with MQTT client tools
+5. Configure firewall if using local broker
+6. Verify broker allows anonymous connections or add auth
+
+Troubleshooting:
+---------------
+- Check wiring connections if sensors return errors
+- Verify WiFi credentials if connection fails
+- Ensure MQTT broker is accessible and running
+- Check MQTT broker address and port
+- Verify topic permissions on broker
+- Check I2C address (default 0x27) for LCD
+- Use external power supply if sensors are unstable
+- Check analog pin assignments for rain sensor (Pin 34)
+- Monitor serial output for detailed error messages
+- Verify BMP180 sensor initialization
+- Check DHT11 sensor readings for NaN values
+
+Code Constants and Variables:
+----------------------------
+- sensorInterval: 2000ms (sensor reading frequency)
+- mqttInterval: 30000ms (MQTT publish frequency)
+- WiFi connection attempts: 20 (10 seconds total)
+- MQTT reconnection delay: 5 seconds
+- Rain sensor mapping: 0-4095 to 0-100% (inverted)
+- LDR reading: Digital (HIGH/LOW)
+- Pressure oversampling: 3 (BMP180)
+
+Project Status:
+--------------
+Version: 3.0.0 (MQTT Edition)
+Last Updated: May 2026
+Author: Weather Station Team
+License: Open Source
+
+Additional Notes:
+---------------
+- MQTT provides flexible IoT integration options
+- JSON format allows easy data processing and parsing
+- Rain sensor values are inverted and mapped to percentage (0-100%)
+- LDR provides digital light detection (HIGH=light detected, LOW=no light)
+- LED indicates light detection status (ON when light detected)
+- LCD shows formatted sensor data locally with error messages
+- System requires WiFi connection for MQTT functionality
+- Automatic reconnection ensures reliable data transmission
+- All sensor data available via MQTT subscription
+- Non-blocking code design prevents system hangs
+- Modular structure allows easy sensor additions

+ 17 - 0
platformio.ini

@@ -0,0 +1,17 @@
+[env:esp32dev]
+platform = espressif32
+board = esp32dev
+framework = arduino
+monitor_speed = 115200
+
+lib_deps = 
+    adafruit/DHT sensor library@^1.4.4
+    adafruit/LiquidCrystal I2C@^1.1.4
+    sparkfun/BMP180 Breakout Library@^1.0.1
+    knolleary/PubSubClient@^2.8
+
+build_flags = 
+    -DCORE_DEBUG_LEVEL=3
+
+upload_speed = 921600
+monitor_filters = esp32_exception_decoder

+ 299 - 0
schematics.md

@@ -0,0 +1,299 @@
+# ESP32 Weather Station Schematics
+
+## Wiring Diagram
+
+### ESP32 Pin Connections
+
+```
+ESP32 Development Board
+┌─────────────────────────────────────┐
+│                                     │
+│  3V3  ──┐                          │
+│  GND  ──┼───┐                      │
+│  GPIO2 ──┘   │                      │
+│             │                      │
+│  GPIO4 ──────┼─── DHT11 Sensor      │
+│             │   ┌─────┐            │
+│  GPIO21 ─────┼───│ SDA │            │
+│             │   │     │            │
+│  GPIO22 ─────┼───│ SCL │            │
+│             │   └─────┘            │
+│  GPIO34 ─────┼─── Rain Sensor       │
+│             │                      │
+│  GPIO35 ─────┼─── LDR               │
+│                                     │
+│  VIN  ──┐                          │
+│  GND  ──┼───┐                      │
+│         │   │                      │
+└─────────┘   │                      │
+              │                      │
+              ▼                      ▼
+         Power Supply              LCD Display
+```
+
+### Detailed Component Connections
+
+#### DHT11 Temperature & Humidity Sensor
+```
+DHT11 Sensor
+┌───────┐
+│  1    │─── +3.3V
+│  2    │─── GPIO4 (Data)
+│  3    │─── (Not Connected)
+│  4    │─── GND
+└───────┘
+
+Pinout (front view):
+┌─────────┐
+│  •  •  • │  ← Pins 1-4
+└─────────┘
+```
+
+#### BMP180 Pressure Sensor (I2C)
+```
+BMP180 Sensor
+┌─────────────┐
+│ VIN   ─────┼─── +3.3V
+│ GND   ─────┼─── GND
+│ SDA   ─────┼─── GPIO21
+│ SCL   ─────┼─── GPIO22
+└─────────────┘
+```
+
+#### Rain Sensor Module
+```
+Rain Sensor Module
+┌─────────────┐
+│ VCC  ───────┼─── +3.3V
+│ GND  ───────┼─── GND
+│ AO   ───────┼─── GPIO34 (Analog)
+│ DO   ───────┼─── (Not Connected)
+└─────────────┘
+```
+
+#### LDR (Light Dependent Resistor)
+```
+LDR Circuit
+┌─────────┐    ┌─────────┐
+│ 3.3V    │    │         │
+│         │    │   LDR   │
+│   ┌─────┼────┼─────┐   │
+│   │     │    │     │   │
+│   ▼     │    │     ▼   │
+│ 10kΩ    │    │         │
+│ Resistor│    │         │
+│   │     │    │         │
+│   └─────┼────┼─────┐   │
+│         │    │     │   │
+│ GND     │    │     │   │
+└─────────┘    │ GPIO35│   │
+               │       │   │
+               └───────┼───┘
+                       │
+                      GND
+```
+
+#### 16x2 I2C LCD Display
+```
+LCD with I2C Module
+┌─────────────────────┐
+│ 16x2 LCD Display    │
+│                     │
+│ ┌─────────────────┐ │
+│ │   I2C Module   │ │
+│ │                 │ │
+│ │ GND ───────────┼─┼─── GND
+│ │ VCC ───────────┼─┼─── +5V
+│ │ SDA ───────────┼─┼─── GPIO21
+│ │ SCL ───────────┼─┼─── GPIO22
+│ └─────────────────┘ │
+└─────────────────────┘
+```
+
+#### LED Status Indicator
+```
+LED Circuit
+┌─────┐    ┌─────────┐
+│3.3V │    │         │
+│     │    │   LED   │
+│ ┌───┼────┼─────┐   │
+│ │   │    │     │   │
+│ ▼   │    │     ▼   │
+│220Ω │    │         │
+│Res  │    │         │
+│ │   │    │         │
+│ └───┼────┼─────┐   │
+│     │    │     │   │
+│GPIO2│    │     │   │
+└─────┼────┼─────┼───┘
+      │    │     │
+      └────┼─────┘
+           │
+          GND
+```
+
+## Complete Circuit Schematic
+
+```
+                    +3.3V
+                      │
+                      ├───────────────────┐
+                      │                   │
+                      │                   ▼
+                      │               ┌─────────┐
+                      │               │  DHT11  │
+                      │               │  Sensor │
+                      │               └─────┬───┘
+                      │                     │
+                      │                     ▼
+                      │                   GPIO4
+                      │                     │
+                      │                     │
+                      │                   ┌─────┐
+                      │                   │ESP32│
+                      │                   │Board│
+                      │                   └─────┘
+                      │                     │
+                      │                     │
+                      │                     │
+                      │                     ▼
+                      │                   GPIO21
+                      │                     │
+                      │                     ▼
+                      │               ┌─────────┐
+                      │               │ BMP180  │
+                      │               │ Sensor  │
+                      │               └─────┬───┘
+                      │                     │
+                      │                     ▼
+                      │                   GPIO22
+                      │                     │
+                      │                     │
+                      │                     │
+                      │                     ▼
+                      │                   GPIO34
+                      │                     │
+                      │                     ▼
+                      │               ┌─────────┐
+                      │               │  Rain   │
+                      │               │ Sensor  │
+                      │               └─────┬───┘
+                      │                     │
+                      │                     │
+                      │                     │
+                      │                     │
+                      │                     ▼
+                      │                   GPIO35
+                      │                     │
+                      │                     ▼
+                      │               ┌─────────┐
+                      │               │  LDR    │
+                      │               │ Circuit │
+                      │               └─────┬───┘
+                      │                     │
+                      │                     │
+                      │                     │
+                      │                     ▼
+                      │                   GPIO2
+                      │                     │
+                      │                     ▼
+                      │               ┌─────────┐
+                      │               │  LED    │
+                      │               │ Circuit │
+                      │               └─────┬───┘
+                      │                     │
+                      │                     │
+                      │                     ▼
+                      │                   ┌─────────┐
+                      │                   │  LCD    │
+                      │                   │Display  │
+                      │                   │ (I2C)   │
+                      │                   └─────┬───┘
+                      │                     │
+                      │                     │
+                      │                     ▼
+                      │                   ┌─────────┐
+                      └───────────────────┤   GND   │
+                                        └─────────┘
+```
+
+## Power Distribution
+
+```
+Power Supply (USB 5V or External 5V)
+┌─────────────────────────────────────┐
+│                                     │
+│  +5V ───────────────────────────────┼─── LCD VCC
+│                                     │
+│  +3.3V ──────────────────────────────┼─── DHT11 VCC
+│  (from ESP32 regulator)             │
+│                                     ├─── BMP180 VCC
+│                                     ├─── Rain Sensor VCC
+│                                     └─── LDR Circuit VCC
+│                                     │
+│  GND ────────────────────────────────┼─── All GND connections
+│                                     │
+└─────────────────────────────────────┘
+```
+
+## Bill of Materials
+
+### Components Required
+1. **ESP32 Development Board** - 1x
+2. **DHT11 Temperature & Humidity Sensor** - 1x
+3. **BMP180 Pressure Sensor** - 1x
+4. **Rain Sensor Module** - 1x
+5. **LDR (Light Dependent Resistor)** - 1x
+6. **16x2 LCD Display with I2C Module** - 1x
+7. **LED (5mm, any color)** - 1x
+8. **Resistors**:
+   - 220Ω (for LED) - 1x
+   - 10kΩ (for LDR pull-down) - 1x
+9. **Breadboard** - 1x
+10. **Jumper Wires** - Multiple
+
+### Optional Components
+- **External Power Supply** (5V, 1A) - For standalone operation
+- **Project Enclosure** - For protection
+- **PCB** - For permanent installation
+
+## Assembly Instructions
+
+### Step 1: Power Connections
+1. Connect ESP32 to USB power
+2. Verify 3.3V output from ESP32
+3. Connect all VCC pins to appropriate power sources
+
+### Step 2: I2C Bus Setup
+1. Connect GPIO21 to all SDA pins
+2. Connect GPIO22 to all SCL pins
+3. Add pull-up resistors if needed (usually built-in to modules)
+
+### Step 3: Digital Sensors
+1. Connect DHT11 data pin to GPIO4
+2. Connect LED circuit to GPIO2
+3. Connect LDR circuit to GPIO35
+
+### Step 4: Analog Sensors
+1. Connect rain sensor analog output to GPIO34
+2. Ensure proper grounding for analog circuits
+
+### Step 5: Testing
+1. Test each sensor individually
+2. Verify LCD display operation
+3. Check MQTT connectivity
+4. Validate complete system operation
+
+## Troubleshooting Guide
+
+### Common Issues
+- **I2C Communication**: Check SDA/SCL connections and addresses
+- **Power Issues**: Verify voltage levels and current capacity
+- **Sensor Readings**: Check pin assignments and wiring
+- **LCD Display**: Verify I2C address (usually 0x27)
+
+### Measurement Points
+- **3.3V Rail**: Should be stable at 3.3V
+- **I2C Signals**: Should show clear clock and data transitions
+- **Analog Inputs**: Should vary with sensor changes
+- **Digital Inputs**: Should show clear HIGH/LOW states

BIN
weather_station_diagram.jpg


+ 259 - 0
weatherstation.ino

@@ -0,0 +1,259 @@
+// -------- LIBRARIES --------
+#include <Wire.h>
+#include <LiquidCrystal_I2C.h>
+#include <WiFi.h>
+#include <PubSubClient.h>
+#include <DHT.h>
+#include <SFE_BMP180.h>
+// -------- PIN DEFINITIONS --------
+#define DHTPIN 4
+#define DHTTYPE DHT11
+#define LDR_PIN 35 // input only pin (good choice)
+#define RAIN_PIN 34 // analog pin
+#define LED_PIN 2
+// -------- OBJECTS --------
+LiquidCrystal_I2C lcd(0x27, 16, 2);
+DHT dht(DHTPIN, DHTTYPE);
+SFE_BMP180 bmp;
+WiFiClient espClient;
+PubSubClient client(espClient);
+// -------- WIFI & MQTT CREDENTIALS --------
+const char* ssid = "YOUR_WIFI_SSID";
+const char* password = "YOUR_WIFI_PASSWORD";
+const char* mqtt_server = "YOUR_MQTT_BROKER";
+const int mqtt_port = 1883;
+const char* mqtt_topic = "weather/station";
+// -------- VARIABLES --------
+double T, P;
+unsigned long lastSensorRead = 0;
+const long sensorInterval = 2000; // Read sensors every 2 seconds
+unsigned long lastMQTTSend = 0;
+const long mqttInterval = 30000; // Send data every 30 seconds
+
+struct WeatherData {
+  float temperature;
+  float humidity;
+  float pressure;
+  int rainLevel;
+  bool lightDetected;
+  bool valid;
+};
+
+WeatherData currentData;
+// -------- FUNCTIONS --------
+// DHT SENSOR
+void readDHT() {
+  float h = dht.readHumidity();
+  float t = dht.readTemperature();
+  if (isnan(h) || isnan(t)) {
+    Serial.println("DHT Error!");
+    currentData.valid = false;
+    return;
+  }
+  currentData.temperature = t;
+  currentData.humidity = h;
+}
+// RAIN SENSOR
+void readRain() {
+  int value = analogRead(RAIN_PIN);
+  value = map(value, 0, 4095, 0, 100);
+  value = 100 - value;
+  currentData.rainLevel = value;
+}
+// PRESSURE SENSOR
+void readPressure() {
+  if (bmp.startTemperature()) {
+    delay(100);
+    if (bmp.getTemperature(T)) {
+      if (bmp.startPressure(3)) {
+        delay(100);
+        if (bmp.getPressure(P, T)) {
+          currentData.pressure = P;
+        }
+      }
+    }
+  } else {
+    Serial.println("BMP180 Error");
+    currentData.valid = false;
+  }
+}
+// LDR SENSOR
+void readLDR() {
+  int value = digitalRead(LDR_PIN);
+  currentData.lightDetected = (value == HIGH);
+  digitalWrite(LED_PIN, currentData.lightDetected ? HIGH : LOW);
+}
+// READ ALL SENSORS
+void readSensors() {
+  currentData.valid = true;
+  readDHT();
+  readRain();
+  readPressure();
+  readLDR();
+  
+  if (currentData.valid) {
+    Serial.print("Temp: ");
+    Serial.print(currentData.temperature);
+    Serial.print("°C, Humidity: ");
+    Serial.print(currentData.humidity);
+    Serial.print("%, Rain: ");
+    Serial.print(currentData.rainLevel);
+    Serial.print("%, Pressure: ");
+    Serial.print(currentData.pressure);
+    Serial.print(" hPa, Light: ");
+    Serial.println(currentData.lightDetected ? "YES" : "NO");
+  }
+}
+// UPDATE LCD DISPLAY
+void updateDisplay() {
+  if (!currentData.valid) {
+    lcd.setCursor(0, 0);
+    lcd.print("Sensor Error! ");
+    lcd.setCursor(0, 1);
+    lcd.print("Check wiring ");
+    return;
+  }
+  
+  // Display temperature and humidity on first line
+  lcd.setCursor(0, 0);
+  lcd.print("T:");
+  lcd.print(currentData.temperature, 1);
+  lcd.print("C H:");
+  lcd.print(currentData.humidity, 0);
+  lcd.print("%");
+  
+  // Display rain and pressure on second line
+  lcd.setCursor(0, 1);
+  lcd.print("R:");
+  lcd.print(currentData.rainLevel);
+  lcd.print("% P:");
+  lcd.print(currentData.pressure, 0);
+  lcd.print(" ");
+}
+// SETUP WIFI
+void setupWiFi() {
+  Serial.println("Connecting to WiFi...");
+  lcd.setCursor(0, 0);
+  lcd.print("WiFi connecting");
+  
+  WiFi.begin(ssid, password);
+  
+  int attempts = 0;
+  while (WiFi.status() != WL_CONNECTED && attempts < 20) {
+    delay(500);
+    Serial.print(".");
+    attempts++;
+  }
+  
+  if (WiFi.status() == WL_CONNECTED) {
+    Serial.println("\nWiFi connected");
+    Serial.println("IP address: ");
+    Serial.println(WiFi.localIP());
+    lcd.setCursor(0, 0);
+    lcd.print("WiFi connected ");
+  } else {
+    Serial.println("Failed to connect to WiFi");
+    lcd.setCursor(0, 0);
+    lcd.print("WiFi failed! ");
+  }
+  
+  delay(2000);
+}
+// RECONNECT MQTT
+void reconnectMQTT() {
+  while (!client.connected()) {
+    Serial.print("Attempting MQTT connection...");
+    
+    String clientId = "ESP32WeatherStation-";
+    clientId += String(random(0xffff), HEX);
+    
+    if (client.connect(clientId.c_str())) {
+      Serial.println("connected");
+    } else {
+      Serial.print("failed, rc=");
+      Serial.print(client.state());
+      Serial.println(" try again in 5 seconds");
+      delay(5000);
+    }
+  }
+}
+// SEND MQTT DATA
+void sendMQTTData() {
+  if (!currentData.valid || !client.connected()) {
+    return;
+  }
+  
+  String payload = "{";
+  payload += "\"temperature\":" + String(currentData.temperature, 2) + ",";
+  payload += "\"humidity\":" + String(currentData.humidity, 2) + ",";
+  payload += "\"pressure\":" + String(currentData.pressure, 2) + ",";
+  payload += "\"rainLevel\":" + String(currentData.rainLevel) + ",";
+  payload += "\"lightDetected\":" + String(currentData.lightDetected ? "true" : "false");
+  payload += "}";
+  
+  if (client.publish(mqtt_topic, payload.c_str())) {
+    Serial.println("MQTT data sent successfully");
+  } else {
+    Serial.println("Failed to send MQTT data");
+  }
+}
+// -------- SETUP --------
+void setup() {
+  Serial.begin(115200);
+  
+  // Initialize pins
+  pinMode(LDR_PIN, INPUT);
+  pinMode(RAIN_PIN, INPUT);
+  pinMode(LED_PIN, OUTPUT);
+  digitalWrite(LED_PIN, LOW);
+  
+  // Initialize I2C and sensors
+  Wire.begin(21, 22); // SDA, SCL
+  lcd.init();
+  lcd.backlight();
+  dht.begin();
+  
+  if (!bmp.begin()) {
+    Serial.println("BMP180 not detected!");
+  }
+  
+  // Initialize WiFi
+  setupWiFi();
+  
+  // Initialize MQTT
+  client.setServer(mqtt_server, mqtt_port);
+  
+  // Initial sensor reading
+  readSensors();
+  updateDisplay();
+  
+  lcd.setCursor(0, 0);
+  lcd.print("System Ready");
+  delay(2000);
+  lcd.clear();
+}
+// -------- LOOP --------
+void loop() {
+  unsigned long currentMillis = millis();
+  
+  // Reconnect MQTT if needed
+  if (!client.connected()) {
+    reconnectMQTT();
+  }
+  client.loop();
+  
+  // Read sensors at regular interval
+  if (currentMillis - lastSensorRead >= sensorInterval) {
+    lastSensorRead = currentMillis;
+    readSensors();
+    updateDisplay();
+  }
+  
+  // Send MQTT data at regular interval
+  if (currentMillis - lastMQTTSend >= mqttInterval) {
+    lastMQTTSend = currentMillis;
+    sendMQTTData();
+  }
+  
+  delay(100);
+}