weatherstation.ino 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // -------- LIBRARIES --------
  2. #include <Wire.h>
  3. #include <LiquidCrystal_I2C.h>
  4. #include <WiFi.h>
  5. #include <PubSubClient.h>
  6. #include <DHT.h>
  7. #include <SFE_BMP180.h>
  8. // -------- PIN DEFINITIONS --------
  9. #define DHTPIN 4
  10. #define DHTTYPE DHT11
  11. #define LDR_PIN 35 // input only pin (good choice)
  12. #define RAIN_PIN 34 // analog pin
  13. #define LED_PIN 2
  14. // -------- OBJECTS --------
  15. LiquidCrystal_I2C lcd(0x27, 16, 2);
  16. DHT dht(DHTPIN, DHTTYPE);
  17. SFE_BMP180 bmp;
  18. WiFiClient espClient;
  19. PubSubClient client(espClient);
  20. // -------- WIFI & MQTT CREDENTIALS --------
  21. const char* ssid = "YOUR_WIFI_SSID";
  22. const char* password = "YOUR_WIFI_PASSWORD";
  23. const char* mqtt_server = "YOUR_MQTT_BROKER";
  24. const int mqtt_port = 1883;
  25. const char* mqtt_topic = "weather/station";
  26. // -------- VARIABLES --------
  27. double T, P;
  28. unsigned long lastSensorRead = 0;
  29. const long sensorInterval = 2000; // Read sensors every 2 seconds
  30. unsigned long lastMQTTSend = 0;
  31. const long mqttInterval = 30000; // Send data every 30 seconds
  32. struct WeatherData {
  33. float temperature;
  34. float humidity;
  35. float pressure;
  36. int rainLevel;
  37. bool lightDetected;
  38. bool valid;
  39. };
  40. WeatherData currentData;
  41. // -------- FUNCTIONS --------
  42. // DHT SENSOR
  43. void readDHT() {
  44. float h = dht.readHumidity();
  45. float t = dht.readTemperature();
  46. if (isnan(h) || isnan(t)) {
  47. Serial.println("DHT Error!");
  48. currentData.valid = false;
  49. return;
  50. }
  51. currentData.temperature = t;
  52. currentData.humidity = h;
  53. }
  54. // RAIN SENSOR
  55. void readRain() {
  56. int value = analogRead(RAIN_PIN);
  57. value = map(value, 0, 4095, 0, 100);
  58. value = 100 - value;
  59. currentData.rainLevel = value;
  60. }
  61. // PRESSURE SENSOR
  62. void readPressure() {
  63. if (bmp.startTemperature()) {
  64. delay(100);
  65. if (bmp.getTemperature(T)) {
  66. if (bmp.startPressure(3)) {
  67. delay(100);
  68. if (bmp.getPressure(P, T)) {
  69. currentData.pressure = P;
  70. }
  71. }
  72. }
  73. } else {
  74. Serial.println("BMP180 Error");
  75. currentData.valid = false;
  76. }
  77. }
  78. // LDR SENSOR
  79. void readLDR() {
  80. int value = digitalRead(LDR_PIN);
  81. currentData.lightDetected = (value == HIGH);
  82. digitalWrite(LED_PIN, currentData.lightDetected ? HIGH : LOW);
  83. }
  84. // READ ALL SENSORS
  85. void readSensors() {
  86. currentData.valid = true;
  87. readDHT();
  88. readRain();
  89. readPressure();
  90. readLDR();
  91. if (currentData.valid) {
  92. Serial.print("Temp: ");
  93. Serial.print(currentData.temperature);
  94. Serial.print("°C, Humidity: ");
  95. Serial.print(currentData.humidity);
  96. Serial.print("%, Rain: ");
  97. Serial.print(currentData.rainLevel);
  98. Serial.print("%, Pressure: ");
  99. Serial.print(currentData.pressure);
  100. Serial.print(" hPa, Light: ");
  101. Serial.println(currentData.lightDetected ? "YES" : "NO");
  102. }
  103. }
  104. // UPDATE LCD DISPLAY
  105. void updateDisplay() {
  106. if (!currentData.valid) {
  107. lcd.setCursor(0, 0);
  108. lcd.print("Sensor Error! ");
  109. lcd.setCursor(0, 1);
  110. lcd.print("Check wiring ");
  111. return;
  112. }
  113. // Display temperature and humidity on first line
  114. lcd.setCursor(0, 0);
  115. lcd.print("T:");
  116. lcd.print(currentData.temperature, 1);
  117. lcd.print("C H:");
  118. lcd.print(currentData.humidity, 0);
  119. lcd.print("%");
  120. // Display rain and pressure on second line
  121. lcd.setCursor(0, 1);
  122. lcd.print("R:");
  123. lcd.print(currentData.rainLevel);
  124. lcd.print("% P:");
  125. lcd.print(currentData.pressure, 0);
  126. lcd.print(" ");
  127. }
  128. // SETUP WIFI
  129. void setupWiFi() {
  130. Serial.println("Connecting to WiFi...");
  131. lcd.setCursor(0, 0);
  132. lcd.print("WiFi connecting");
  133. WiFi.begin(ssid, password);
  134. int attempts = 0;
  135. while (WiFi.status() != WL_CONNECTED && attempts < 20) {
  136. delay(500);
  137. Serial.print(".");
  138. attempts++;
  139. }
  140. if (WiFi.status() == WL_CONNECTED) {
  141. Serial.println("\nWiFi connected");
  142. Serial.println("IP address: ");
  143. Serial.println(WiFi.localIP());
  144. lcd.setCursor(0, 0);
  145. lcd.print("WiFi connected ");
  146. } else {
  147. Serial.println("Failed to connect to WiFi");
  148. lcd.setCursor(0, 0);
  149. lcd.print("WiFi failed! ");
  150. }
  151. delay(2000);
  152. }
  153. // RECONNECT MQTT
  154. void reconnectMQTT() {
  155. while (!client.connected()) {
  156. Serial.print("Attempting MQTT connection...");
  157. String clientId = "ESP32WeatherStation-";
  158. clientId += String(random(0xffff), HEX);
  159. if (client.connect(clientId.c_str())) {
  160. Serial.println("connected");
  161. } else {
  162. Serial.print("failed, rc=");
  163. Serial.print(client.state());
  164. Serial.println(" try again in 5 seconds");
  165. delay(5000);
  166. }
  167. }
  168. }
  169. // SEND MQTT DATA
  170. void sendMQTTData() {
  171. if (!currentData.valid || !client.connected()) {
  172. return;
  173. }
  174. String payload = "{";
  175. payload += "\"temperature\":" + String(currentData.temperature, 2) + ",";
  176. payload += "\"humidity\":" + String(currentData.humidity, 2) + ",";
  177. payload += "\"pressure\":" + String(currentData.pressure, 2) + ",";
  178. payload += "\"rainLevel\":" + String(currentData.rainLevel) + ",";
  179. payload += "\"lightDetected\":" + String(currentData.lightDetected ? "true" : "false");
  180. payload += "}";
  181. if (client.publish(mqtt_topic, payload.c_str())) {
  182. Serial.println("MQTT data sent successfully");
  183. } else {
  184. Serial.println("Failed to send MQTT data");
  185. }
  186. }
  187. // -------- SETUP --------
  188. void setup() {
  189. Serial.begin(115200);
  190. // Initialize pins
  191. pinMode(LDR_PIN, INPUT);
  192. pinMode(RAIN_PIN, INPUT);
  193. pinMode(LED_PIN, OUTPUT);
  194. digitalWrite(LED_PIN, LOW);
  195. // Initialize I2C and sensors
  196. Wire.begin(21, 22); // SDA, SCL
  197. lcd.init();
  198. lcd.backlight();
  199. dht.begin();
  200. if (!bmp.begin()) {
  201. Serial.println("BMP180 not detected!");
  202. }
  203. // Initialize WiFi
  204. setupWiFi();
  205. // Initialize MQTT
  206. client.setServer(mqtt_server, mqtt_port);
  207. // Initial sensor reading
  208. readSensors();
  209. updateDisplay();
  210. lcd.setCursor(0, 0);
  211. lcd.print("System Ready");
  212. delay(2000);
  213. lcd.clear();
  214. }
  215. // -------- LOOP --------
  216. void loop() {
  217. unsigned long currentMillis = millis();
  218. // Reconnect MQTT if needed
  219. if (!client.connected()) {
  220. reconnectMQTT();
  221. }
  222. client.loop();
  223. // Read sensors at regular interval
  224. if (currentMillis - lastSensorRead >= sensorInterval) {
  225. lastSensorRead = currentMillis;
  226. readSensors();
  227. updateDisplay();
  228. }
  229. // Send MQTT data at regular interval
  230. if (currentMillis - lastMQTTSend >= mqttInterval) {
  231. lastMQTTSend = currentMillis;
  232. sendMQTTData();
  233. }
  234. delay(100);
  235. }