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. Announcements
  3. 💬 Water Meter Pulse Sensor

💬 Water Meter Pulse Sensor

Scheduled Pinned Locked Moved Announcements
109 Posts 37 Posters 31.1k Views 35 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.
  • V Offline
    V Offline
    vikram0228
    wrote on last edited by
    #11

    Water Meters with pulse output have two leads. They generate a simple pulse.

    The MySensors circuit also should also work with two leads - just need to know which two. The three leads are for water meters with no pulse output and where you need an optical sensor to sense the moving wheel.

    1 Reply Last reply
    0
    • DirtbagD Offline
      DirtbagD Offline
      Dirtbag
      wrote on last edited by
      #12

      Hi.
      Cant get my watersensor to send any values.
      I have debug enabled and it seems like it communicates fine with the gw but no flow data are beeing reported to the gw or the serial monitor.
      TSP:MSG:SEND 4-4-0-0 s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=ok:
      Anyone else experienced this problem?

      1 Reply Last reply
      0
      • bart59B Offline
        bart59B Offline
        bart59
        wrote on last edited by bart59
        #13

        I wanted to operate my water pulse meter on batteries and also get the water flow. The original design had the following issues with that:

        • Incorrect flow calc: micros() was used to calculate the flow, however micros() wraps every 70 minutes which looks like a huge flow (which is then discarded in code)
        • Volume calc: millis() wraps every 50 days which is not handled correctly either
        • Too much current for battery use: The IR LED of the TCRT5000 is always on and the LM393 comparator is also taking a few mA's
        • Could not report flow in sleep mode because millis() does not increment on sleep - need to do this based on calculation of total sleep time. We now simply calculate the number of pulses per minute and deduct the flow
        • I also had issued with the data transport reliability, so I added error counters (which show up on the Gateway as distance sensors)
        • I also wanted to provide a measurement counter to the gateway (that counts up each time a message is sent)
        • The sensor will reboot itself when too many errors occur

        So I modified the circuit of the IR sensor:

        • Assumption that the wheel of the water meter turns slowly (takes at least a few seconds to turn around)
        • We will wake up every 500 millisecond to turn on the IR LED connected to PIN 8. Pin 8 also powers the photo transistor that measures the reflection
        • I removed the power from the opamp circuit that is linked to the photo transistor
        • The voltage from the photo transistor is then read using an analog read on A1. Based on a threshold value we will deduct if the mirror on the water meter is in view
        • Pin 7 is connected to a learning switch which will turn the device in a specific mode and the min/max values on A1 are used to calculate the value of the threshold (which is then stored in the EEPROM)
        • After 30 seconds in learning mode, the new threshold is established and the LED on Pin 6 will show the actual on/off mirror signals, so you can see the pulses are correctly counted
        • switch back the DIP switch on Pin 7 to bring back normal mode
        • The circuit also contains the battery voltage sensor circuit (I am using a 1.5V battery and step up circuit). So the resistors used are 470k from + pole of battery to the A0 input and 1 M ohm from A0 to ground
        
        /**
        
         * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
         * Copyright (C) 2013-2015 Sensnology AB
         * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
         *
         * Documentation: http://www.mysensors.org
         * Support Forum: http://forum.mysensors.org
         *
         * This program is free software; you can redistribute it and/or
         * modify it under the terms of the GNU General Public License
         * version 2 as published by the Free Software Foundation.
         *
         *******************************
         *
         * REVISION HISTORY
         * Version 1.0 - Henrik Ekblad
         * Version 1.1 - GizMoCuz
         * Version 1.2 - changed BM: using low power separate circuit for infra red on pin 8 + analog A1
         * 
         * ISSUES WITH ORIGINAL CODE
         * Incorrect flow calc: micros() was used to calculate the flow, however micros() is wraps every 70 minutes which looks like a huge flow (which is discarded)
         * Volume calc: millis() wraps every 50 days which is not handled correctly
         * Too much current for battery use: The IR LED of the TCRT5000 is always on and the LM393 comparator is also taking a few mA's
         * Could not report flow in sleep mode because millis() does not increment on sleep - need to do this based on calculation of total sleep time
         * 
         * MODIFIED CIRCUIT IR SENSOR
         * Assumption that the wheel of the water meter turns slowly (takes at least a few seconds to turn around)
         * We will wake up every second to turn on the IR LED (connected to PIN 8). Pin 8 also powers the photo transistor that measures the reflection
         * The voltage from the photo transistor is then read using an analog read on A1. Based on a treshold value we will deduct if the mirror is in view
         * Pin 7 is connected to a learning switch which will turn the device in continous mode and the min/max values on A1 are used to recalc the treshold
         * during a 30 second period. After this period the new treshold is established and the LED on Pin 6 will show the actual on/off mirror signals
         *
         * http://www.mysensors.org/build/pulse_water
         */
        
        // BOARD: PRO MINI 3.3V/ 8Mhz ATMEGA328 8Mhz
        
        // Enable debug prints to serial monitor
        #define MY_DEBUG 
        
        // Enable and select radio type attached
        #define MY_RADIO_NRF24
        //#define MY_RADIO_RFM69
        
        #define MY_NODE_ID 10                 // hard code the node number
        #include <SPI.h>
        #include <MySensors.h>  
        
        #define SENSOR_POWER 8                // pin that will provide power to IR LED + sense circuit
        #define IR_SENSE_PIN  A1              // input for IR voltage
        #define BATTERY_SENSE_PIN  A0         // select the input pin for the battery sense point
        #define LEARN_SWITCH_PIN 7            // switch (SW1 on battery module) to turn on learning mode (low==on)
        #define LEARN_LED_PIN 6               // LED feedback during learning mode (LED on battery module)
        #define LEARN_TIME 30                 // number of seconds we will keep learn loop
        
        #define PULSE_FACTOR 1000             // Nummber of blinks per m3 of your meter (One rotation/1 liter)
        #define MAX_FLOW 80                   // Max flow (l/min) value to report. This filters outliers.
        #define CHILD_ID 1                    // Id of the sensor child (contains 3 subs: V_FLOW, V_VOLUME, VAR1)
        #define CHILD_PINGID 2                // ID of ping counter
        #define CHILD_ERRID 3                 // ID of error counter
        
        #define CHECK_FREQUENCY 500           // time in milliseconds between loop (where we check the sensor) - 500ms   
        #define MIN_SEND_FREQ 60              // Minimum time between send (in multiplies of CHECK_FREQUENCY). We don't want to spam the gateway (30 seconds)
        #define MAX_SEND_FREQ 1200            // Maximum time between send (in multiplies of CHECK_FREQUENCY). We need to show we are alive (600 sec/10 min)
        #define IR_ON_SETTLE 2                // number of milliseconds after we turned on the IR LED and we assume the receive signal is stable (in ms)
        #define EE_TRESHOLD 10                // config addresses 0 + 1 used for treshold from learning (loadState() returns only uint8 value)
        #define TRESHOLD_MARGIN 3             // additional margin before we actually see a one or zero
        #define RESETMIN 5                    // number of cycle times (either 30 sec of 10 min) we consistently need to have transmission errors before we perform hard reset
        
        MyMessage volumeMsg(CHILD_ID,V_VOLUME); // display volume and flow on the same CHILD_ID
        MyMessage flowMsg(CHILD_ID,V_FLOW); // flow
        MyMessage lastCounterMsg(CHILD_ID,V_VAR1);
        MyMessage pingMsg(CHILD_PINGID,V_DISTANCE); // use distance to keep track of changing value
        MyMessage errMsg(CHILD_ERRID,V_DISTANCE); // use distance to keep track of changing value
        
        
        double ppl = ((double)PULSE_FACTOR / 1000.0);    // Pulses per liter
        unsigned int oldBatteryPcnt = 0;          // check if changed
        unsigned int minsendcnt = MIN_SEND_FREQ;  // counter for keeping minimum intervals between sending
        unsigned int maxsendcnt = MAX_SEND_FREQ;  // counter for keeping maximum intervals between sending 
        unsigned int treshold = 512;              // threshold value when to swap on/off for pulse
        unsigned long pulseCount = 0;             // total volume of this pulse meter (value stored/received on gateway on pcReceived)
        unsigned long oldPulseCount = 0;          // to see if we have received something
        boolean pcReceived = false;               // received volume from prior reboot
        boolean onoff = false;                    // sensor value above/below treshold 
        unsigned int intervalcnt = 0;             // number of cycles between last period (for flow calculation)
        double flow = 0;                          // maintain flow
        double oldflow = 0;                       // keep prior flow (only send on change)
        unsigned int learntime=LEARN_TIME*2;      // timer for learning period
        unsigned int learnlow = 1023;             // lowest value found during learning
        unsigned int learnhigh = 0;               // highest value found during learning
        boolean learnsaved = false;               // have saved learned value
        unsigned long pingcnt = 0;
        unsigned long errcnt = 0;                 // error count
        unsigned int errcnt2 = 0;                 // error counter set to 0 when sending is ok
        
        void(* resetFunc) (void) = 0;//declare reset function at address 0 (for rebooting the Arduino)
        
        void setup() {    
          // make sure a few vars have the right init value after software reboot
          pingcnt = 0;
          pcReceived = false;
          pulseCount = oldPulseCount = 0;
          // setup hardware
          pinMode(SENSOR_POWER, OUTPUT); 
          digitalWrite(SENSOR_POWER, LOW);
          pinMode(LEARN_SWITCH_PIN, INPUT_PULLUP);
          pinMode(LEARN_LED_PIN, INPUT);      // default is input because this pin also has SW2 of battery block
        
          // Fetch last known pulse count value from gateway
          request(CHILD_ID, V_VAR1);
        
          // Fetch threshold value from EE prom
          treshold = readEeprom(EE_TRESHOLD);
          if (treshold<30 || treshold>1000) treshold = 512;   // wrong value in EEprom, take default
          Serial.print("Treshold: ");
          Serial.println(treshold);
                
          // use the 1.1 V internal reference for the battery and IR sensor
        #if defined(__AVR_ATmega2560__)
           analogReference(INTERNAL1V1);
        #else
           analogReference(INTERNAL);
        #endif
          analogRead(IR_SENSE_PIN); // settle analogreference value
          wait(CHECK_FREQUENCY); // wait a bit
        }
        
        void presentation()  {
          // Send the sketch version information to the gateway and Controller
          sendSketchInfo("Water Meter", "1.2");
        
          // Register this device as Waterflow sensor
          present(CHILD_ID, S_WATER);      
          present(CHILD_PINGID, S_DISTANCE); 
          present(CHILD_ERRID, S_DISTANCE);
        }
        
        void loop() {
          if (digitalRead(LEARN_SWITCH_PIN)==LOW) {
            pinMode(LEARN_LED_PIN, OUTPUT);
            digitalWrite(SENSOR_POWER, HIGH);
            intervalcnt = 0;
            learn_loop();
          } else {
            learntime=LEARN_TIME*2;
            learnlow = 1023;
            learnhigh = 0;
            pinMode(LEARN_LED_PIN, INPUT);
            normal_loop();
          }
        }
        
        void learn_loop() {
          // will run into this loop as long as we are learning
          wait(500);
          unsigned int sensorValue = analogRead(IR_SENSE_PIN);
          Serial.print("IR: ");
          Serial.print(sensorValue);
          if (learntime>0) {
            // still learning
            learntime--;
            learnsaved = false;    
            digitalWrite(LEARN_LED_PIN, !digitalRead(LEARN_LED_PIN));  // blink led
            if (sensorValue < learnlow) {
              learnlow = sensorValue;
              Serial.println(" Lowest");
            } else if (sensorValue > learnhigh) {
              learnhigh = sensorValue;
              Serial.println(" Highest");
            } else Serial.println();
          } else {
            if (!learnsaved) {
              treshold = (learnhigh + learnlow)/2;
              Serial.print("Treshold: ");
              Serial.println(treshold);
              storeEeprom(EE_TRESHOLD, treshold);
            }
            learnsaved = true;
            // just display using LED
            digitalWrite(LEARN_LED_PIN, sensorValue>treshold);
            Serial.println((sensorValue>treshold ? " on" : " off"));
          }
        }
        
        void normal_loop() { 
          unsigned long start_loop = millis();    // to allow adjusting wait time
          intervalcnt++;
          // we start doing a measurement
          digitalWrite(SENSOR_POWER, HIGH);
          wait(IR_ON_SETTLE); 
          unsigned int sensorValue = analogRead(IR_SENSE_PIN);
          digitalWrite(SENSOR_POWER, LOW); 
          #ifdef MY_DEBUG_DETAIL
          Serial.print("IR: ");
          Serial.println(sensorValue);
          #endif
          boolean nowvalue = onoff;
          if (onoff && (sensorValue<treshold-TRESHOLD_MARGIN)) nowvalue = false;
          if (!onoff && (sensorValue>treshold+TRESHOLD_MARGIN)) nowvalue = true;
          if (nowvalue != onoff) {
            // we have a pulse, only count on upwards pulse
            onoff = nowvalue;
            if (onoff) {
              pulseCount++;
              #ifdef MY_DEBUG
              Serial.print("p: ");
              Serial.println(pulseCount);
              #endif
            }
          }
        
        // Only send values at a maximum frequency or woken up from sleep
          if (minsendcnt>0) minsendcnt--;
          if (maxsendcnt>0) maxsendcnt--;
          // send minimum interval when we have pulse changes or if we had some flow the prior time or send on timeout
          if ((minsendcnt==0 && (pulseCount != oldPulseCount)) || (minsendcnt==0 && oldflow != 0) || maxsendcnt==0) {
            if (!pcReceived) {   //Last Pulsecount not yet received from controller, request it again
              Serial.print("Re-request var1 ..");
              request(CHILD_ID, V_VAR1);
        // Prevent flooding the gateway with re-requests,,, wait at least 1000 ms for gateway (cannot be sleep or smartSleep
              wait(2*CHECK_FREQUENCY); 
              return;
            }
            minsendcnt = MIN_SEND_FREQ;
            maxsendcnt = MAX_SEND_FREQ;
            pingcnt++;
        
            sensorValue = analogRead(BATTERY_SENSE_PIN);
            int batteryPcnt = sensorValue / 10;
            // 1M, 470K divider across battery and using internal ADC ref of 1.1V
            // Sense point is bypassed with 0.1 uF cap to reduce noise at that point
            // ((1e6+470e3)/1e6)*1.1 = Vmax = 1.67 Volts
            // 1.67/1023 = Volts per bit = 0.00158065
        
            Serial.print("Battery %: ");
            Serial.println(batteryPcnt);
        
            if (oldBatteryPcnt != batteryPcnt) {
              sendBatteryLevel(batteryPcnt);
              oldBatteryPcnt = batteryPcnt;
            }
            double volume = ((double)pulseCount/((double)PULSE_FACTOR));      
            flow = ((double) (pulseCount-oldPulseCount)) * (60000.0 / ((double) intervalcnt*(double) CHECK_FREQUENCY)) / ppl;  // flow in liter/min
        
            #ifdef MY_DEBUG
            Serial.print("pulsecount:");
            Serial.println(pulseCount);
            Serial.print("volume:");
            Serial.println(volume, 3);
            Serial.print("l/min:");
            Serial.println(flow);
            #endif
               
            bool b = send(lastCounterMsg.set(pulseCount));  // Send  pulsecount value to gw in VAR1
            if (b) errcnt2=0; else { errcnt++; errcnt2++; }
            b = send(volumeMsg.set(volume, 3));               // Send volume (set function 2nd argument is resolution)
            if (b) errcnt2=0; else { errcnt++; errcnt2++; }
            b = send(flowMsg.set(flow, 2));                   // Send flow value to gw
            if (b) errcnt2=0; else { errcnt++; errcnt2++; }
            b = send(pingMsg.set(pingcnt));                   // ensure at least this var has a different value
            if (b) errcnt2=0; else { errcnt++; errcnt2++; }
            b = send(errMsg.set(errcnt2+((float) errcnt2/100),2));    // ensure we always send error count
            if (b) errcnt2=0; else { errcnt++; errcnt2++; }
            oldPulseCount = pulseCount;
            intervalcnt = 0;
            oldflow = flow; 
            if (errcnt2>= (5*RESETMIN)) {
              Serial.println("Reset");
              wait(300);
              resetFunc(); //call reset to reboot the Arduino
            }
          }
        // calculate how long it took to process all of this. then go to sleep for the remaining period
          unsigned long end_loop = millis();
          if (end_loop - start_loop < CHECK_FREQUENCY)
            sleep(CHECK_FREQUENCY - (end_loop > start_loop ? end_loop - start_loop : 0));
        }
        
        void receive(const MyMessage &message) {
          if (message.type==V_VAR1) {
            unsigned long gwPulseCount=message.getULong();
            pulseCount += gwPulseCount;
            oldPulseCount += gwPulseCount;
            flow=oldflow=0;
            Serial.print("Received last pulse count from gw:");
            Serial.println(pulseCount);
            pcReceived = true;
          }
        }
        
        
        void storeEeprom(int pos, int value) {
            // function for saving the values to the internal EEPROM
            // value = the value to be stored (as int)
            // pos = the first byte position to store the value in
            // only two bytes can be stored with this function (max 32.767)
            saveState(pos, ((unsigned int)value >> 8 ));
            pos++;
            saveState(pos, (value & 0xff));
        }
        
        int readEeprom(int pos) {
            // function for reading the values from the internal EEPROM
            // pos = the first byte position to read the value from 
            int hiByte;
            int loByte;
            hiByte = loadState(pos) << 8;
            pos++;
            loByte = loadState(pos);
            return (hiByte | loByte);
        }
        
        mfalkviddM Emmanuel AbrahamE 2 Replies Last reply
        4
        • bart59B bart59

          I wanted to operate my water pulse meter on batteries and also get the water flow. The original design had the following issues with that:

          • Incorrect flow calc: micros() was used to calculate the flow, however micros() wraps every 70 minutes which looks like a huge flow (which is then discarded in code)
          • Volume calc: millis() wraps every 50 days which is not handled correctly either
          • Too much current for battery use: The IR LED of the TCRT5000 is always on and the LM393 comparator is also taking a few mA's
          • Could not report flow in sleep mode because millis() does not increment on sleep - need to do this based on calculation of total sleep time. We now simply calculate the number of pulses per minute and deduct the flow
          • I also had issued with the data transport reliability, so I added error counters (which show up on the Gateway as distance sensors)
          • I also wanted to provide a measurement counter to the gateway (that counts up each time a message is sent)
          • The sensor will reboot itself when too many errors occur

          So I modified the circuit of the IR sensor:

          • Assumption that the wheel of the water meter turns slowly (takes at least a few seconds to turn around)
          • We will wake up every 500 millisecond to turn on the IR LED connected to PIN 8. Pin 8 also powers the photo transistor that measures the reflection
          • I removed the power from the opamp circuit that is linked to the photo transistor
          • The voltage from the photo transistor is then read using an analog read on A1. Based on a threshold value we will deduct if the mirror on the water meter is in view
          • Pin 7 is connected to a learning switch which will turn the device in a specific mode and the min/max values on A1 are used to calculate the value of the threshold (which is then stored in the EEPROM)
          • After 30 seconds in learning mode, the new threshold is established and the LED on Pin 6 will show the actual on/off mirror signals, so you can see the pulses are correctly counted
          • switch back the DIP switch on Pin 7 to bring back normal mode
          • The circuit also contains the battery voltage sensor circuit (I am using a 1.5V battery and step up circuit). So the resistors used are 470k from + pole of battery to the A0 input and 1 M ohm from A0 to ground
          
          /**
          
           * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
           * Copyright (C) 2013-2015 Sensnology AB
           * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
           *
           * Documentation: http://www.mysensors.org
           * Support Forum: http://forum.mysensors.org
           *
           * This program is free software; you can redistribute it and/or
           * modify it under the terms of the GNU General Public License
           * version 2 as published by the Free Software Foundation.
           *
           *******************************
           *
           * REVISION HISTORY
           * Version 1.0 - Henrik Ekblad
           * Version 1.1 - GizMoCuz
           * Version 1.2 - changed BM: using low power separate circuit for infra red on pin 8 + analog A1
           * 
           * ISSUES WITH ORIGINAL CODE
           * Incorrect flow calc: micros() was used to calculate the flow, however micros() is wraps every 70 minutes which looks like a huge flow (which is discarded)
           * Volume calc: millis() wraps every 50 days which is not handled correctly
           * Too much current for battery use: The IR LED of the TCRT5000 is always on and the LM393 comparator is also taking a few mA's
           * Could not report flow in sleep mode because millis() does not increment on sleep - need to do this based on calculation of total sleep time
           * 
           * MODIFIED CIRCUIT IR SENSOR
           * Assumption that the wheel of the water meter turns slowly (takes at least a few seconds to turn around)
           * We will wake up every second to turn on the IR LED (connected to PIN 8). Pin 8 also powers the photo transistor that measures the reflection
           * The voltage from the photo transistor is then read using an analog read on A1. Based on a treshold value we will deduct if the mirror is in view
           * Pin 7 is connected to a learning switch which will turn the device in continous mode and the min/max values on A1 are used to recalc the treshold
           * during a 30 second period. After this period the new treshold is established and the LED on Pin 6 will show the actual on/off mirror signals
           *
           * http://www.mysensors.org/build/pulse_water
           */
          
          // BOARD: PRO MINI 3.3V/ 8Mhz ATMEGA328 8Mhz
          
          // Enable debug prints to serial monitor
          #define MY_DEBUG 
          
          // Enable and select radio type attached
          #define MY_RADIO_NRF24
          //#define MY_RADIO_RFM69
          
          #define MY_NODE_ID 10                 // hard code the node number
          #include <SPI.h>
          #include <MySensors.h>  
          
          #define SENSOR_POWER 8                // pin that will provide power to IR LED + sense circuit
          #define IR_SENSE_PIN  A1              // input for IR voltage
          #define BATTERY_SENSE_PIN  A0         // select the input pin for the battery sense point
          #define LEARN_SWITCH_PIN 7            // switch (SW1 on battery module) to turn on learning mode (low==on)
          #define LEARN_LED_PIN 6               // LED feedback during learning mode (LED on battery module)
          #define LEARN_TIME 30                 // number of seconds we will keep learn loop
          
          #define PULSE_FACTOR 1000             // Nummber of blinks per m3 of your meter (One rotation/1 liter)
          #define MAX_FLOW 80                   // Max flow (l/min) value to report. This filters outliers.
          #define CHILD_ID 1                    // Id of the sensor child (contains 3 subs: V_FLOW, V_VOLUME, VAR1)
          #define CHILD_PINGID 2                // ID of ping counter
          #define CHILD_ERRID 3                 // ID of error counter
          
          #define CHECK_FREQUENCY 500           // time in milliseconds between loop (where we check the sensor) - 500ms   
          #define MIN_SEND_FREQ 60              // Minimum time between send (in multiplies of CHECK_FREQUENCY). We don't want to spam the gateway (30 seconds)
          #define MAX_SEND_FREQ 1200            // Maximum time between send (in multiplies of CHECK_FREQUENCY). We need to show we are alive (600 sec/10 min)
          #define IR_ON_SETTLE 2                // number of milliseconds after we turned on the IR LED and we assume the receive signal is stable (in ms)
          #define EE_TRESHOLD 10                // config addresses 0 + 1 used for treshold from learning (loadState() returns only uint8 value)
          #define TRESHOLD_MARGIN 3             // additional margin before we actually see a one or zero
          #define RESETMIN 5                    // number of cycle times (either 30 sec of 10 min) we consistently need to have transmission errors before we perform hard reset
          
          MyMessage volumeMsg(CHILD_ID,V_VOLUME); // display volume and flow on the same CHILD_ID
          MyMessage flowMsg(CHILD_ID,V_FLOW); // flow
          MyMessage lastCounterMsg(CHILD_ID,V_VAR1);
          MyMessage pingMsg(CHILD_PINGID,V_DISTANCE); // use distance to keep track of changing value
          MyMessage errMsg(CHILD_ERRID,V_DISTANCE); // use distance to keep track of changing value
          
          
          double ppl = ((double)PULSE_FACTOR / 1000.0);    // Pulses per liter
          unsigned int oldBatteryPcnt = 0;          // check if changed
          unsigned int minsendcnt = MIN_SEND_FREQ;  // counter for keeping minimum intervals between sending
          unsigned int maxsendcnt = MAX_SEND_FREQ;  // counter for keeping maximum intervals between sending 
          unsigned int treshold = 512;              // threshold value when to swap on/off for pulse
          unsigned long pulseCount = 0;             // total volume of this pulse meter (value stored/received on gateway on pcReceived)
          unsigned long oldPulseCount = 0;          // to see if we have received something
          boolean pcReceived = false;               // received volume from prior reboot
          boolean onoff = false;                    // sensor value above/below treshold 
          unsigned int intervalcnt = 0;             // number of cycles between last period (for flow calculation)
          double flow = 0;                          // maintain flow
          double oldflow = 0;                       // keep prior flow (only send on change)
          unsigned int learntime=LEARN_TIME*2;      // timer for learning period
          unsigned int learnlow = 1023;             // lowest value found during learning
          unsigned int learnhigh = 0;               // highest value found during learning
          boolean learnsaved = false;               // have saved learned value
          unsigned long pingcnt = 0;
          unsigned long errcnt = 0;                 // error count
          unsigned int errcnt2 = 0;                 // error counter set to 0 when sending is ok
          
          void(* resetFunc) (void) = 0;//declare reset function at address 0 (for rebooting the Arduino)
          
          void setup() {    
            // make sure a few vars have the right init value after software reboot
            pingcnt = 0;
            pcReceived = false;
            pulseCount = oldPulseCount = 0;
            // setup hardware
            pinMode(SENSOR_POWER, OUTPUT); 
            digitalWrite(SENSOR_POWER, LOW);
            pinMode(LEARN_SWITCH_PIN, INPUT_PULLUP);
            pinMode(LEARN_LED_PIN, INPUT);      // default is input because this pin also has SW2 of battery block
          
            // Fetch last known pulse count value from gateway
            request(CHILD_ID, V_VAR1);
          
            // Fetch threshold value from EE prom
            treshold = readEeprom(EE_TRESHOLD);
            if (treshold<30 || treshold>1000) treshold = 512;   // wrong value in EEprom, take default
            Serial.print("Treshold: ");
            Serial.println(treshold);
                  
            // use the 1.1 V internal reference for the battery and IR sensor
          #if defined(__AVR_ATmega2560__)
             analogReference(INTERNAL1V1);
          #else
             analogReference(INTERNAL);
          #endif
            analogRead(IR_SENSE_PIN); // settle analogreference value
            wait(CHECK_FREQUENCY); // wait a bit
          }
          
          void presentation()  {
            // Send the sketch version information to the gateway and Controller
            sendSketchInfo("Water Meter", "1.2");
          
            // Register this device as Waterflow sensor
            present(CHILD_ID, S_WATER);      
            present(CHILD_PINGID, S_DISTANCE); 
            present(CHILD_ERRID, S_DISTANCE);
          }
          
          void loop() {
            if (digitalRead(LEARN_SWITCH_PIN)==LOW) {
              pinMode(LEARN_LED_PIN, OUTPUT);
              digitalWrite(SENSOR_POWER, HIGH);
              intervalcnt = 0;
              learn_loop();
            } else {
              learntime=LEARN_TIME*2;
              learnlow = 1023;
              learnhigh = 0;
              pinMode(LEARN_LED_PIN, INPUT);
              normal_loop();
            }
          }
          
          void learn_loop() {
            // will run into this loop as long as we are learning
            wait(500);
            unsigned int sensorValue = analogRead(IR_SENSE_PIN);
            Serial.print("IR: ");
            Serial.print(sensorValue);
            if (learntime>0) {
              // still learning
              learntime--;
              learnsaved = false;    
              digitalWrite(LEARN_LED_PIN, !digitalRead(LEARN_LED_PIN));  // blink led
              if (sensorValue < learnlow) {
                learnlow = sensorValue;
                Serial.println(" Lowest");
              } else if (sensorValue > learnhigh) {
                learnhigh = sensorValue;
                Serial.println(" Highest");
              } else Serial.println();
            } else {
              if (!learnsaved) {
                treshold = (learnhigh + learnlow)/2;
                Serial.print("Treshold: ");
                Serial.println(treshold);
                storeEeprom(EE_TRESHOLD, treshold);
              }
              learnsaved = true;
              // just display using LED
              digitalWrite(LEARN_LED_PIN, sensorValue>treshold);
              Serial.println((sensorValue>treshold ? " on" : " off"));
            }
          }
          
          void normal_loop() { 
            unsigned long start_loop = millis();    // to allow adjusting wait time
            intervalcnt++;
            // we start doing a measurement
            digitalWrite(SENSOR_POWER, HIGH);
            wait(IR_ON_SETTLE); 
            unsigned int sensorValue = analogRead(IR_SENSE_PIN);
            digitalWrite(SENSOR_POWER, LOW); 
            #ifdef MY_DEBUG_DETAIL
            Serial.print("IR: ");
            Serial.println(sensorValue);
            #endif
            boolean nowvalue = onoff;
            if (onoff && (sensorValue<treshold-TRESHOLD_MARGIN)) nowvalue = false;
            if (!onoff && (sensorValue>treshold+TRESHOLD_MARGIN)) nowvalue = true;
            if (nowvalue != onoff) {
              // we have a pulse, only count on upwards pulse
              onoff = nowvalue;
              if (onoff) {
                pulseCount++;
                #ifdef MY_DEBUG
                Serial.print("p: ");
                Serial.println(pulseCount);
                #endif
              }
            }
          
          // Only send values at a maximum frequency or woken up from sleep
            if (minsendcnt>0) minsendcnt--;
            if (maxsendcnt>0) maxsendcnt--;
            // send minimum interval when we have pulse changes or if we had some flow the prior time or send on timeout
            if ((minsendcnt==0 && (pulseCount != oldPulseCount)) || (minsendcnt==0 && oldflow != 0) || maxsendcnt==0) {
              if (!pcReceived) {   //Last Pulsecount not yet received from controller, request it again
                Serial.print("Re-request var1 ..");
                request(CHILD_ID, V_VAR1);
          // Prevent flooding the gateway with re-requests,,, wait at least 1000 ms for gateway (cannot be sleep or smartSleep
                wait(2*CHECK_FREQUENCY); 
                return;
              }
              minsendcnt = MIN_SEND_FREQ;
              maxsendcnt = MAX_SEND_FREQ;
              pingcnt++;
          
              sensorValue = analogRead(BATTERY_SENSE_PIN);
              int batteryPcnt = sensorValue / 10;
              // 1M, 470K divider across battery and using internal ADC ref of 1.1V
              // Sense point is bypassed with 0.1 uF cap to reduce noise at that point
              // ((1e6+470e3)/1e6)*1.1 = Vmax = 1.67 Volts
              // 1.67/1023 = Volts per bit = 0.00158065
          
              Serial.print("Battery %: ");
              Serial.println(batteryPcnt);
          
              if (oldBatteryPcnt != batteryPcnt) {
                sendBatteryLevel(batteryPcnt);
                oldBatteryPcnt = batteryPcnt;
              }
              double volume = ((double)pulseCount/((double)PULSE_FACTOR));      
              flow = ((double) (pulseCount-oldPulseCount)) * (60000.0 / ((double) intervalcnt*(double) CHECK_FREQUENCY)) / ppl;  // flow in liter/min
          
              #ifdef MY_DEBUG
              Serial.print("pulsecount:");
              Serial.println(pulseCount);
              Serial.print("volume:");
              Serial.println(volume, 3);
              Serial.print("l/min:");
              Serial.println(flow);
              #endif
                 
              bool b = send(lastCounterMsg.set(pulseCount));  // Send  pulsecount value to gw in VAR1
              if (b) errcnt2=0; else { errcnt++; errcnt2++; }
              b = send(volumeMsg.set(volume, 3));               // Send volume (set function 2nd argument is resolution)
              if (b) errcnt2=0; else { errcnt++; errcnt2++; }
              b = send(flowMsg.set(flow, 2));                   // Send flow value to gw
              if (b) errcnt2=0; else { errcnt++; errcnt2++; }
              b = send(pingMsg.set(pingcnt));                   // ensure at least this var has a different value
              if (b) errcnt2=0; else { errcnt++; errcnt2++; }
              b = send(errMsg.set(errcnt2+((float) errcnt2/100),2));    // ensure we always send error count
              if (b) errcnt2=0; else { errcnt++; errcnt2++; }
              oldPulseCount = pulseCount;
              intervalcnt = 0;
              oldflow = flow; 
              if (errcnt2>= (5*RESETMIN)) {
                Serial.println("Reset");
                wait(300);
                resetFunc(); //call reset to reboot the Arduino
              }
            }
          // calculate how long it took to process all of this. then go to sleep for the remaining period
            unsigned long end_loop = millis();
            if (end_loop - start_loop < CHECK_FREQUENCY)
              sleep(CHECK_FREQUENCY - (end_loop > start_loop ? end_loop - start_loop : 0));
          }
          
          void receive(const MyMessage &message) {
            if (message.type==V_VAR1) {
              unsigned long gwPulseCount=message.getULong();
              pulseCount += gwPulseCount;
              oldPulseCount += gwPulseCount;
              flow=oldflow=0;
              Serial.print("Received last pulse count from gw:");
              Serial.println(pulseCount);
              pcReceived = true;
            }
          }
          
          
          void storeEeprom(int pos, int value) {
              // function for saving the values to the internal EEPROM
              // value = the value to be stored (as int)
              // pos = the first byte position to store the value in
              // only two bytes can be stored with this function (max 32.767)
              saveState(pos, ((unsigned int)value >> 8 ));
              pos++;
              saveState(pos, (value & 0xff));
          }
          
          int readEeprom(int pos) {
              // function for reading the values from the internal EEPROM
              // pos = the first byte position to read the value from 
              int hiByte;
              int loByte;
              hiByte = loadState(pos) << 8;
              pos++;
              loByte = loadState(pos);
              return (hiByte | loByte);
          }
          
          mfalkviddM Offline
          mfalkviddM Offline
          mfalkvidd
          Mod
          wrote on last edited by
          #14

          Great work @bart59 !
          Do you have any indication on how long battery life you will get with this setup?

          bart59B S 2 Replies Last reply
          0
          • mfalkviddM mfalkvidd

            Great work @bart59 !
            Do you have any indication on how long battery life you will get with this setup?

            bart59B Offline
            bart59B Offline
            bart59
            wrote on last edited by
            #15

            @mfalkvidd - I did measure the average current consumption at the time, but I not remember the exact value. I believe it was well below the 0.5 mA. The sensor has been up and running on the same single 1.5V AA battery for 30 days now and the batt percentage still shows 93%.

            1 Reply Last reply
            1
            • dpcrD Offline
              dpcrD Offline
              dpcr
              wrote on last edited by
              #16

              I hope this is not off topic but I'm trying to read our gas meter - but....I cannot use a photo sensor or a hall sensor or a reed switch (the meter is outside and there is no magnet in it). I was able to get some good data using a magnetometer (https://www.sparkfun.com/tutorials/301) using an arduino. But I tink from what I am told is the arduino isn't big enough to handle the code I need to use to change the data (x axis, y axis, z axis) into a pulse but will work on a pi.

              My question is am I missing something (hardware guy, not software)? Can I use a Pi for a sensor (it has the inputs and room), all the code on this site is for arduinos. Could I have the Pi output a pulse to an arduino? Am I over thinking this?

              bart59B 1 Reply Last reply
              0
              • dpcrD dpcr

                I hope this is not off topic but I'm trying to read our gas meter - but....I cannot use a photo sensor or a hall sensor or a reed switch (the meter is outside and there is no magnet in it). I was able to get some good data using a magnetometer (https://www.sparkfun.com/tutorials/301) using an arduino. But I tink from what I am told is the arduino isn't big enough to handle the code I need to use to change the data (x axis, y axis, z axis) into a pulse but will work on a pi.

                My question is am I missing something (hardware guy, not software)? Can I use a Pi for a sensor (it has the inputs and room), all the code on this site is for arduinos. Could I have the Pi output a pulse to an arduino? Am I over thinking this?

                bart59B Offline
                bart59B Offline
                bart59
                wrote on last edited by
                #17

                @dpcreel. I would be surprised the Arduino could not handle the HMC5883L magnetometer from Sparkfun. The I2C protocol is natively supported and you only need to analyse numbers coming from the 3-Axis to decide when the wheels inside the gas meter turn. I think the position of the sensor will be very critical, but the code should not be too complex. Arduino's are typically limited in handling much data (there is only 2000 bytes of RAM in the ATmega328), but your code should not need much RAM space. The program size can be 32 KB which should be enough.

                If you want to go for the PI, there are I2C libraries out there you could use and I would then bypass the Mysensors gateway alltogether and connect an ethernet cable to the PI and use the MQTT protocol to talk to your home controller.

                regards
                Bart

                dpcrD 1 Reply Last reply
                1
                • bart59B bart59

                  @dpcreel. I would be surprised the Arduino could not handle the HMC5883L magnetometer from Sparkfun. The I2C protocol is natively supported and you only need to analyse numbers coming from the 3-Axis to decide when the wheels inside the gas meter turn. I think the position of the sensor will be very critical, but the code should not be too complex. Arduino's are typically limited in handling much data (there is only 2000 bytes of RAM in the ATmega328), but your code should not need much RAM space. The program size can be 32 KB which should be enough.

                  If you want to go for the PI, there are I2C libraries out there you could use and I would then bypass the Mysensors gateway alltogether and connect an ethernet cable to the PI and use the MQTT protocol to talk to your home controller.

                  regards
                  Bart

                  dpcrD Offline
                  dpcrD Offline
                  dpcr
                  wrote on last edited by
                  #18

                  @bart59 The Arduino works fine with the HMC5883L, I got some good data from it and was able to "see" the gas meter movements very well. I am not able to write code (hardware guy) to change this data to a pulse for MySensors or whatever it needs. I just want to be able to read my gas meter with the HMC5883L. I did find some code in python that works on the pi, that's why I mentioned it. I'm a hack at software.

                  1 Reply Last reply
                  0
                  • A Offline
                    A Offline
                    aram
                    wrote on last edited by
                    #19

                    Hi
                    I am trying to use the subject code with pulse water meters and hope someone can help to figure out what needs to be adjusted to get more accurate data.

                    My setup:
                    Gateway ESP8266 (NodeMCU) + NRF24 -> Connected to Domoticz
                    Sensor node: Arduino Uno + NRF24
                    Default codes from Build. Test sensors so far work great.

                    Task:
                    Need to connect Siemens WFK2 water meters (four of them actually) with pulse outputs (2 line). According to data sheet (link text) there are two types: reed output or NAMUR.

                    To start with, I connected the reed output of the water meter via 10k resistor to +5V, GND and D3. Again, according to data sheet, for every 10l the water meter should give an impulse (e.g. connect the switch). Taking this into account I have adjusted pulse factor to 100 and based on Nominal Flow Rate (Max Flow Rate impossible in my case) limited Max Flow to 25 l/min. This setup works, but I definitely get wrong flow values (e.g. with constant flow of 6l/min serial monitor and domoticz report anything between 12-15l/min) and also wrong water usage m3 and litre usage in Domoticz.

                    When trying to debug, found out following behaviour (must be connected to Pulse length an Qn from data sheet IMHO):
                    with each turn it indeed switches on, e.g. shortens the contacts which generates pulse for the sensor, however it takes up to 2-4 litres until switch is in the off state.

                    As a result you might have a situation when meter switches on, one closes the tap, and the signal is on for minutes/hours until tap is again opened and 2-4 litres have been used, after which signal will switch off.

                    Do I understand correctly that the debouncer which should take care of similar situations is not ready for this?

                    thanks in advance for support

                    1 Reply Last reply
                    0
                    • bart59B Offline
                      bart59B Offline
                      bart59
                      wrote on last edited by
                      #20

                      Hi Aram

                      The original code from the mysensors site does not handle your situation very well (indeed because the switch staying on or off for a long time). You can use my code (see my post further up this discussion). In my case I have a pulse every 1 liter.

                      In your case you only have 1 pulse every 10 liters, which means you have to take a much longer period to calculate the flow correctly. Basically you have to set MIN_SEND_FREQ to a higher value. The flow is calculated based on the number of pulses in a given time period. Example: with 6 l/min you have to calculate this value only once every 5 minutes (=30 liter = 3 pulses from your Siemens meter) instead of every 30 seconds as I do. So if MIN_SEND_FREQ = 600 (every 5 minutes) your flow is calculated as:

                      flow = ((double) (pulseCount-oldPulseCount)) * (60000.0 / ((double) intervalcnt*(double) CHECK_FREQUENCY)) / ppl;

                      In the example above (pulseCount-oldPulseCount) = 3 pulses
                      ppl = 0.1
                      intervalcnt = MIN_SEND_FREQ = 600
                      CHECK_FREQUENCY = 500
                      ==> flow is 6 l/min

                      regards

                      Bart

                      1 Reply Last reply
                      1
                      • A Offline
                        A Offline
                        aram
                        wrote on last edited by
                        #21

                        bart59,

                        thanks for quick reply. I will try to adjust MIN_SEND_FREQ and use your code.
                        however, if I understand correctly, with the current logic used its impossible to avoid misinterpretations of pulses in case of very very long on or off state. It will approximate the flow rate to more correct value during usage of water (this is good enough) and should report total usage somehow correctly (this one I would better get as precise as possible). I wonder if the code will capture the correct number of pulses in the case of very long on state.

                        BTW, I was not able to find a readily available sketch to connect NAMUR output, which is basically 5kOhm off state and 1.5795 kOhm on state. I believe, I will have to calculate required pull up resistance to get a proper voltage divider for 5\3.3v, right?

                        1 Reply Last reply
                        0
                        • bart59B Offline
                          bart59B Offline
                          bart59
                          wrote on last edited by
                          #22

                          My code basically measures the time between two upward pulses. You can modify the code to also count the downward pulses. The net effect is that you will get a count every 5 liter (on average), but if there is no flow, the first pulse will always be off by 1-4 liter because you do not know how far the rotation is completed.

                          On NAMUR: you can actually use my code here too: I use analog input A1 to measure the voltage on the infra red sensor (which varies between 0 and 1.1 Volt). During the learn mode (set with a seaprate DIP switch) the code measures the input voltage for a period of 30 seconds while you turn open the water tap (you may want to increase the timing in your case) and then calculates the average between the lowest and highest voltage as the currect point there is a 1 or 0 coming from the pump (in my case it is an IR LED that is reflecting from a mirror into a photo sensor and the position of the mirror may change - resulting in different voltages).

                          regards
                          Bart

                          1 Reply Last reply
                          0
                          • Curtis DobrowolskiC Offline
                            Curtis DobrowolskiC Offline
                            Curtis Dobrowolski
                            wrote on last edited by
                            #23

                            Would anyone be able to help me get the hall sensor to work to work directly connected to an ESP8266 MQTT gateway? I was able to created the MQTT gateway, appended this sketch to the MQTT gateway sketch and connect the hall sensor DO to D12 (D3 is occupied), but when I subscribe to my mosquitto server no values are published. I am able to see the prefixes and they get published every 20 seconds as expected, but there are no sensor values. I plan on using this with home assistant, incase that helps with the final setup. If anyone has any recommendations it would be greatly appreciated.

                            1 Reply Last reply
                            0
                            • J Offline
                              J Offline
                              jagadesh waran
                              wrote on last edited by
                              #24

                              Can you please roughly say

                              1. what is the current consumption overall
                              2. what is the current consumption when measuring a pulse
                              3. what is the current consumed when the data is transmitted
                              mfalkviddM 1 Reply Last reply
                              0
                              • J jagadesh waran

                                Can you please roughly say

                                1. what is the current consumption overall
                                2. what is the current consumption when measuring a pulse
                                3. what is the current consumed when the data is transmitted
                                mfalkviddM Offline
                                mfalkviddM Offline
                                mfalkvidd
                                Mod
                                wrote on last edited by mfalkvidd
                                #25

                                @jagadesh-waran welcome to the MySensors community.

                                The current consumption depends on which Arduino you are using and which radio you are using.

                                Could you describe what your goal is?

                                Maybe the page on battery power can be useful.

                                J 1 Reply Last reply
                                0
                                • mfalkviddM mfalkvidd

                                  @jagadesh-waran welcome to the MySensors community.

                                  The current consumption depends on which Arduino you are using and which radio you are using.

                                  Could you describe what your goal is?

                                  Maybe the page on battery power can be useful.

                                  J Offline
                                  J Offline
                                  jagadesh waran
                                  wrote on last edited by
                                  #26

                                  @mfalkvidd im using mini at 8mhz with a 3V battery, No LDO and an ESP8266

                                  I want to calculate the battery life say im using 3V 19000mah battery and if im consuming 100 gallons per day

                                  Could you please update me the life of the battery?

                                  Could you please update me the current consumptions at various intervals?

                                  mfalkviddM 1 Reply Last reply
                                  0
                                  • J jagadesh waran

                                    @mfalkvidd im using mini at 8mhz with a 3V battery, No LDO and an ESP8266

                                    I want to calculate the battery life say im using 3V 19000mah battery and if im consuming 100 gallons per day

                                    Could you please update me the life of the battery?

                                    Could you please update me the current consumptions at various intervals?

                                    mfalkviddM Offline
                                    mfalkviddM Offline
                                    mfalkvidd
                                    Mod
                                    wrote on last edited by
                                    #27

                                    @jagadesh-waran The easiest ways is to either measure the consumption on your devices, or look at the datasheets.

                                    1 Reply Last reply
                                    0
                                    • W Offline
                                      W Offline
                                      webzter30
                                      wrote on last edited by
                                      #28

                                      I am trying this node. I have it set up. but I am having the same problem as Dirtbag. I am not getting any values. I debugged and I am getting 1 and 0 for my sensor output, so my sensor is working when I trigger it with a magnet.
                                      Does this work with MQTT gateway?? am I missing something. Communication is fine between by ESP gateway and my node.?
                                      Thanks ahead of time for any help with this.

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

                                        Hi. i'm having a strange problem using a arduino nano connecting a hall sensor to read my water meter. My water meter is dated from 1996 and i can't use the TCRT5000 sensor so i'm trying my luck with the hall sensor. My problem is that my arduino is always sending data.... even if i have the water turned off the most strange thing is that even when the arduino is not connected to the hall sensor it send's data. How can i fix this problem ?

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

                                          Hi. i'm having a strange problem using a arduino nano connecting a hall sensor to read my water meter. My water meter is dated from 1996 and i can't use the TCRT5000 sensor so i'm trying my luck with the hall sensor. My problem is that my arduino is always sending data.... even if i have the water turned off the most strange thing is that even when the arduino is not connected to the hall sensor it send's data. How can i fix this problem ?

                                          mfalkviddM Offline
                                          mfalkviddM Offline
                                          mfalkvidd
                                          Mod
                                          wrote on last edited by
                                          #30

                                          @mrc-core did you read this part of the instructions?

                                          You can also set the frequency that the sensor will report the water consumption by updating the SEND_FREQUENCY. The default frequency 3 times per minute (every 20 seconds).

                                          mrc-coreM 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          23

                                          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