💬 Power Meter Pulse Sensor


  • Admin

    This thread contains comments for the article "Power Meter Pulse Sensor" posted on MySensors.org.



  • Hey guys, I have a strange problem using excact this scetch and the new 2.0 serial gateway scetch using FHEM.
    I do get KWH values, but no Power values, and sometimes all of a sudden it gives me a power value, like twice a day.
    It didn't do that before and I am a complete copy-pase N00B, so maybe somebody already sovled this issue? HELP



  • Fhem tells me this all the time:
    MYSENSORS: ignoring presentation-msg from unknown radioId 0, childId 255, sensorType 18


  • Admin

    There is another thread with exactly this problem here:

    https://forum.mysensors.org/topic/4845/send-fake-data-to-fhem-without-transmitter/9

    I guess you also have the sensor connected directly to the gateway? You should probably seek some more info in the FHEM community.



  • I built this node but it doesn't seem to work. It shows up in the hardware list of my controller (Domoticz latest stable) as S_Power but no values appear like I was expecting V_WATT, V_KWH etc. Nothing appears under the devices section. Does the sketch need modifying for 2.0 or is it a Domoticz issue? Anybody else got one of these working?


  • Mod

    @mikeS has the sensor sent any values? Domotics does not show anything until the first value has been sent.
    Could you post the log from the sensor and the gateway?



  • Sorry please disregard, I got it working, the pot just needed trimming down, it was permanently triggered so not reading pulses. It worked straight away as soon as I did that. I thought the green light on the lm393 was a power indicator as it was always on, not pulsing.


  • Mod

    @mikeS great work, thanks for reporting back



  • Like all the nodes and the project in general, it's amazing, but in the space of 24hrs I have turned into a "turn everything off" sort of a guy. I cringed when I suddenly had a log of how much money I was wasting! One thing that's weird is that Domoticz shows 2 devices; usage and meter, the usage one doesn't update at all, but the meter one displays everything you need anyway. It's a bit like the DHT node, in that they show as 3 devices TempHum combined which update nicely; and 2x LacrosseTX which update randomly.



  • I do not understand. My boiler is 3KW. https://1drv.ms/i/s!AtuQgBKT8NIPhi4F_I3mPVYW0S9P



  • @Fat-Fly
    I think something is wrong in your code.

    Is the pulse setup correct?



  • Can someone please explain how the sleep mode works?

    My sensor works like a charm when sleep mode is "false" but when changing to "true" i get nothing to the GW

    Exactly the same setup, the only thing I changed is from "false" to "true"



  • @miljume
    Use sleep mode if you have battery for the node.

    Maybe it need lots of Kwh before sending new data. If you don't use sleep mode it will send watt more often.



  • @flopp Yes, that was my intention

    But I wonder how often the sensor send data to the gateway in that mode i.e. how the mechanism works

    I might not have waited long enough but it would be good to know what "long enough" is



  • it need to change 0,02 kWh before sending new value

    see more information here
    https://forum.mysensors.org/topic/4727/energy-meter-not-sending-at-expected



  • This post is deleted!


  • @flopp Thanks for the link but I still cant get anything in sleep mode

    Now I have waited for over an hour with simulated blinks approx twice/second but so far the device havent reported one single time!

    By the way, does anyone know how to reset the value stored in the GW?

    After some testing the value get's quite high 😃



  • Hi. I built this sensor and loaded the example. It appears the sensor registers with my serial gateway and appears in domoticz. The problem is it hasn't updated the value in 24h? Any ideas?
    Thanks



  • @asgardro
    What does the serial output in arduino says?



  • In the end it displays the watt value and then just hangs. I haven't modified the example at all. I am @ work now but will be able to check again later



  • Came back from work and checked. it is sending to the gateway the first value and gets displayed in domoticz. then dead.. it appears it does not get the pulse count from the gateway respectively from domoticz. has anyone got this working with domoticz?



  • @asgardro
    I am using two of these to DZ.
    One has been working perfect for 1,5 month the second I had some problem with initialize after 3 weeks.



  • would you mind please sharing the sketch? i don't know whats wrong. i even forced it with "bool pcReceived = false" puting it to true. thanks



  • i do not get Serial.print("Received last pulse count from gw:"); in serial output



  • @asgardro
    this is my sketch
    i use MS 1.5.1

    /**
     * The MySensors Arduino library handles the wireless radio link and protocol
     * between your home built sensors/actuators and HA controller of choice.
     * The sensors forms a self healing radio network with optional repeaters. Each
     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
     * network topology allowing messages to be routed to nodes.
     *
     * 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
     * 
     * DESCRIPTION
     * This sketch provides an example how to implement a distance sensor using HC-SR04 
     * Use this sensor to measure KWH and Watt of your house meeter
     * You need to set the correct pulsefactor of your meeter (blinks per KWH).
     * The sensor starts by fetching current KWH value from gateway.
     * Reports both KWH and Watt back to gateway.
     *
     * Unfortunately millis() won't increment when the Arduino is in 
     * sleepmode. So we cannot make this sensor sleep if we also want 
     * to calculate/report watt-number.
     * http://www.mysensors.org/build/pulse_power
     */
    
    #include <SPI.h>
    #include <MySensor.h>  
    
    #define DIGITAL_INPUT_SENSOR 3  // The digital input you attached your light sensor.  (Only 2 and 3 generates interrupt!)
    #define PULSE_FACTOR 1000       // Number of blinks per KWH of your meeter
    #define SLEEP_MODE false        // Watt-value can only be reported when sleep mode is false.
    #define MAX_WATT 15000          // Max watt value to report. This filters outliers.
    #define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
    #define CHILD_ID 1              // Id of the sensor child
    unsigned long SEND_FREQUENCY = 5*60000; // Minimum time between send (in milliseconds). We don't want to spam the gateway.
    MySensor gw;
    double ppwh = ((double)PULSE_FACTOR)/1000; // Pulses per watt hour
    boolean pcReceived = false;
    volatile unsigned long pulseCount = 0;   
    volatile unsigned long lastBlink = 0;
    volatile unsigned long watt = 0;
    unsigned long oldPulseCount = 0;   
    unsigned long oldWatt = 0;
    //double oldKwh;
    unsigned long lastSend;
    MyMessage wattMsg(CHILD_ID,V_WATT);
    MyMessage kwhMsg(CHILD_ID,V_KWH);
    MyMessage pcMsg(CHILD_ID,V_VAR1);
    
    
    void setup()  
    {  
      gw.begin(incomingMessage);
    
      // Send the sketch version information to the gateway and Controller
      gw.sendSketchInfo("Energy Huset", "1.1");
    //1.1 no check for old value, always send
      // Register this device as power sensor
      gw.present(CHILD_ID, S_POWER);
    
      // Fetch last known pulse count value from gw
      gw.request(CHILD_ID, V_VAR1);
      
      attachInterrupt(INTERRUPT, onPulse, RISING);
      lastSend=millis();
    }
    
    
    void loop()     
    { 
      gw.process();
      unsigned long now = millis();
      // Only send values at a maximum frequency or woken up from sleep
      bool sendTime = now - lastSend > SEND_FREQUENCY;
      if (pcReceived && (SLEEP_MODE || sendTime)) {
        
        // New watt value has been calculated  
        if (!SLEEP_MODE && watt != oldWatt) {
        
          // Check that we dont get unresonable large watt value. 
          // could hapen when long wraps or false interrupt triggered
          if (watt<((unsigned long)MAX_WATT)) {
          
            gw.send(wattMsg.set(watt));  // Send watt value to gw 
          }  
          Serial.print("Watt:");
          Serial.println(watt);
          oldWatt = watt;
        }
      
        // Pulse cout has changed
        
        if (pulseCount != oldPulseCount) {
        
          gw.send(pcMsg.set(pulseCount));  // Send pulse count value to gw 
          double kwh = ((double)pulseCount/((double)PULSE_FACTOR));     
          oldPulseCount = pulseCount;
          
          //if (kwh != oldKwh) {
            gw.send(kwhMsg.set(kwh, 4));  // Send kwh value to gw 
            //oldKwh = kwh;
          //}
        }    
        lastSend = now;
      } else if (sendTime && !pcReceived) {
        // No count received. Try requesting it again
        gw.request(CHILD_ID, V_VAR1);
        lastSend=now;
      }
      
      if (SLEEP_MODE) {
        gw.sleep(SEND_FREQUENCY);
      }
    }
    
    void incomingMessage(const MyMessage &message) {
      if (message.type==V_VAR1) {  
        pulseCount = oldPulseCount = message.getLong();
        Serial.print("Received last pulse count from gw:");
        Serial.println(pulseCount);
        pcReceived = true;
      }
    }
    
    void onPulse()     
    { 
      if (!SLEEP_MODE) {
        unsigned long newBlink = micros();  
        unsigned long interval = newBlink-lastBlink;
        if (interval<10000L) { // Sometimes we get interrupt on RISING
          return;
        }
        watt = (3600000000.0 /interval) / ppwh;
        
        lastBlink = newBlink;
      } 
      pulseCount++;
    }
    


  • 0 MCO:BGN:INIT NODE,CP=RNNNA--,VER=2.1.0
    3 TSM:INIT
    4 TSF:WUR:MS=0
    11 TSM:INIT:TSP OK
    13 TSF:SID:OK,ID=254
    14 TSM:FPAR
    51 TSF:MSG:SEND,254-254-255-255,s=255,c=3,t=7,pt=0,l=0,sg=0,ft=0,st=OK:
    2058 !TSM:FPAR:NO REPLY
    2060 TSM:FPAR
    2096 TSF:MSG:SEND,254-254-255-255,s=255,c=3,t=7,pt=0,l=0,sg=0,ft=0,st=OK:
    2121 TSF:MSG:READ,0-0-254,s=255,c=3,t=8,pt=1,l=1,sg=0:0
    2126 TSF:MSG:FPAR OK,ID=0,D=1
    4104 TSM:FPAR:OK
    4105 TSM:ID
    4106 TSM:ID:OK
    4108 TSM:UPL
    4113 TSF:MSG:SEND,254-254-0-0,s=255,c=3,t=24,pt=1,l=1,sg=0,ft=0,st=OK:1
    4123 TSF:MSG:READ,0-0-254,s=255,c=3,t=25,pt=1,l=1,sg=0:1
    4128 TSF:MSG:PONG RECV,HP=1
    4131 TSM:UPL:OK
    4132 TSM:READY:ID=254,PAR=0,DIS=1
    4140 TSF:MSG:SEND,254-254-0-0,s=255,c=3,t=15,pt=6,l=2,sg=0,ft=0,st=OK:0100
    4164 TSF:MSG:READ,0-0-254,s=255,c=3,t=15,pt=6,l=2,sg=0:0100
    4172 TSF:MSG:SEND,254-254-0-0,s=255,c=0,t=17,pt=0,l=5,sg=0,ft=0,st=OK:2.1.0
    4183 TSF:MSG:SEND,254-254-0-0,s=255,c=3,t=6,pt=1,l=1,sg=0,ft=0,st=OK:0
    4203 TSF:MSG:READ,0-0-254,s=255,c=3,t=6,pt=0,l=1,sg=0:M
    4210 TSF:MSG:SEND,254-254-0-0,s=255,c=3,t=11,pt=0,l=12,sg=0,ft=0,st=OK:Energy Meter
    4224 TSF:MSG:SEND,254-254-0-0,s=255,c=3,t=12,pt=0,l=3,sg=0,ft=0,st=OK:1.0
    4235 TSF:MSG:SEND,254-254-0-0,s=1,c=0,t=13,pt=0,l=0,sg=0,ft=0,st=OK:
    4241 MCO:REG:REQ
    4246 TSF:MSG:SEND,254-254-0-0,s=255,c=3,t=26,pt=1,l=1,sg=0,ft=0,st=OK:2
    4253 TSF:MSG:READ,0-0-254,s=255,c=3,t=27,pt=1,l=1,sg=0:1
    4258 MCO:PIM:NODE REG=1
    4260 MCO:BGN:STP
    4267 TSF:MSG:SEND,254-254-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    4273 MCO:BGN:INIT OK,TSP=1
    4283 TSF:MSG:READ,0-0-254,s=1,c=2,t=24,pt=0,l=1,sg=0:1
    Received last pulse count from gw:1



  • here is my serial output. and remains like this.
    i have found your sketch but can not seem to get it to work to gw 2.0



  • And this is my log from DZ

    2017-01-10 22:00:28.664 MySensors: Node: 254, Sketch Name: Energy Meter
    2017-01-10 22:00:28.675 MySensors: Node: 254, Sketch Version: 1.0
    2017-01-10 22:00:33.737 (Gate) General/kWh (Meter)
    2017-01-10 22:00:33.761 (Gate) General/kWh (Meter)
    2017-01-10 22:01:34.631 (Gate) Temp + Humidity (GatewayBed1)
    2017-01-10 22:01:37.207 (Gate) Temp (Radio Room)
    2017-01-10 22:01:46.109 (Gate) General/Barometer (Pressure)
    2017-01-10 22:02:34.570 (Gate) Temp + Humidity (GatewayBed1)
    2017-01-10 22:02:34.573 (Gate) Temp + Humidity (GatewayBed1)
    2017-01-10 22:03:34.510 (Gate) Temp + Humidity (GatewayBed1)
    2017-01-10 22:03:34.513 (Gate) Temp + Humidity (GatewayBed1)
    2017-01-10 22:03:50.973 (Gate) Temp (Radio Room)
    2017-01-10 22:04:03.239 (Gate) Temp (Outside)
    2017-01-10 22:04:03.249 (Gate) General/Barometer (Pressure)



  • can you please print your code?

    I am not so good to read the Message structure but it look like it present temperature and other stuff



  • Ah the gateway works fine with other sensors
    The code for the pulse power meter is the one in the example



  • @asgardro said:

    i do not get Serial.print("Received last pulse count from gw:"); in serial output

    Yes you do, look at the last line and you will see it.



  • @asgardro

    change SEND_FREQUENCY to 5000, upload to Arduino, when you see Received from GW, trig Digital Input 3 and after 5 seconds it should send data to DZ again



  • Done that... reset everything..still the same

    here is my code

    #define DIGITAL_INPUT_SENSOR 3 // The digital input you attached your light sensor. (Only 2 and 3 generates interrupt!)
    #define PULSE_FACTOR 1000 // Nummber of blinks per KWH of your meeter
    #define SLEEP_MODE false // Watt-value can only be reported when sleep mode is false.
    #define MAX_WATT 10000 // Max watt value to report. This filetrs outliers.
    #define CHILD_ID 1 // Id of the sensor child

    unsigned long SEND_FREQUENCY = 5000; // Minimum time between send (in milliseconds). We don't wnat to spam the gateway.
    double ppwh = ((double)PULSE_FACTOR)/1000; // Pulses per watt hour
    bool pcReceived = true;
    volatile unsigned long pulseCount = 0;
    volatile unsigned long lastBlink = 0;
    volatile unsigned long watt = 0;
    unsigned long oldPulseCount = 0;
    unsigned long oldWatt = 0;
    double oldKwh;
    unsigned long lastSend;
    MyMessage wattMsg(CHILD_ID,V_WATT);
    MyMessage kwhMsg(CHILD_ID,V_KWH);
    MyMessage pcMsg(CHILD_ID,V_VAR1);

    void setup()
    {
    // Fetch last known pulse count value from gw
    request(CHILD_ID, V_VAR1);

    // Use the internal pullup to be able to hook up this sketch directly to an energy meter with S0 output
    // If no pullup is used, the reported usage will be too high because of the floating pin
    pinMode(DIGITAL_INPUT_SENSOR,INPUT_PULLUP);

    attachInterrupt(digitalPinToInterrupt(DIGITAL_INPUT_SENSOR), onPulse, RISING);
    lastSend=millis();
    }

    void presentation() {
    // Send the sketch version information to the gateway and Controller
    sendSketchInfo("Energy Meter", "1.0");

    // Register this device as power sensor
    present(CHILD_ID, S_POWER);
    }

    void loop()
    {
    unsigned long now = millis();
    // Only send values at a maximum frequency or woken up from sleep
    bool sendTime = now - lastSend > SEND_FREQUENCY;
    if (pcReceived && (SLEEP_MODE || sendTime)) {
    // New watt value has been calculated
    if (!SLEEP_MODE && watt != oldWatt) {
    // Check that we dont get unresonable large watt value.
    // could hapen when long wraps or false interrupt triggered
    if (watt<((unsigned long)MAX_WATT)) {
    send(wattMsg.set(watt)); // Send watt value to gw
    }
    Serial.print("Watt:");
    Serial.println(watt);
    oldWatt = watt;
    }

    // Pulse cout has changed
    if (pulseCount != oldPulseCount) {
      send(pcMsg.set(pulseCount));  // Send pulse count value to gw 
      double kwh = ((double)pulseCount/((double)PULSE_FACTOR));     
      oldPulseCount = pulseCount;
      if (kwh != oldKwh) {
        send(kwhMsg.set(kwh, 4));  // Send kwh value to gw 
        oldKwh = kwh;
      }
    }    
    lastSend = now;
    

    } else if (sendTime && !pcReceived) {
    // No count received. Try requesting it again
    request(CHILD_ID, V_VAR1);
    lastSend=now;
    }

    if (SLEEP_MODE) {
    sleep(SEND_FREQUENCY);
    }
    }

    void receive(const MyMessage &message) {
    if (message.type==V_VAR1) {
    pulseCount = oldPulseCount = message.getLong();
    Serial.print("Received last pulse count from gw:");
    Serial.println(pulseCount);
    pcReceived = true;
    }
    }

    void onPulse()
    {
    if (!SLEEP_MODE) {
    unsigned long newBlink = micros();
    unsigned long interval = newBlink-lastBlink;
    if (interval<10000L) { // Sometimes we get interrupt on RISING
    return;
    }
    watt = (3600000000.0 /interval) / ppwh;
    lastBlink = newBlink;
    }
    pulseCount++;
    }



  • @asgardro
    don't forget to use CODE function when posting code.

    If you don't see any reaction when you trig Digital 3 i don't know what can be the problem,

    Have you tried another Arduino?



  • @asgardro

    change bool pcReceived to false



  • ooops sorry about that... just found the function lol
    the sensor inits itself once and then doesn't do anything/ i don't know through what miracle i got the pulse count.
    will try another arduino... i do not think it is a radio problem..
    thanks for your help



  • changed it to false.
    put it true before to try to force the sensor sending independent of the count.. if i am correct
    still the same outcome... will try tomorrow diffrent hardware
    anyway, thanks a lot for the help



  • @asgardro said:

    changed it to false.
    put it true before to try to force the sensor sending independent of the count.. if i am correct

    Yes it will but it will only send 0 to VAR in DZ so it will be a loop of same value.
    Maybe that's why it never sends again.
    Try now to trig digital 3



  • sorry for the next noob question but what do you mean by trigginh the pin 3? simulating the sensor? if yes i done that.. i have a led blinking



  • @asgardro

    what have you connected to digital 3?



  • this is the code now

    /**
     * The MySensors Arduino library handles the wireless radio link and protocol
     * between your home built sensors/actuators and HA controller of choice.
     * The sensors forms a self healing radio network with optional repeaters. Each
     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
     * network topology allowing messages to be routed to nodes.
     *
     * 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
     * 
     * DESCRIPTION
     * This sketch provides an example how to implement a distance sensor using HC-SR04 
     * Use this sensor to measure KWH and Watt of your house meeter
     * You need to set the correct pulsefactor of your meeter (blinks per KWH).
     * The sensor starts by fetching current KWH value from gateway.
     * Reports both KWH and Watt back to gateway.
     *
     * Unfortunately millis() won't increment when the Arduino is in 
     * sleepmode. So we cannot make this sensor sleep if we also want 
     * to calculate/report watt-number.
     * http://www.mysensors.org/build/pulse_power
     */
    
    // Enable debug prints
    #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    
    //#define MY_RADIO_RFM69
    
    #include <MySensors.h>  
    
    #define DIGITAL_INPUT_SENSOR 3  // The digital input you attached your light sensor.  (Only 2 and 3 generates interrupt!)
    #define PULSE_FACTOR 1000       // Nummber of blinks per KWH of your meeter
    #define SLEEP_MODE false        // Watt-value can only be reported when sleep mode is false.
    #define MAX_WATT 10000          // Max watt value to report. This filetrs outliers.
    #define CHILD_ID 1              // Id of the sensor child
    
    unsigned long SEND_FREQUENCY = 5000; // Minimum time between send (in milliseconds). We don't wnat to spam the gateway.
    double ppwh = ((double)PULSE_FACTOR)/1000; // Pulses per watt hour
    bool pcReceived = false;
    volatile unsigned long pulseCount = 0;   
    volatile unsigned long lastBlink = 0;
    volatile unsigned long watt = 0;
    unsigned long oldPulseCount = 0;   
    unsigned long oldWatt = 0;
    double oldKwh;
    unsigned long lastSend;
    MyMessage wattMsg(CHILD_ID,V_WATT);
    MyMessage kwhMsg(CHILD_ID,V_KWH);
    MyMessage pcMsg(CHILD_ID,V_VAR1);
    
    
    void setup()  
    {  
      // Fetch last known pulse count value from gw
      request(CHILD_ID, V_VAR1);
    
      // Use the internal pullup to be able to hook up this sketch directly to an energy meter with S0 output
      // If no pullup is used, the reported usage will be too high because of the floating pin
      pinMode(DIGITAL_INPUT_SENSOR,INPUT_PULLUP);
    
      attachInterrupt(digitalPinToInterrupt(DIGITAL_INPUT_SENSOR), onPulse, RISING);
      lastSend=millis();
    }
    
    void presentation() {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Energy Meter", "1.0");
    
      // Register this device as power sensor
      present(CHILD_ID, S_POWER);
    }
    
    void loop()     
    { 
      unsigned long now = millis();
      // Only send values at a maximum frequency or woken up from sleep
      bool sendTime = now - lastSend > SEND_FREQUENCY;
      if (pcReceived && (SLEEP_MODE || sendTime)) {
        // New watt value has been calculated  
        if (!SLEEP_MODE && watt != oldWatt) {
          // Check that we dont get unresonable large watt value. 
          // could hapen when long wraps or false interrupt triggered
          if (watt<((unsigned long)MAX_WATT)) {
            send(wattMsg.set(watt));  // Send watt value to gw 
          }  
          Serial.print("Watt:");
          Serial.println(watt);
          oldWatt = watt;
        }
    
        // Pulse cout has changed
        if (pulseCount != oldPulseCount) {
          send(pcMsg.set(pulseCount));  // Send pulse count value to gw 
          double kwh = ((double)pulseCount/((double)PULSE_FACTOR));     
          oldPulseCount = pulseCount;
          if (kwh != oldKwh) {
            send(kwhMsg.set(kwh, 4));  // Send kwh value to gw 
            oldKwh = kwh;
          }
        }    
        lastSend = now;
      } else if (sendTime && !pcReceived) {
        // No count received. Try requesting it again
        request(CHILD_ID, V_VAR1);
        lastSend=now;
      }
    
      if (SLEEP_MODE) {
        sleep(SEND_FREQUENCY);
      }
    }
    
    void receive(const MyMessage &message) {
      if (message.type==V_VAR1) {  
        pulseCount = oldPulseCount = message.getLong();
        Serial.print("Received last pulse count from gw:");
        Serial.println(pulseCount);
        pcReceived = true;
      }
    }
    
    void onPulse()     
    { 
      if (!SLEEP_MODE) {
        unsigned long newBlink = micros();  
        unsigned long interval = newBlink-lastBlink;
        if (interval<10000L) { // Sometimes we get interrupt on RISING
          return;
        }
        watt = (3600000000.0 /interval) / ppwh;
        lastBlink = newBlink;
      } 
      pulseCount++;
    }
    


  • @flopp

    i have connected the digital out from the sensor



  • @asgardro said:

    @flopp

    i have connected the digital out from the sensor

    Do you mean LM393?

    Can you put a flash light in front of the sensor so trigger it. You shall now see some text in serial monitor



  • @flopp
    lm393



  • @asgardro said:

    @flopp
    lm393

    Have you trimmed the pot so the LED turns on when your power meter flash?



  • @flopp
    i have done that and calibrated the lm393 , i have a blinking light that triggers the sensor. thats how i am testing...but after initializing sends the value first time and thats it
    sorry to reply so late but have to wait 120seconds between posts lol



  • /**
     * The MySensors Arduino library handles the wireless radio link and protocol
     * between your home built sensors/actuators and HA controller of choice.
     * The sensors forms a self healing radio network with optional repeaters. Each
     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
     * network topology allowing messages to be routed to nodes.
     *
     * 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
     * 
     * DESCRIPTION
     * This sketch provides an example how to implement a distance sensor using HC-SR04 
     * Use this sensor to measure KWH and Watt of your house meeter
     * You need to set the correct pulsefactor of your meeter (blinks per KWH).
     * The sensor starts by fetching current KWH value from gateway.
     * Reports both KWH and Watt back to gateway.
     *
     * Unfortunately millis() won't increment when the Arduino is in 
     * sleepmode. So we cannot make this sensor sleep if we also want 
     * to calculate/report watt-number.
     * http://www.mysensors.org/build/pulse_power
     */
    
    // Enable debug prints
    #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RF24_CHANNEL 74
    //#define MY_RADIO_RFM69
    
    #include <MySensors.h>  
    
    #define DIGITAL_INPUT_SENSOR 3  // The digital input you attached your light sensor.  (Only 2 and 3 generates interrupt!)
    #define PULSE_FACTOR 1000       // Nummber of blinks per KWH of your meeter
    #define SLEEP_MODE false        // Watt-value can only be reported when sleep mode is false.
    #define MAX_WATT 10000          // Max watt value to report. This filetrs outliers.
    #define CHILD_ID 1              // Id of the sensor child
    
    unsigned long SEND_FREQUENCY = 5000; // Minimum time between send (in milliseconds). We don't wnat to spam the gateway.
    double ppwh = ((double)PULSE_FACTOR)/1000; // Pulses per watt hour
    bool pcReceived = false;
    volatile unsigned long pulseCount = 0;   
    volatile unsigned long lastBlink = 0;
    volatile unsigned long watt = 0;
    unsigned long oldPulseCount = 0;   
    unsigned long oldWatt = 0;
    double oldKwh;
    unsigned long lastSend;
    MyMessage wattMsg(CHILD_ID,V_WATT);
    MyMessage kwhMsg(CHILD_ID,V_KWH);
    MyMessage pcMsg(CHILD_ID,V_VAR1);
    
    
    void setup()  
    {  
      // Fetch last known pulse count value from gw
      request(CHILD_ID, V_VAR1);
    
      // Use the internal pullup to be able to hook up this sketch directly to an energy meter with S0 output
      // If no pullup is used, the reported usage will be too high because of the floating pin
      pinMode(DIGITAL_INPUT_SENSOR,INPUT_PULLUP);
    
      attachInterrupt(digitalPinToInterrupt(DIGITAL_INPUT_SENSOR), onPulse, RISING);
      lastSend=millis();
      Serial.println("7");
    }
    
    void presentation() {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Energy Meter", "1.0");
    
      // Register this device as power sensor
      present(CHILD_ID, S_POWER);
      Serial.println("7");
    }
    //Serial.println("6");
    void loop()     
    { 
      unsigned long now = millis();
      // Only send values at a maximum frequency or woken up from sleep
      bool sendTime = now - lastSend > SEND_FREQUENCY;
      if (pcReceived && (SLEEP_MODE || sendTime)) {
        // New watt value has been calculated  
        if (!SLEEP_MODE && watt != oldWatt) {
          // Check that we dont get unresonable large watt value. 
          // could hapen when long wraps or false interrupt triggered
          if (watt<((unsigned long)MAX_WATT)) {
            send(wattMsg.set(watt));  // Send watt value to gw 
          }  
          Serial.print("Watt:");
          Serial.println(watt);
          oldWatt = watt;
        }
    Serial.println("5");
        // Pulse cout has changed
        if (pulseCount != oldPulseCount) {
          send(pcMsg.set(pulseCount));  // Send pulse count value to gw 
          double kwh = ((double)pulseCount/((double)PULSE_FACTOR));     
          oldPulseCount = pulseCount;
          if (kwh != oldKwh) {
            send(kwhMsg.set(kwh, 4));  // Send kwh value to gw 
            oldKwh = kwh;
          }
          Serial.println("4");
        }    
        lastSend = now;
      } else if (sendTime && !pcReceived) {
        // No count received. Try requesting it again
        request(CHILD_ID, V_VAR1);
        lastSend=now;
      }
    Serial.println("3");
      if (SLEEP_MODE) {
        sleep(SEND_FREQUENCY);
      }
      Serial.println("2");
    }
    
    void receive(const MyMessage &message) {
    if (message.type==V_VAR1) {
    Serial.println("rece");
    pulseCount = oldPulseCount = message.getLong();
    Serial.print("Received last pulse count from gw:");
    Serial.println(pulseCount);
    pcReceived = true;
    }
    Serial.println("not_rece");
    }
    
    void onPulse()     
    { 
      if (!SLEEP_MODE) {
        unsigned long newBlink = micros();  
        unsigned long interval = newBlink-lastBlink;
        if (interval<10000L) { // Sometimes we get interrupt on RISING
          return;
        }
        watt = (3600000000.0 /interval) / ppwh;
        lastBlink = newBlink;
        
      } 
     
      pulseCount++;
      Serial.println("1");
      
    }
    
    

    this



  • As the sketch starts by requesting the latest pulse count (e.g starting kWh value) and does not send anything without having received it, how do I "seed" this value to my GW? I am using a MQTT GW, can I construct a MQTT special message containing the value, or how is it supposed to work?



  • @maghac
    I am using Domoticz ans MyS 1.5.1
    You don't have to create VAR1, it will be created when you ask for it or it always exists for each Child.
    If you want VAR1 to be exactly the same as your meter you need to open domoticz.db and set the value or in your sketch.


  • Hardware Contributor

    Anyone knows why I dont get the sleep() function (time) to work properly.

    My hardware is EasyPCB, Pro Mini 3.3v 8mhz, Booster 2xAA and NRF24 radio.
    My software is: standard sketch 2.0.1, with sleep function.

    The problem is the sleep time is 5 times less than declared so maybe timing?
    When i enter sleep(10000) for example the nodes sleeps for 2 sec and wakes up.

    The interupt works fine.

    My sollution was adding *5 to get the correct sleep time - but why doesnt it work?



  • @flopp I had to set pcReceived to true, upload the sketch, run it and then change back to false again and recompile/reupload. I can understand why it does it, since you don't want the pulse counter to reset to 0 if the sensor happens to restart (because you killed the power or whatever).

    What I don't understand is how I can seed the value with the correct initial value.

    Is it the controller (in my case HomeAssistant) or the gateway that is supplying the value?



  • It appears to be the controller that stores the value. I deleted the sensor from HomeAssistant and restarted, when it came back in again it started from zero.


  • Plugin Developer

    @maghac

    This is a hack, but if using json persistence, you can set the count in the JSON file and restart home assistant, with the node turned off. Then turn on the node.



  • @martinhjelmare Yep, I figured I could do that. The absolute value is not so important actually, I'm more interested in the daily/weekly delta, which I hope Grafana can tell me.


  • Mod

    is this the same sensor than the one in the guide?
    http://uk.farnell.com/ams/tsl250r-lf/photodiode-sensor-l-volts/dp/1182346

    Can I also use also photoresistor? (Since I already have one)


  • Hardware Contributor

    @gohan - nope its not the same, and yes you can use a photoresistor (i have just made one) but I needed a transistor for it to work and also it had to be completley dark. Using this on batteries its much better using just a photoresistor because the sensor in the guide draws about 1mA which will drain the batteris very quickly.

    I will post my sensor later.

    Edit: this is the sensor i build:

    0_1486915502085_1.jpg
    0_1486915592318_20170212_135834.jpg

    The node (including pro mini) draws about 50uA sleeping and 170uA not sleeping.
    The photoresistor was 5M ohm in complete dark.


  • Mod

    The guide specifies LM393 Light Sensor or the tsl250r-lf so I thought it was the same since the same name.
    Since the node will be powered with it's power supply, I don't have any battery drain problem in this case. But why did you use a transistor? Can't you just check for a threshold value in the analog input to count as a pulse?


  • Hardware Contributor

    Ok, all I can see is that it doesnt look the same at all.
    @gohan - I tried, and I thought that should work - but for some reason I could not get it to trigger the interupt on the atmega 😞
    Looking the the voltage thresholds it was supposed to work but it didnt. I was thinking it was to low uA but i dont know really.




  • Mod

    @sundberg84

    Instead of the 10k resistor, do you think I could use a potentiometer to "adjust" sensitivity? I would like to avoid messing up the readings with lights entering when opening the cabinet door where the meter is located

    @flopp
    Do you mind sharing your wiring? 940nm, isn't it infrared?


  • Hardware Contributor

    @gohan - a potentiometer is just a variable resistor so why not? Good idea if you have one laying around.
    As i said before though, the try with the transistor is just a try - im not that good with transistors yet and dont know how they work exactly. After this i read somewhere that the base resistor should be bigger to protect the transistor... dont know how to calculate that.



  • @gohan said in 💬 Power Meter Pulse Sensor:

    @sundberg84

    @flopp
    Do you mind sharing your wiring? 940nm, isn't it infrared?

    I connected the photo resistor directly to the LM393.
    I don't know if that is IR.



  • Hello,

    First, thanks for this tutorial !
    I used the code defined in tutorial but I have the following message for "void receive(const MyMessage &message)" :

    'MyMessage' does not name a type
    

    Do you know what can be the cause of this error please ?

    Thanks in advance for your help


  • Mod

    @moumout31 do you have void receive(const MyMessage &message) somewhere in your code or where does it come from?
    Could you post the full error message?

    Have you installed the MySensors library?



  • @mfalkvidd void receive(const MyMessage &message) is in the code.
    MySensors library is installed, I already use it in other nodes.
    It's strange because it works in another computer...

    The full error messages, in french beacause I'm french are :

    Arduino : 1.8.0 (Windows 7), Carte : "Arduino Pro or Pro Mini, ATmega328 (3.3V, 8 MHz)"
    
    _02_Main_loop:271: error: 'MyMessage' does not name a type
    
    In file included from C:\Users\Anne-Laure\Documents\Arduino\libraries\arduino_759467/MySensors.h:257:0,
    
                     from C:\Users\Anne-Laure\Dropbox\Maison\A récupérer sur OneDrive\my_teleinfo_light\_02_Main_loop.ino:118:
    
    C:\Users\Anne-Laure\Documents\Arduino\libraries\arduino_759467/core/MyTransport.cpp: In function 'void transportProcessMessage()':
    
    C:\Users\Anne-Laure\Documents\Arduino\libraries\arduino_759467/core/MyTransport.cpp:745:14: error: cannot resolve overloaded function 'receive' based on conversion to type 'bool'
    
       if (receive) {
    
                  ^
    
    C:\Users\Anne-Laure\Documents\Arduino\libraries\arduino_759467/core/MyTransport.cpp:811:15: error: cannot resolve overloaded function 'receive' based on conversion to type 'bool'
    
        if (receive) {
    
                   ^
    
    exit status 1
    'MyMessage' does not name a type
    
    Bibliothèque non valide trouvée dans C:\Users\Anne-Laure\Documents\Arduino\libraries\MySensors : C:\Users\Anne-Laure\Documents\Arduino\libraries\MySensors
    
    Ce rapport pourrait être plus détaillé avec
    l'option "Afficher les résultats détaillés de la compilation"
    activée dans Fichier -> Préférences.
    

    Thanks for your help


  • Mod

    @moumout31 My guess is that MyMessage is defined in your sketch, overriding the definition in the MySensors library. Could you post your sketch?



  • @mfalkvidd It's strange... It works with an older version of Arduino software... Thus, the problem is solved ! Thanks



  • Hello,

    I don't understand why, but my power meter sensor gives a higher index than the real power meter index after 2 days.
    I think that it counts more pulses than pulses provided by the power meter...
    Does anybody encounter this problem ?
    Can it be cause to bounce for example ?

    Thank you


  • Mod

    @moumout31
    could it be getting some light from another source?



  • @moumout31
    I had same issue, check here for my solution
    https://forum.mysensors.org/topic/4716/two-energy-meter/4



  • Hei.

    How to connect arduino to electricity meter pulse out. Not to led.



  • @gohan No, the light is always switched off in this room and I tried, when I switch on the light, there is no pulse from the sensor.

    @flopp Thanks for your help. What I see in your topic is that you increase from 10000µs to 40000µs the interval to avoid corrupted interrupts, is that correct ?

    Thank you



  • @moumout31
    Yes correct.
    When I checked with Serial Monitor and some serial.print in different places I could see that arduino registered double interrupts



  • @flopp Thanks a lot, I will try this solution and check if it's better !



  • @flopp It seems to work, index on Domoticz is still consistent with the real index... I will see in a few days if it's still the case.
    Thanks a lot for your help !



  • @flopp After a few days, I confirm you that the index is consistent with power meter index.
    However, instant power in watt is not correcly calculated.
    For example, when power meter indicates 550W, about 1500W is calculated by the sketch. Do you know how I can resolve this problem please ?

    Thanks a lot !



  • @moumout31
    Watt calculation is using time between two interrupts.
    How often do you send watt?
    Did you measure watt with a measurement tool How did you get 500 watts from power meter?
    When you send watt you need to measure exact same second otherwise it will not be correct.



  • @flopp Watt is sent every 20 seconds (as done in the original sketch).
    500 watts is the power indicated on the screen of the power meter.



  • Just changed from 1-wire counter to MySensors for logging my power consumption. Using the same LED detector as I did when using 1-wire. Also changed watt limit to 20 000 (my heat pump likes to use 9-10kW sometimes). The wires from the old 1-wire net now provide power for the new MySensors-sensor. I have 10 000 led blinks per kWh. Had som crazy counter values with 1-wire that totally messed up the graphs and haven't seen anything like that with this sketch. Let's hope it stays that way. 😉 Dumping data to Domoticz. This sensor gives me higher resolution as a bonus. The 1-wire counter was read every minute, this every 20-sec. 😉

    0_1490286464866_Domoticz_-_Google_Chrome_2017-03-23_17-27-32_78641890.png

    0_1490286540285_Domoticz_-_Google_Chrome_2017-03-23_17-28-46_94994234.png

    My old 1-wire counter with one crazy value messing upp all the graphs:
    0_1490286637201_Domoticz_-_Google_Chrome_2017-03-23_17-30-09_29365468.png
    I know that you can hold shift and click the value that is crazy to make the graphs show up good but you loose the data for the full day. That's not good. 😉


  • Hardware Contributor

    I seem to be getting a connection to my gateway, while monitoring the two topics for the gateway i only seem to see any activity regarding this sensor on the gateway-out topic, and it keeps sending out a type 2 message (req). The serial monitor of the sensors is showing:

    104198 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    114199 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    124200 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    134201 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    144202 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    154203 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    164204 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    174205 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    184206 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    194207 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:

    So it seems to be sending a request package, but i don't see it on the gateway-in topic and i see other sensors sending data to the gateway-in topic so i'm not subscribed to the wrong one. Is this a structural request message or is this the feature that requests the last known message from the gateway? Either way, there doesn't seem to be any sensor data being sent from the node to the gateway.


  • Hardware Contributor

    @Samuel235 said in 💬 Power Meter Pulse Sensor:

    164204 TSF:MSG:SEND,16-16-0-0,s=1,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:

    I dont know if I dont understand you, but it seems like your node is requesting the last pulse counter. I have mentioned this in several threads I have a problem with this (both this thread and rain sensor thread). Im using an ethernet gw and the request reaches the gw but there my error led blinks and it fails to send it back (or recieve it on the node) so it re-request it.

    I have never been able to pinpoint it due to repeaters in between.
    https://forum.mysensors.org/topic/2116/hard-to-grab-time-and-value-sent-from-controller/ (old).


  • Hardware Contributor

    @sundberg84 - You do understand me correctly :). I made a thread on the troubleshooting section of the forum for this simply because i suspected it was normal behaviour, however. It seems that the node isn't sending any other data to the gateway at all and it can not get the previous value as there isn't one. So, my post here and on the troubleshooting section was me aiming to get to this point and then troubleshoot the actual node to see what can be done to get it to send data.


  • Hardware Contributor

    Has anyone came across their pulse meter not sending the message for WATT, the other two messages are being sent perfectly fine. My WATT message has been working all day and suddenly stopped.



  • Make sure that you don't reach your wattage limit in the sketch.


  • Hardware Contributor

    @NiklasO - Where is this value stored? I've cleared the EEPROM and the MQTT topic too, but it still refuses to send the watt value.



  • @Samuel235
    In the sketch, change this
    #define MAX_WATT 10000 // Max watt value to report. This filetrs outliers.
    I have it set to 20000, using 15 000 easily when it's cold outside. 😉 Just make sure that you use the right divider for your pulse/kWh count.


  • Hardware Contributor

    Ahh i see what it is it; its set to not send if it hasn't changed.... how much of a silly error that was from me. The wattage is way below 1000 but because i'm using a normal LED on another arduino flashing at a constant rate to set my node up, its not changing the watt value.

    Back to solving my initial issue now >.<

    Thank you.



  • Ah, I see. Well, I would like the sensor to send data even if it hasn't changed. What did you change?


  • Mod

    Watt usage is normally changing all the time, so you should have data reported quite often



  • @gohan But Samuel235 had that problem? 😉 Edit: well, ok, he had a different setup. I need to read better. 😉


  • Hardware Contributor

    To be honest, i had it running for a while before it stopped sending the WATTS. But i'm guessing this is the issue as if i vary the blinks it sends it. I'de like to see if anyone has this working recently on OpenHAB through means of not touching the node sketch like people have posted before. I have an idea to send the data of the pulse count message onto the request message topic on MQTT and so then when it requests previous count it would have it.


  • Hardware Contributor

    This post is deleted!


  • EDIT:
    This was not the case, I am still debugging the issue, in the mean time I have deleted the code.

    After some debugging it seems that Domoticz messes with the V_WATT and V_KWH, and the solution is to have two sensors, one for kWh and one for W.
    After I changed it, I have consistent W and kWh.
    See also this issue for Home Assistant



  • OK, I think I have nailed it. I am now running a beta code pulling S0 from my energy meter and I am getting consistent results.
    Before when I checked the domoticz.db I got this for Energy:

    sqlite> select Name, sValue from DeviceStatus;
    Storage kWh|0.000;4773.700
    

    Now I get this:

    sqlite> select Name, sValue from DeviceStatus;
    Storage kWh|118.000;11678062.000
    

    Notice that the first field is now with value, previously it was 0.000 (and I have updated the meter count to the actual value)
    And in table Meter I now get consistent results:

    sqlite> SELECT Value, Usage, Date FROM Meter WHERE DeviceRowID=43;
    11678003|1170|2017-07-22 09:25:00
    11678012|1170|2017-07-22 09:30:00
    11678021|1180|2017-07-22 09:35:00
    11678031|1180|2017-07-22 09:40:00
    11678043|1170|2017-07-22 09:45:00
    11678053|1180|2017-07-22 09:50:00
    11678062|1180|2017-07-22 09:55:00
    11678072|1180|2017-07-22 10:00:00
    

    The field Usage is now populated as it should.
    I will let the code run for a couple of days, then I will post the updated code here.



  • Here is a code example that works for me. I have an energy meter with S0 output and I use Domoticz as the controller.

    /**
     * The MySensors Arduino library handles the wireless radio link and protocol
     * between your home built sensors/actuators and HA controller of choice.
     * The sensors forms a self healing radio network with optional repeaters. Each
     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
     * network topology allowing messages to be routed to nodes.
     *
     * 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 - Mikael Carlsson
     *
     * DESCRIPTION
     * This sketch provides an example how to implement a sensor reading from an energy meter
     * Use this sensor to measure KWH and Watt of your house meeter
     * You need to set the correct pulsefactor of your meeter (blinks per KWH).
     * The sensor starts by fetching current KWH value from gateway.
     * Reports both KWH and Watt back to gateway.
     *
     * Unfortunately millis() won't increment when the Arduino is in
     * sleepmode. So we cannot make this sensor sleep if we also want
     * to calculate/report watt-number.
     * http://www.mysensors.org/build/pulse_power
     */
    
    // Enable debug prints
    #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    
    #include <MySensors.h>
    
    #define DIGITAL_INPUT_SENSOR 3  // The digital input you attached your light sensor.  (Only 2 and 3 generates interrupt!)
    #define PULSE_FACTOR 1000       // Nummber of blinks per KWH of your meter
    #define SLEEP_MODE false        // Watt-value can only be reported when sleep mode is false.
    #define MAX_WATT 10000          // Max watt value to report. This filters bad data.
    #define CHILD_ID 1              // Id of the sensor child
    
    unsigned long SEND_FREQUENCY =
        20000; // Minimum time between send (in milliseconds). We don't want to spam the gateway.
    double ppwh = ((double)PULSE_FACTOR)/1000; // Pulses per watt hour
    bool pcReceived = false;
    volatile unsigned long pulseCount = 0;
    volatile unsigned long lastBlink = 0;
    volatile unsigned long watt = 0;
    unsigned long oldPulseCount = 0;
    unsigned long oldWatt = 0;
    double oldKwh;
    unsigned long lastSend;
    MyMessage wattMsg(CHILD_ID,V_WATT);
    MyMessage kwhMsg(CHILD_ID,V_KWH);
    MyMessage pcMsg(CHILD_ID,V_VAR1);
    
    
    void setup()
    {
        // Fetch last known pulse count value from gw
        request(CHILD_ID, V_VAR1);
    
        // Use the internal pullup to be able to hook up this sketch directly to an energy meter with S0 output
        // If no pullup is used, the reported usage will be too high because of the floating pin
        pinMode(DIGITAL_INPUT_SENSOR,INPUT_PULLUP);
    
        attachInterrupt(digitalPinToInterrupt(DIGITAL_INPUT_SENSOR), onPulse, RISING);
        lastSend=millis();
    }
    
    void presentation()
    {
        // Send the sketch version information to the gateway and Controller
        sendSketchInfo("Energy Meter", "1.0");
    
        // Register this device as power sensor
        present(CHILD_ID, S_POWER);
    }
    
    void loop()
    {
        unsigned long now = millis();
        // Only send values at a maximum frequency or woken up from sleep
        bool sendTime = now - lastSend > SEND_FREQUENCY;
        if (pcReceived && (SLEEP_MODE || sendTime)) {
            // New watt value has been calculated
            if (!SLEEP_MODE && watt != oldWatt) {
                // Check that we dont get unresonable large watt value.
                // could happen when long wraps or false interrupt triggered
                // We need to send in all values at one time to get consistent data
                if (watt<((unsigned long)MAX_WATT)) {
                    send(wattMsg.set(watt));  // Send watt value to gw
                    Serial.print("Watt: ");
                    Serial.println(watt);
                    oldWatt = watt;
                    send(pcMsg.set(pulseCount));  // Send pulse count value to gw
                    Serial.print("pulseCount: ");
                    Serial.println(watt);
                    double kwh = ((double)pulseCount/((double)PULSE_FACTOR));
                    oldPulseCount = pulseCount;
                    send(kwhMsg.set(kwh, 4));  // Send kwh value to gw
                    Serial.print("kWh: ");
                    Serial.println(kwh);
                    oldKwh = kwh;
                }
            }
            lastSend = now;
        } else if (sendTime && !pcReceived) {
            // No count received. Try requesting it again
            request(CHILD_ID, V_VAR1);
            lastSend=now;
        }
    
        if (SLEEP_MODE) {
            sleep(SEND_FREQUENCY);
        }
    }
    
    void receive(const MyMessage &message)
    {
        if (message.type==V_VAR1) {
            pulseCount = oldPulseCount = message.getLong();
            Serial.print("Received last pulse count from gw:");
            Serial.println(pulseCount);
            pcReceived = true;
        }
    }
    
    void onPulse()
    {
        if (!SLEEP_MODE) {
            unsigned long newBlink = micros();
            unsigned long interval = newBlink-lastBlink;
            if (interval<10000L) { // Sometimes we get interrupt on RISING
                return;
            }
            watt = (3600000000.0 /interval) / ppwh;
            lastBlink = newBlink;
        }
        pulseCount++;
    }```


  • One (probably stupid) question about the batter powered option: Since sensor cannot keep track of real time power usage as it sleeps most of the time, would it be possible to do the math on the controller side and get "5min delay real time power usage"?
    By dividing number of pulses since last transmission, is that basically what this sensor is doing when not being powered by batteries?

    I could experiment with 2min delay f.eks, and see how batteries hold. If dht22 temp sensors works over a year with 5min transmission time, i hope 2min delay in pulse meter can hold 6mnt or something?
    Another thing is that the electrical box is all metal, and there is a lot of electricity around the sensor so radio could struggle (I guess a repeater would definitively help)


  • Mod

    Is it only me that is getting a compile error?

    Error: call of overloaded 'set(volatile long unsigned int&)' is ambiguous
    send(wattMsg.set(watt)); \ Send watt value to gw

    error: call of overloaded 'set(volatile long unsigned int&)' is ambiguous
    send(pcMsg.set(pulseCount)); \ Send pulse count value to gw

    followed by all the possible candidates of .set arguments


  • Mod

    @gohan I get the same, both for 2.1.1 and 2.2.0-beta. Strange. I thought there were Jenkins tests that endured the examples compiled.


  • Mod

    Replacing all

    unsigned long
    

    with

    uint32_t
    

    makes the sketch compile fine, but I don't know if that is the correct solution.


  • Mod


Log in to reply
 

Suggested Topics

  • 3
  • 2
  • 5
  • 584
  • 109
  • 10

0
Online

11.4k
Users

11.1k
Topics

112.7k
Posts