Arduino Sketch for Rain Monitoring System using Rain Sensor, ThingSpeak and ESP32

#include <WiFi.h> 

#include <ThingSpeak.h> 

 

#define WIFI_SSID “YourWiFiSSID” 

#define WIFI_PASS “YourWiFiPassword” 

#define CHANNEL_ID 12345678 // Replace with your ThingSpeak Channel ID 

 

#define WRITE_API_KEY “YourWriteAPIKey” // Replace with your ThingSpeak Write API Key 

 

#define RAIN_SENSOR_PIN A6 // Replace with the analog pin connected to the rain sensor 

#define LED_PIN 13          // Replace with the GPIO pin connected to the LED 

 

WiFiClient client; 

unsigned long lastConnectionTime = 0; 

const unsigned long postingInterval = 60000; // Post data to ThingSpeak every 60 seconds 

 

void connectToWiFi() { 

 WiFi.begin(WIFI_SSID, WIFI_PASS); 

 while (WiFi.status() != WL_CONNECTED) { 

   delay(250); 

   Serial.println(“Connecting to WiFi…”); 

 } 

 Serial.println(“Connected to WiFi”); 

 

void sendToThingSpeak(int rainIntensity) { 

 ThingSpeak.setField(1, rainIntensity); 

 int statusCode = ThingSpeak.writeFields(CHANNEL_ID, WRITE_API_KEY); 

 

 if (statusCode == 200) { 

   Serial.println(“Data sent to ThingSpeak successfully”); 

 } else { 

   Serial.println(“Failed to send data to ThingSpeak. HTTP error code: ” + String(statusCode)); 

 } 

 

void setup() { 

 Serial.begin(115200); 

 pinMode(LED_PIN, OUTPUT); 

 connectToWiFi(); 

 ThingSpeak.begin(client); 

 

void loop() { 

 if (millis() – lastConnectionTime > postingInterval) { 

   int rainValue = analogRead(RAIN_SENSOR_PIN); 

 

    // Convert analog value to a percentage (0-100%) 

 int rainIntensity = map(rainValue, 4095,0, 0, 100); 

 

   sendToThingSpeak(rainIntensity); 

   // Adjust this threshold based on your sensor’s characteristics 

 

   if (rainIntensity > 50) { 

     digitalWrite(LED_PIN, HIGH); // Turn on the LED if rain intensity is above the threshold 

   }  

   else { 

     digitalWrite(LED_PIN, LOW);  // Turn off the LED if rain intensity is below the threshold 

   } 

   lastConnectionTime = millis(); 

 } 

 

Leave a comment

Your email address will not be published. Required fields are marked *