Skip to content
  • MySensors
  • OpenHardware.io
  • Categories
  • Recent
  • Tags
  • Popular
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo
  1. Home
  2. My Project
  3. Rain Guage

Rain Guage

Scheduled Pinned Locked Moved My Project
128 Posts 23 Posters 110.3k Views 21 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • petewillP petewill

    @BulldogLowell said:

    Do you want to use accumulated rain over X days as the trigger?

    As opposed to hours? I don't have too strong of an opinion either way. I think whatever is easier works. If they are both the same then maybe hours so we have a little more granular control?

    I was thinking about storing the time on EEPROM and retrieving the stored rain values from VERA for each of the last 5 days after a power-up/restart.

    I like that it will simplify the EEPROM more and potentially prolong the life of the device (since it's not using as much EEPROM). One thought though, if there is a communication error between Vera and the rain gauge when it is first started is there a way to prevent the rain gauge from subsequently overwriting the values in Vera? I don't know too much about the "ack" portion of the communication but maybe that would make it so it's not an issue?

    I'm excited to see the new code. Keep up the good work!

    BulldogLowellB Offline
    BulldogLowellB Offline
    BulldogLowell
    Contest Winner
    wrote on last edited by
    #78

    @petewill said:

    As opposed to hours? I don't have too strong of an opinion either way. I think whatever is easier works. If they are both the same then maybe hours so we have a little more granular control?

    that's where we were with the 120 hour framework, so let's leave that. I'm not worried about EEPROM life, you get 100,000 writes and that is your lifetime++ using the circular buffer. I did the math on it but can't recall the exact number.

    So, we won't change EEPROM data, actually may need to add another 24hours. We just send to VERA the total of each of the past 5 days instead of the total accumulated rainfall over the past 24, 48, 72, 96 and 120 hours. This will be calendar days, we will verify by getting the time from VERA, and synchronize that a few times daily. the days will rollover at midnight, and the daily accumulation will be cascaded back accordingly.

    trigger for the sensor will still be total accumulation over so many hours.

    Yes?

    petewillP 1 Reply Last reply
    0
    • BulldogLowellB BulldogLowell

      @petewill said:

      As opposed to hours? I don't have too strong of an opinion either way. I think whatever is easier works. If they are both the same then maybe hours so we have a little more granular control?

      that's where we were with the 120 hour framework, so let's leave that. I'm not worried about EEPROM life, you get 100,000 writes and that is your lifetime++ using the circular buffer. I did the math on it but can't recall the exact number.

      So, we won't change EEPROM data, actually may need to add another 24hours. We just send to VERA the total of each of the past 5 days instead of the total accumulated rainfall over the past 24, 48, 72, 96 and 120 hours. This will be calendar days, we will verify by getting the time from VERA, and synchronize that a few times daily. the days will rollover at midnight, and the daily accumulation will be cascaded back accordingly.

      trigger for the sensor will still be total accumulation over so many hours.

      Yes?

      petewillP Offline
      petewillP Offline
      petewill
      Admin
      wrote on last edited by
      #79

      @BulldogLowell That sounds GREAT to me! This is your baby though (and you have much more experience with this stuff) so I trust what direction you go.

      My "How To" home automation video channel: https://www.youtube.com/channel/UCq_Evyh5PQALx4m4CQuxqkA

      BulldogLowellB 1 Reply Last reply
      0
      • petewillP petewill

        @BulldogLowell That sounds GREAT to me! This is your baby though (and you have much more experience with this stuff) so I trust what direction you go.

        BulldogLowellB Offline
        BulldogLowellB Offline
        BulldogLowell
        Contest Winner
        wrote on last edited by
        #80

        @petewill

        here is some (untested) mods to update the 5 day rainfall history once per day at midnight. Take a look, let me know what you think (any problems issues). It turns out I was overthinking the problem and it really only needed minor mods...

        /*
         Arduino Tipping Bucket Rain Gauge
        
         April 26, 2015
        
         Version 1.4.1 alpha
        
         Arduino Tipping Bucket Rain Gauge
        
         Utilizing a tipping bucket sensor, your Vera home automation controller and the MySensors.org
         gateway you can measure and sense local rain.  This sketch will create two devices on your
         Vera controller.  One will display your total precipitation for the last 24, 48, 72, 96 and 120
         hours.  The other, a sensor that changes state if there is recent rain (up to last 120 hours)
         above a threshold.  Both these settings are user definable.
        
         This sketch features the following:
        
         * Allows you to set the rain threshold in mm
         * Allows you to determine the interval window up to 120 hours.
         * Displays the last 5 days of rain in Variable1 through Variable5
           of the Rain Sensor device
         * Configuration changes to Sensor device updated every hour
         * SHould run on any Arduino
         * Will retain Tripped/Not Tripped status and data in a power interruption, saving small ammount
           of data to EEPROM (Circular Buffer to maximize life of EEPROM)
         * LED status indicator
        
         by @BulldogLowell and @PeteWill for free public use
        
         */
        #include <SPI.h>
        #include <MySensor.h>
        #include <math.h>
        #include <Time.h>
        
        #define NODE_ID 24
        #define SKETCH_NAME "Rain Gauge"
        #define SKETCH_VERSION "1.4.1a"
        
        #define DWELL_TIME 125  // this allows for radio to come back to power after a transmission, ideally 0 
        
        #define DEBUG_ON  // comment out this line to disable serial debug
        
        #define CHILD_ID_RAIN_LOG 3  // Keeps track of accumulated rainfall
        #define CHILD_ID_TRIPPED_INDICATOR 4  // Indicates Tripped when rain detected
        
        #define EEPROM_STATE_LOCATION 0 // location to save state to EEPROM
        #define EEPROM_BUFFER_LOCATION 1  // location of the EEPROM circular buffer
        #define BUFFER_LENGTH 121
        
        #define CALIBRATE_FACTOR 100 // e.g. 5 is .05mm (or 5 hundredths of an inch if imperial) per tip
        
        #ifdef  DEBUG_ON
        #define DEBUG_PRINT(x)   Serial.print(x)
        #define DEBUG_PRINTLN(x) Serial.println(x)
        #define SERIAL_START(x)  Serial.begin(x)
        #else
        #define DEBUG_PRINT(x)
        #define DEBUG_PRINTLN(x)
        #define SERIAL_START(x)
        #endif
        //
        MySensor gw;
        //
        MyMessage msgRainRate(CHILD_ID_RAIN_LOG, V_RAINRATE);
        MyMessage msgRain(CHILD_ID_RAIN_LOG, V_RAIN);
        //
        MyMessage msgRainVAR1(CHILD_ID_RAIN_LOG, V_VAR1);
        MyMessage msgRainVAR2(CHILD_ID_RAIN_LOG, V_VAR2);
        MyMessage msgRainVAR3(CHILD_ID_RAIN_LOG, V_VAR3);
        MyMessage msgRainVAR4(CHILD_ID_RAIN_LOG, V_VAR4);
        MyMessage msgRainVAR5(CHILD_ID_RAIN_LOG, V_VAR5);
        //
        MyMessage msgTripped(CHILD_ID_TRIPPED_INDICATOR, V_TRIPPED);
        MyMessage msgTrippedVar1(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
        MyMessage msgTrippedVar2(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
        //
        boolean metric = true;
        int eepromIndex;
        int tipSensorPin = 3; // Must be interrupt capable pin
        int ledPin = 5; // PWM capable pin required
        unsigned long dataMillis;
        const unsigned long serialInterval = 10000UL;
        const unsigned long oneHour = 3600000UL;
        unsigned long lastTipTime;
        unsigned long startMillis;
        unsigned int rainBucket [24] ; /* 24 hours = 1 day of data */
        unsigned int rainRate = 0;
        volatile int wasTippedBuffer = 0;
        byte rainWindow = 72;         //default rain window in hours
        int rainSensorThreshold = 50; //default rain sensor sensitivity in hundredths.  Will be overwritten with msgTrippedVar2.
        byte state = 0;
        byte oldState = -1;
        int lastRainRate = 0;
        int lastMeasure = 0;
        boolean gotTime = false;
        byte lastHour;
        
        void setup()
        {
          SERIAL_START(115200);
          //
          // Set up the IO
          pinMode(tipSensorPin, INPUT_PULLUP);
          attachInterrupt (1, sensorTipped, FALLING);  // depending on location of the hall effect sensor may need CHANGE
          pinMode(ledPin, OUTPUT);
          digitalWrite(ledPin, HIGH);
          //
          //Let's get the controller talking to the Arduino
          gw.begin(getVariables, NODE_ID);
          gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
          delay(DWELL_TIME);
          gw.present(CHILD_ID_RAIN_LOG, S_RAIN);
          delay(DWELL_TIME);
          gw.present(CHILD_ID_TRIPPED_INDICATOR, S_MOTION);
          delay(DWELL_TIME);
          DEBUG_PRINTLN(F("Sensor Presentation Complete"));
          state = gw.loadState(EEPROM_STATE_LOCATION); //retreive prior state from EEPROM
          DEBUG_PRINT(F("Previous Tripped State (from EEPROM): "));
          DEBUG_PRINTLN(state ? "Tripped" : "Not Tripped");
          //
          gw.send(msgTripped.set(state));
          delay(DWELL_TIME);
          //
          //Sync time with the server, this will be called hourly in order to keep time from creeping with the crystal
          //
          while(timeStatus() == timeNotSet)
          {
            gw.process();
            gw.requestTime(receiveTime);
            Serial.println("getting Time");
            delay(1000); // call once per second
            Serial.print(".");
          }
          //
          //retrieve from EEPROM stored values on a power cycle.
          //
          boolean isDataOnEeprom = false;
          for (int i = 0; i < BUFFER_LENGTH; i++)
          {
            byte locator = gw.loadState(EEPROM_BUFFER_LOCATION + 2 * i); //<<<<<<<<<<<
            if (locator == 0xFF)  // found the EEPROM circular buffer index
            {
              eepromIndex = EEPROM_BUFFER_LOCATION + 2 * i;
              //Now that we have the buffer index let's populate the rainBucket[] with data from eeprom
              loadRainArray(eepromIndex);
              isDataOnEeprom = true;
              DEBUG_PRINT("EEPROM Index ");
              DEBUG_PRINTLN(eepromIndex);
              isDataOnEeprom = true;
              break;
            }
          }
          if (!isDataOnEeprom) // Added for the first time it is run on a new arduino
          {
            eepromIndex = 1;
            gw.saveState(eepromIndex, 0xFF); // store the EEPROM index marker...
            gw.saveState(eepromIndex + 1, 0xFF);
          }
          dataMillis = millis();
          startMillis = millis();
          lastTipTime = millis() - oneHour;
          //
          //Get sensor time window and threshold from controller
          gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1); 
          delay(DWELL_TIME);
          gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2); 
          delay(DWELL_TIME);
          DEBUG_PRINTLN(F("Radio Setup Complete!"));
        }
        
        void loop()
        {
          gw.process();
          if (state)
          {
            prettyFade();  // breathe if tripped
          }
          else
          {
            slowFlash();   // blink if not tripped
          }
        #ifdef DEBUG_ON  // Serial Debug Block
          if ( (millis() - dataMillis) >= serialInterval)
          {
            for (int i = 24; i <= 120; i = i + 24)
            {
              updateSerialData(i);
            }
            dataMillis = millis();
          }
        #endif
          //
          // let's constantly check to see if the rain in the past rainWindow hours is greater than rainSensorThreshold
          //
          int measure = 0; // Check to see if we need to show sensor tripped in this block
          for (int i = 0; i < rainWindow; i++)
          {
            measure += rainBucket [i];
            if (measure != lastMeasure)
            {
              DEBUG_PRINT(F("measure value (total rainBucket within rainWindow): "));
              DEBUG_PRINTLN(measure);
              lastMeasure = measure;
            }
          }
          //
          state = (measure >= rainSensorThreshold);
          if (state != oldState)
          {
            gw.send(msgTripped.set(state));
            delay(DWELL_TIME);
            gw.saveState(EEPROM_STATE_LOCATION, state); //New Code
            DEBUG_PRINT(F("New Sensor State... Sensor: "));
            DEBUG_PRINTLN(state? "Tripped" : "Not Tripped");
            oldState = state;
          }
          //
          unsigned long tipDelay = millis() - lastTipTime;
          if (wasTippedBuffer) // if was tipped, then update the 24hour total and transmit to Vera
          {
            DEBUG_PRINTLN(F("Sensor Tipped"));
            DEBUG_PRINT(F("rainBucket [0] value: "));
            DEBUG_PRINTLN(rainBucket [0]);
            //
            int dayTotal = 0;
            for (int i = 0; i < 24; i++)
            {
              dayTotal = dayTotal + rainBucket [i];
            }
            //
            DEBUG_PRINT(F("dayTotal value: "));
            DEBUG_PRINTLN(dayTotal);
            gw.send(msgRain.set(dayTotal, 1));
            delay(DWELL_TIME);
            wasTippedBuffer--;
            rainRate = ((oneHour) / tipDelay);
            if (rainRate != lastRainRate)
            {
              gw.send(msgRainRate.set(rainRate, 1));
              delay(DWELL_TIME);
              DEBUG_PRINT(F("RainRate= "));
              DEBUG_PRINTLN(rainRate);
              lastRainRate = rainRate;
            }
          }
          if (tipDelay > oneHour)
          {
            rainRate = 0;
            gw.send(msgRainRate.set(rainRate, 1));
          }
          //
          if (millis() - startMillis >= oneHour)
          {
            DEBUG_PRINTLN(F("One hour elapsed."));
            for (int i = BUFFER_LENGTH - 1; i >= 0; i--)//cascade an hour of values back into the array
            {
              rainBucket [i + 1] = rainBucket [i];
            }
            rainBucket[0] = 0;
            gw.send(msgRain.set(rainTotal(24), 1)); // send 24hr tips
            delay(DWELL_TIME);
            gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
            delay(DWELL_TIME);
            gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
            delay(DWELL_TIME);
            gw.saveState(eepromIndex, highByte(rainBucket[0]));
            gw.saveState(eepromIndex + 1, lowByte(rainBucket[0]));
            eepromIndex++;
            if (eepromIndex > EEPROM_BUFFER_LOCATION + BUFFER_LENGTH) eepromIndex = EEPROM_BUFFER_LOCATION;
            DEBUG_PRINT(F("Writing to EEPROM.  Index: "));
            DEBUG_PRINTLN(eepromIndex);
            gw.saveState(eepromIndex, 0xFF);
            gw.saveState(eepromIndex + 1, 0xFF);
            gw.requestTime(receiveTime); // sync the time every hour
            delay(DWELL_TIME);
            startMillis = millis();
          }
          if (hour() == 0 and lastHour == 23)
          {
            transmitRainData();
          }
          lastHour = hour();
        }
        
        void sensorTipped()
        {
          unsigned long thisTipTime = millis();
          if (thisTipTime - lastTipTime > 100UL)
          {
            rainBucket[0] += CALIBRATE_FACTOR; // adds CALIBRATE_FACTOR hundredths of unit each tip
            wasTippedBuffer++;
          }
          lastTipTime = thisTipTime;
        }
        //
        int rainTotal(int hours)
        {
          int total = 0;
          for ( int i = 0; i < hours; i++)
          {
            total += rainBucket [i];
          }
          return total;
        }
        
        void updateSerialData(int x)
        {
          DEBUG_PRINT(F("Tips last "));
          DEBUG_PRINT(x);
          DEBUG_PRINTLN(F(" hours: "));
          int tipCount = 0;
          for (int i = 0; i < x; i++)
          {
            tipCount = tipCount + rainBucket [i];
          }
          DEBUG_PRINTLN(tipCount);
        }
        
        void loadRainArray(int value) // load stored rain array from EEPROM on powerup
        {
          for (int i = 0; i < BUFFER_LENGTH - 1; i++)
          {
            value--;
            DEBUG_PRINT("EEPROM location: ");
            DEBUG_PRINTLN(value);
            if (value < EEPROM_BUFFER_LOCATION)
            {
              value = EEPROM_BUFFER_LOCATION + BUFFER_LENGTH;
            }
            byte rainValueHigh = gw.loadState(value);
            byte rainValueLow = gw.loadState(value + 1);
            int rainValue = (rainValueHigh << 8) & rainValueLow;
            rainBucket[i] = rainValue;
            //
            DEBUG_PRINT(F("rainBucket[ value: "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F("] value: "));
            DEBUG_PRINTLN(rainBucket[i]);
          }
        }
        
        void transmitRainData(void)
        {
          int rainUpdateTotal = 0;
          for (int i = 0; i < 24; i++)
          {
            rainUpdateTotal += rainBucket[i];
          }
          gw.send(msgRainVAR1.set(( float) rainUpdateTotal / 100.0 , 1));
          delay(DWELL_TIME);
          rainUpdateTotal = 0;
          for (int i = 24; i < 48; i++)
          {
            rainUpdateTotal += rainBucket[i];
          }
          gw.send(msgRainVAR2.set( (float) rainUpdateTotal / 100.0 , 1));
          delay(DWELL_TIME);
          rainUpdateTotal = 0;
          for (int i = 48; i < 72; i++)
          {
            rainUpdateTotal += rainBucket[i];
          }
          gw.send(msgRainVAR3.set( (float) rainUpdateTotal / 100.0 , 1));
          delay(DWELL_TIME);
          rainUpdateTotal = 0;
          for (int i = 72; i < 96; i++)
          {
            rainUpdateTotal += rainBucket[i];
          }
          gw.send(msgRainVAR4.set( (float) rainUpdateTotal / 100.0 , 1));
          delay(DWELL_TIME);
          rainUpdateTotal = 0;
          for (int i = 96; i < 120; i++)
          {
            rainUpdateTotal += rainBucket[i];
          }
          gw.send(msgRainVAR5.set( (float) rainUpdateTotal / 100.0 , 1));
          delay(DWELL_TIME);
        }
        
        void getVariables(const MyMessage &message)
        {
          if (message.sensor == CHILD_ID_RAIN_LOG)
          {
            // nothing to do here
          }
          else if (message.sensor == CHILD_ID_TRIPPED_INDICATOR)
          {
            if (message.type == V_VAR1)
            {
              rainWindow = atoi(message.data);
              if (rainWindow > 120)
              {
                rainWindow = 120;
              }
              else if (rainWindow < 1)
              {
                rainWindow = 1;
              }
              if (rainWindow != atoi(message.data))   // if I changed the value back inside the boundries, push that number back to Vera
              {
                gw.send(msgTrippedVar1.set(rainWindow));
              }
            }
            else if (message.type == V_VAR2)
            {
              rainSensorThreshold = atoi(message.data);
              if (rainSensorThreshold > 10000)
              {
                rainSensorThreshold = 10000;
              }
              else if (rainSensorThreshold < 1)
              {
                rainSensorThreshold = 1;
              }
              if (rainSensorThreshold != atoi(message.data))  // if I changed the value back inside the boundries, push that number back to Vera
              {
                gw.send(msgTrippedVar2.set(rainSensorThreshold));
              }
            }
          }
        }
        
        void prettyFade(void)
        {
          float val = (exp(sin(millis() / 2000.0 * PI)) - 0.36787944) * 108.0;
          analogWrite(ledPin, val);
        }
        
        void slowFlash(void)
        {
          static boolean ledState = true;
          static unsigned long pulseStart = millis();
          if (millis() - pulseStart < 100UL)
          {
            digitalWrite(ledPin, !ledState);
            pulseStart = millis();
          }
        }
        
        void receiveTime(unsigned long time)
        {
          DEBUG_PRINTLN(F("Time received from controller..."));
          setTime(time);
          char theTime[26];
          sprintf(theTime, "The current time is %d:%2d", hour(), minute());
          DEBUG_PRINTLN(theTime);
        }
        
        RJ_MakeR 1 Reply Last reply
        1
        • BulldogLowellB BulldogLowell

          @petewill

          here is some (untested) mods to update the 5 day rainfall history once per day at midnight. Take a look, let me know what you think (any problems issues). It turns out I was overthinking the problem and it really only needed minor mods...

          /*
           Arduino Tipping Bucket Rain Gauge
          
           April 26, 2015
          
           Version 1.4.1 alpha
          
           Arduino Tipping Bucket Rain Gauge
          
           Utilizing a tipping bucket sensor, your Vera home automation controller and the MySensors.org
           gateway you can measure and sense local rain.  This sketch will create two devices on your
           Vera controller.  One will display your total precipitation for the last 24, 48, 72, 96 and 120
           hours.  The other, a sensor that changes state if there is recent rain (up to last 120 hours)
           above a threshold.  Both these settings are user definable.
          
           This sketch features the following:
          
           * Allows you to set the rain threshold in mm
           * Allows you to determine the interval window up to 120 hours.
           * Displays the last 5 days of rain in Variable1 through Variable5
             of the Rain Sensor device
           * Configuration changes to Sensor device updated every hour
           * SHould run on any Arduino
           * Will retain Tripped/Not Tripped status and data in a power interruption, saving small ammount
             of data to EEPROM (Circular Buffer to maximize life of EEPROM)
           * LED status indicator
          
           by @BulldogLowell and @PeteWill for free public use
          
           */
          #include <SPI.h>
          #include <MySensor.h>
          #include <math.h>
          #include <Time.h>
          
          #define NODE_ID 24
          #define SKETCH_NAME "Rain Gauge"
          #define SKETCH_VERSION "1.4.1a"
          
          #define DWELL_TIME 125  // this allows for radio to come back to power after a transmission, ideally 0 
          
          #define DEBUG_ON  // comment out this line to disable serial debug
          
          #define CHILD_ID_RAIN_LOG 3  // Keeps track of accumulated rainfall
          #define CHILD_ID_TRIPPED_INDICATOR 4  // Indicates Tripped when rain detected
          
          #define EEPROM_STATE_LOCATION 0 // location to save state to EEPROM
          #define EEPROM_BUFFER_LOCATION 1  // location of the EEPROM circular buffer
          #define BUFFER_LENGTH 121
          
          #define CALIBRATE_FACTOR 100 // e.g. 5 is .05mm (or 5 hundredths of an inch if imperial) per tip
          
          #ifdef  DEBUG_ON
          #define DEBUG_PRINT(x)   Serial.print(x)
          #define DEBUG_PRINTLN(x) Serial.println(x)
          #define SERIAL_START(x)  Serial.begin(x)
          #else
          #define DEBUG_PRINT(x)
          #define DEBUG_PRINTLN(x)
          #define SERIAL_START(x)
          #endif
          //
          MySensor gw;
          //
          MyMessage msgRainRate(CHILD_ID_RAIN_LOG, V_RAINRATE);
          MyMessage msgRain(CHILD_ID_RAIN_LOG, V_RAIN);
          //
          MyMessage msgRainVAR1(CHILD_ID_RAIN_LOG, V_VAR1);
          MyMessage msgRainVAR2(CHILD_ID_RAIN_LOG, V_VAR2);
          MyMessage msgRainVAR3(CHILD_ID_RAIN_LOG, V_VAR3);
          MyMessage msgRainVAR4(CHILD_ID_RAIN_LOG, V_VAR4);
          MyMessage msgRainVAR5(CHILD_ID_RAIN_LOG, V_VAR5);
          //
          MyMessage msgTripped(CHILD_ID_TRIPPED_INDICATOR, V_TRIPPED);
          MyMessage msgTrippedVar1(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
          MyMessage msgTrippedVar2(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
          //
          boolean metric = true;
          int eepromIndex;
          int tipSensorPin = 3; // Must be interrupt capable pin
          int ledPin = 5; // PWM capable pin required
          unsigned long dataMillis;
          const unsigned long serialInterval = 10000UL;
          const unsigned long oneHour = 3600000UL;
          unsigned long lastTipTime;
          unsigned long startMillis;
          unsigned int rainBucket [24] ; /* 24 hours = 1 day of data */
          unsigned int rainRate = 0;
          volatile int wasTippedBuffer = 0;
          byte rainWindow = 72;         //default rain window in hours
          int rainSensorThreshold = 50; //default rain sensor sensitivity in hundredths.  Will be overwritten with msgTrippedVar2.
          byte state = 0;
          byte oldState = -1;
          int lastRainRate = 0;
          int lastMeasure = 0;
          boolean gotTime = false;
          byte lastHour;
          
          void setup()
          {
            SERIAL_START(115200);
            //
            // Set up the IO
            pinMode(tipSensorPin, INPUT_PULLUP);
            attachInterrupt (1, sensorTipped, FALLING);  // depending on location of the hall effect sensor may need CHANGE
            pinMode(ledPin, OUTPUT);
            digitalWrite(ledPin, HIGH);
            //
            //Let's get the controller talking to the Arduino
            gw.begin(getVariables, NODE_ID);
            gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
            delay(DWELL_TIME);
            gw.present(CHILD_ID_RAIN_LOG, S_RAIN);
            delay(DWELL_TIME);
            gw.present(CHILD_ID_TRIPPED_INDICATOR, S_MOTION);
            delay(DWELL_TIME);
            DEBUG_PRINTLN(F("Sensor Presentation Complete"));
            state = gw.loadState(EEPROM_STATE_LOCATION); //retreive prior state from EEPROM
            DEBUG_PRINT(F("Previous Tripped State (from EEPROM): "));
            DEBUG_PRINTLN(state ? "Tripped" : "Not Tripped");
            //
            gw.send(msgTripped.set(state));
            delay(DWELL_TIME);
            //
            //Sync time with the server, this will be called hourly in order to keep time from creeping with the crystal
            //
            while(timeStatus() == timeNotSet)
            {
              gw.process();
              gw.requestTime(receiveTime);
              Serial.println("getting Time");
              delay(1000); // call once per second
              Serial.print(".");
            }
            //
            //retrieve from EEPROM stored values on a power cycle.
            //
            boolean isDataOnEeprom = false;
            for (int i = 0; i < BUFFER_LENGTH; i++)
            {
              byte locator = gw.loadState(EEPROM_BUFFER_LOCATION + 2 * i); //<<<<<<<<<<<
              if (locator == 0xFF)  // found the EEPROM circular buffer index
              {
                eepromIndex = EEPROM_BUFFER_LOCATION + 2 * i;
                //Now that we have the buffer index let's populate the rainBucket[] with data from eeprom
                loadRainArray(eepromIndex);
                isDataOnEeprom = true;
                DEBUG_PRINT("EEPROM Index ");
                DEBUG_PRINTLN(eepromIndex);
                isDataOnEeprom = true;
                break;
              }
            }
            if (!isDataOnEeprom) // Added for the first time it is run on a new arduino
            {
              eepromIndex = 1;
              gw.saveState(eepromIndex, 0xFF); // store the EEPROM index marker...
              gw.saveState(eepromIndex + 1, 0xFF);
            }
            dataMillis = millis();
            startMillis = millis();
            lastTipTime = millis() - oneHour;
            //
            //Get sensor time window and threshold from controller
            gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1); 
            delay(DWELL_TIME);
            gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2); 
            delay(DWELL_TIME);
            DEBUG_PRINTLN(F("Radio Setup Complete!"));
          }
          
          void loop()
          {
            gw.process();
            if (state)
            {
              prettyFade();  // breathe if tripped
            }
            else
            {
              slowFlash();   // blink if not tripped
            }
          #ifdef DEBUG_ON  // Serial Debug Block
            if ( (millis() - dataMillis) >= serialInterval)
            {
              for (int i = 24; i <= 120; i = i + 24)
              {
                updateSerialData(i);
              }
              dataMillis = millis();
            }
          #endif
            //
            // let's constantly check to see if the rain in the past rainWindow hours is greater than rainSensorThreshold
            //
            int measure = 0; // Check to see if we need to show sensor tripped in this block
            for (int i = 0; i < rainWindow; i++)
            {
              measure += rainBucket [i];
              if (measure != lastMeasure)
              {
                DEBUG_PRINT(F("measure value (total rainBucket within rainWindow): "));
                DEBUG_PRINTLN(measure);
                lastMeasure = measure;
              }
            }
            //
            state = (measure >= rainSensorThreshold);
            if (state != oldState)
            {
              gw.send(msgTripped.set(state));
              delay(DWELL_TIME);
              gw.saveState(EEPROM_STATE_LOCATION, state); //New Code
              DEBUG_PRINT(F("New Sensor State... Sensor: "));
              DEBUG_PRINTLN(state? "Tripped" : "Not Tripped");
              oldState = state;
            }
            //
            unsigned long tipDelay = millis() - lastTipTime;
            if (wasTippedBuffer) // if was tipped, then update the 24hour total and transmit to Vera
            {
              DEBUG_PRINTLN(F("Sensor Tipped"));
              DEBUG_PRINT(F("rainBucket [0] value: "));
              DEBUG_PRINTLN(rainBucket [0]);
              //
              int dayTotal = 0;
              for (int i = 0; i < 24; i++)
              {
                dayTotal = dayTotal + rainBucket [i];
              }
              //
              DEBUG_PRINT(F("dayTotal value: "));
              DEBUG_PRINTLN(dayTotal);
              gw.send(msgRain.set(dayTotal, 1));
              delay(DWELL_TIME);
              wasTippedBuffer--;
              rainRate = ((oneHour) / tipDelay);
              if (rainRate != lastRainRate)
              {
                gw.send(msgRainRate.set(rainRate, 1));
                delay(DWELL_TIME);
                DEBUG_PRINT(F("RainRate= "));
                DEBUG_PRINTLN(rainRate);
                lastRainRate = rainRate;
              }
            }
            if (tipDelay > oneHour)
            {
              rainRate = 0;
              gw.send(msgRainRate.set(rainRate, 1));
            }
            //
            if (millis() - startMillis >= oneHour)
            {
              DEBUG_PRINTLN(F("One hour elapsed."));
              for (int i = BUFFER_LENGTH - 1; i >= 0; i--)//cascade an hour of values back into the array
              {
                rainBucket [i + 1] = rainBucket [i];
              }
              rainBucket[0] = 0;
              gw.send(msgRain.set(rainTotal(24), 1)); // send 24hr tips
              delay(DWELL_TIME);
              gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
              delay(DWELL_TIME);
              gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
              delay(DWELL_TIME);
              gw.saveState(eepromIndex, highByte(rainBucket[0]));
              gw.saveState(eepromIndex + 1, lowByte(rainBucket[0]));
              eepromIndex++;
              if (eepromIndex > EEPROM_BUFFER_LOCATION + BUFFER_LENGTH) eepromIndex = EEPROM_BUFFER_LOCATION;
              DEBUG_PRINT(F("Writing to EEPROM.  Index: "));
              DEBUG_PRINTLN(eepromIndex);
              gw.saveState(eepromIndex, 0xFF);
              gw.saveState(eepromIndex + 1, 0xFF);
              gw.requestTime(receiveTime); // sync the time every hour
              delay(DWELL_TIME);
              startMillis = millis();
            }
            if (hour() == 0 and lastHour == 23)
            {
              transmitRainData();
            }
            lastHour = hour();
          }
          
          void sensorTipped()
          {
            unsigned long thisTipTime = millis();
            if (thisTipTime - lastTipTime > 100UL)
            {
              rainBucket[0] += CALIBRATE_FACTOR; // adds CALIBRATE_FACTOR hundredths of unit each tip
              wasTippedBuffer++;
            }
            lastTipTime = thisTipTime;
          }
          //
          int rainTotal(int hours)
          {
            int total = 0;
            for ( int i = 0; i < hours; i++)
            {
              total += rainBucket [i];
            }
            return total;
          }
          
          void updateSerialData(int x)
          {
            DEBUG_PRINT(F("Tips last "));
            DEBUG_PRINT(x);
            DEBUG_PRINTLN(F(" hours: "));
            int tipCount = 0;
            for (int i = 0; i < x; i++)
            {
              tipCount = tipCount + rainBucket [i];
            }
            DEBUG_PRINTLN(tipCount);
          }
          
          void loadRainArray(int value) // load stored rain array from EEPROM on powerup
          {
            for (int i = 0; i < BUFFER_LENGTH - 1; i++)
            {
              value--;
              DEBUG_PRINT("EEPROM location: ");
              DEBUG_PRINTLN(value);
              if (value < EEPROM_BUFFER_LOCATION)
              {
                value = EEPROM_BUFFER_LOCATION + BUFFER_LENGTH;
              }
              byte rainValueHigh = gw.loadState(value);
              byte rainValueLow = gw.loadState(value + 1);
              int rainValue = (rainValueHigh << 8) & rainValueLow;
              rainBucket[i] = rainValue;
              //
              DEBUG_PRINT(F("rainBucket[ value: "));
              DEBUG_PRINT(i);
              DEBUG_PRINT(F("] value: "));
              DEBUG_PRINTLN(rainBucket[i]);
            }
          }
          
          void transmitRainData(void)
          {
            int rainUpdateTotal = 0;
            for (int i = 0; i < 24; i++)
            {
              rainUpdateTotal += rainBucket[i];
            }
            gw.send(msgRainVAR1.set(( float) rainUpdateTotal / 100.0 , 1));
            delay(DWELL_TIME);
            rainUpdateTotal = 0;
            for (int i = 24; i < 48; i++)
            {
              rainUpdateTotal += rainBucket[i];
            }
            gw.send(msgRainVAR2.set( (float) rainUpdateTotal / 100.0 , 1));
            delay(DWELL_TIME);
            rainUpdateTotal = 0;
            for (int i = 48; i < 72; i++)
            {
              rainUpdateTotal += rainBucket[i];
            }
            gw.send(msgRainVAR3.set( (float) rainUpdateTotal / 100.0 , 1));
            delay(DWELL_TIME);
            rainUpdateTotal = 0;
            for (int i = 72; i < 96; i++)
            {
              rainUpdateTotal += rainBucket[i];
            }
            gw.send(msgRainVAR4.set( (float) rainUpdateTotal / 100.0 , 1));
            delay(DWELL_TIME);
            rainUpdateTotal = 0;
            for (int i = 96; i < 120; i++)
            {
              rainUpdateTotal += rainBucket[i];
            }
            gw.send(msgRainVAR5.set( (float) rainUpdateTotal / 100.0 , 1));
            delay(DWELL_TIME);
          }
          
          void getVariables(const MyMessage &message)
          {
            if (message.sensor == CHILD_ID_RAIN_LOG)
            {
              // nothing to do here
            }
            else if (message.sensor == CHILD_ID_TRIPPED_INDICATOR)
            {
              if (message.type == V_VAR1)
              {
                rainWindow = atoi(message.data);
                if (rainWindow > 120)
                {
                  rainWindow = 120;
                }
                else if (rainWindow < 1)
                {
                  rainWindow = 1;
                }
                if (rainWindow != atoi(message.data))   // if I changed the value back inside the boundries, push that number back to Vera
                {
                  gw.send(msgTrippedVar1.set(rainWindow));
                }
              }
              else if (message.type == V_VAR2)
              {
                rainSensorThreshold = atoi(message.data);
                if (rainSensorThreshold > 10000)
                {
                  rainSensorThreshold = 10000;
                }
                else if (rainSensorThreshold < 1)
                {
                  rainSensorThreshold = 1;
                }
                if (rainSensorThreshold != atoi(message.data))  // if I changed the value back inside the boundries, push that number back to Vera
                {
                  gw.send(msgTrippedVar2.set(rainSensorThreshold));
                }
              }
            }
          }
          
          void prettyFade(void)
          {
            float val = (exp(sin(millis() / 2000.0 * PI)) - 0.36787944) * 108.0;
            analogWrite(ledPin, val);
          }
          
          void slowFlash(void)
          {
            static boolean ledState = true;
            static unsigned long pulseStart = millis();
            if (millis() - pulseStart < 100UL)
            {
              digitalWrite(ledPin, !ledState);
              pulseStart = millis();
            }
          }
          
          void receiveTime(unsigned long time)
          {
            DEBUG_PRINTLN(F("Time received from controller..."));
            setTime(time);
            char theTime[26];
            sprintf(theTime, "The current time is %d:%2d", hour(), minute());
            DEBUG_PRINTLN(theTime);
          }
          
          RJ_MakeR Offline
          RJ_MakeR Offline
          RJ_Make
          Hero Member
          wrote on last edited by
          #81

          @BulldogLowell

          Wow, just wow man.... that is a thing of beauty!!

          RJ_Make

          BulldogLowellB 1 Reply Last reply
          0
          • RJ_MakeR RJ_Make

            @BulldogLowell

            Wow, just wow man.... that is a thing of beauty!!

            BulldogLowellB Offline
            BulldogLowellB Offline
            BulldogLowell
            Contest Winner
            wrote on last edited by
            #82

            @ServiceXp

            waiting for the 3D prints from China, I'll post when I get them!

            1 Reply Last reply
            1
            • marceltrapmanM Offline
              marceltrapmanM Offline
              marceltrapman
              Mod
              wrote on last edited by
              #83

              I would love to see the .stl files for this.
              It has turned into something really amazing imho.

              Fulltime Servoy Developer
              Parttime Moderator MySensors board

              I use Domoticz as controller for Z-Wave and MySensors (previously Indigo and OpenHAB).
              I have a FABtotum to print cases.

              1 Reply Last reply
              0
              • BulldogLowellB Offline
                BulldogLowellB Offline
                BulldogLowell
                Contest Winner
                wrote on last edited by BulldogLowell
                #84

                @marceltrapman said:

                I would love to see the .stl files for this.
                It has turned into something really amazing imho.

                I'll post, but I wanted to print and check first...

                @marceltrapman here you go...

                Posted to GoogleDrive

                1 Reply Last reply
                1
                • 5546dug5 Offline
                  5546dug5 Offline
                  5546dug
                  wrote on last edited by
                  #85

                  @BulldogLowell this has been quite a project to watch unfold and develop into just the greatest project. I am learning more just following you programing wizards, than I learn surfing . Thanks for the project and the inside tracks on programming etc.
                  I have got my tripping gage back from my local 3d hub shop and the job looks good I hope to have it running hardware and soft before I return to and take it to Florida this fall.

                  1 Reply Last reply
                  1
                  • hekH Offline
                    hekH Offline
                    hek
                    Admin
                    wrote on last edited by
                    #86

                    @BulldogLowell , @petewill

                    A page for your new creation has been deployed here:
                    http://www.mysensors.org/build/rain

                    Please let me know if I missed something or spelling needs to be corrected.

                    petewillP 1 Reply Last reply
                    1
                    • hekH hek

                      @BulldogLowell , @petewill

                      A page for your new creation has been deployed here:
                      http://www.mysensors.org/build/rain

                      Please let me know if I missed something or spelling needs to be corrected.

                      petewillP Offline
                      petewillP Offline
                      petewill
                      Admin
                      wrote on last edited by
                      #87

                      @hek Looks great! Thanks!

                      My "How To" home automation video channel: https://www.youtube.com/channel/UCq_Evyh5PQALx4m4CQuxqkA

                      blaceyB 1 Reply Last reply
                      0
                      • petewillP petewill

                        @hek Looks great! Thanks!

                        blaceyB Offline
                        blaceyB Offline
                        blacey
                        Admin
                        wrote on last edited by
                        #88

                        @petewill - another outstanding tutorial video.

                        petewillP 1 Reply Last reply
                        0
                        • blaceyB blacey

                          @petewill - another outstanding tutorial video.

                          petewillP Offline
                          petewillP Offline
                          petewill
                          Admin
                          wrote on last edited by
                          #89

                          @blacey Thanks! Couldn't have done it without @BulldogLowell and @hek

                          My "How To" home automation video channel: https://www.youtube.com/channel/UCq_Evyh5PQALx4m4CQuxqkA

                          1 Reply Last reply
                          0
                          • hekH Offline
                            hekH Offline
                            hek
                            Admin
                            wrote on last edited by hek
                            #90

                            @petewill, @BulldogLowell

                            Received my off the shelf tipping bucket sensor today. http://www.ebay.com/itm/331525977548?rmvSB=true

                            To my surprise it contained a dummy 2xAAA battery compartment. It might be possible to squeeze in a sensebender and nrf-radio (with some slight modification).

                            20150729_142145.jpg

                            coffeeaddictC 1 Reply Last reply
                            0
                            • petewillP Offline
                              petewillP Offline
                              petewill
                              Admin
                              wrote on last edited by
                              #91

                              @hek Cool! Looks like you may even have some room on the other side if you can figure out a way to waterproof it?

                              My "How To" home automation video channel: https://www.youtube.com/channel/UCq_Evyh5PQALx4m4CQuxqkA

                              1 Reply Last reply
                              0
                              • hekH hek

                                @petewill, @BulldogLowell

                                Received my off the shelf tipping bucket sensor today. http://www.ebay.com/itm/331525977548?rmvSB=true

                                To my surprise it contained a dummy 2xAAA battery compartment. It might be possible to squeeze in a sensebender and nrf-radio (with some slight modification).

                                20150729_142145.jpg

                                coffeeaddictC Offline
                                coffeeaddictC Offline
                                coffeeaddict
                                wrote on last edited by
                                #92

                                @hek said:

                                @petewill, @BulldogLowell

                                Received my off the shelf tipping bucket sensor today. http://www.ebay.com/itm/331525977548?rmvSB=true

                                To my surprise it contained a dummy 2xAAA battery compartment. It might be possible to squeeze in a sensebender and nrf-radio (with some slight modification).

                                @hek
                                Did you ever wire this up with sensebender & radio squeezed in?
                                I have this same guage I want to use with sensebender

                                1 Reply Last reply
                                0
                                • hekH Offline
                                  hekH Offline
                                  hek
                                  Admin
                                  wrote on last edited by
                                  #93

                                  No, never had time to finish my rain gauge this summer.

                                  But it should be doable. But the big pcb in there has to be modified, or even better is probably to move the reed switch directly to the sensebender.

                                  coffeeaddictC 1 Reply Last reply
                                  0
                                  • hekH hek

                                    No, never had time to finish my rain gauge this summer.

                                    But it should be doable. But the big pcb in there has to be modified, or even better is probably to move the reed switch directly to the sensebender.

                                    coffeeaddictC Offline
                                    coffeeaddictC Offline
                                    coffeeaddict
                                    wrote on last edited by
                                    #94

                                    @hek said:

                                    No, never had time to finish my rain gauge this summer.

                                    But it should be doable. But the big pcb in there has to be modified, or even better is probably to move the reed switch directly to the sensebender.

                                    ok thanks

                                    1 Reply Last reply
                                    0
                                    • mrc-coreM Offline
                                      mrc-coreM Offline
                                      mrc-core
                                      wrote on last edited by
                                      #95

                                      Hi.
                                      i'm having some trouble whit my rain gauge...

                                      My rain gauge is a Aercus KW9015, using the code provided i'm getting rain count every hour whit no rain at all.
                                      I don't know what to do to fix this.

                                      Over the rain gauge i have 4 connections.
                                      1 - GND
                                      2 - TX1 --- Temperature sensor
                                      3 - TX2 --- Rain sensor
                                      4 - VCC

                                      Why i'm i getting reads of rain ever 1h when there is no rain ?
                                      Can anyone help me whit this problem ?

                                      petewillP 1 Reply Last reply
                                      0
                                      • mrc-coreM mrc-core

                                        Hi.
                                        i'm having some trouble whit my rain gauge...

                                        My rain gauge is a Aercus KW9015, using the code provided i'm getting rain count every hour whit no rain at all.
                                        I don't know what to do to fix this.

                                        Over the rain gauge i have 4 connections.
                                        1 - GND
                                        2 - TX1 --- Temperature sensor
                                        3 - TX2 --- Rain sensor
                                        4 - VCC

                                        Why i'm i getting reads of rain ever 1h when there is no rain ?
                                        Can anyone help me whit this problem ?

                                        petewillP Offline
                                        petewillP Offline
                                        petewill
                                        Admin
                                        wrote on last edited by
                                        #96

                                        @mrc-core
                                        Are you actually getting a rain value or is it just sending 0? The code is designed to send an update to your gateway every hour with the total rain for the day whether there is rain or not.

                                        My "How To" home automation video channel: https://www.youtube.com/channel/UCq_Evyh5PQALx4m4CQuxqkA

                                        1 Reply Last reply
                                        0
                                        • mrc-coreM Offline
                                          mrc-coreM Offline
                                          mrc-core
                                          wrote on last edited by
                                          #97

                                          Some times i do get value 0 but other times i get rain value a big rain value for example values above 10mm of rain.
                                          The update is made every hour. Yesterday the rain value was 148mm when there was no rain at all. It doesn't rain for the last month.

                                          Ill try today reassembling the arduino, clear cd rom and flash again the rain gauge code.

                                          But i don't understand why i get this values.
                                          I even beleaved that the sensor was sendind data because off the wind... but it's not the problem.

                                          BulldogLowellB 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          17

                                          Online

                                          11.7k

                                          Users

                                          11.2k

                                          Topics

                                          113.1k

                                          Posts


                                          Copyright 2025 TBD   |   Forum Guidelines   |   Privacy Policy   |   Terms of Service
                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • MySensors
                                          • OpenHardware.io
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular