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
N

niccodemi

@niccodemi
About
Posts
118
Topics
10
Shares
0
Groups
0
Followers
1
Following
0

Posts

Recent Best Controversial

  • openHAB 4 MySensors Binding
    N niccodemi

    @forexsieno I am running OH4 but have migrated MySensors to MQTTGateway. Below example of how to control relays.

    thing file

    Bridge mqtt:broker:Mosquitto "Mysensors MQTT Broker" [host="192.xxx.xxx.xxx", secure=false, port=1883, clientID="Openhab"] 
    {
        Thing topic relunderstair "Relay" (mqtt:broker:Mosquitto) {
            Channels:
                Type switch : relunderstair0101 "LED-stairs" [ stateTopic="mygateway1-out/1/1/0/0/2", commandTopic ="mygateway1-in/1/1/0/0/2", on="1", off="0" ]
        }
     }
    

    item file

    Switch relunderstair0101  "LED-stairs" { channel="mqtt:topic:Mosquitto:relunderstair:relunderstair0101" }
    
    OpenHAB

  • openHAB 4 MySensors Binding
    N niccodemi

    @ben999 Thank you. I managed to get sensors data coming into OH.

    Would you happen to have also any thing / item example for switch / relay sketch?

    OpenHAB

  • openHAB 4 MySensors Binding
    N niccodemi

    Hi @ben999

    I used to have OH3 with MySensors Ethernet gateway but now I have upgraded to OH4 and it seems the only option is to connect MySensors network to OH via MQTT.
    I flashed MySensors mqtt_gateway and installed Mosquitto on same machine where OH4 is installed (ip=192.168.1.yyy). I also installed MQTT binding in OH4.

    Can you please advise how did you configure things and items file? In OH3 I had them configured in textual format.

    Things file in OH3

    Bridge mysensors:bridge-eth:gateway [ ipAddress="192.168.1.xxx", tcpPort=5003, sendDelay=300, startupCheckEnabled=false, networkSanCheckEnabled=true ] {
    	 light			relunderstair0101 [ nodeId=1, childId=1, requestAck=false ]
    

    Items file in OH3

    Switch relunderstair0101  "LED-stairs" { channel="mysensors:light:gateway:relunderstair0101:status" }
    
    OpenHAB

  • OH3 - MySensors Binding
    N niccodemi

    After upgrading OH from 3.2.0 to 3.3.0 and placing latest Mysensors binding (3.3.0-SNAPSHOT) into addon folder I can only get it to "Installed" status but not "active".

    Any advise how to remove following issues?

    openhab> feature:install openhab-transport-serial
    openhab> feature:install openhab-core-io-transport-mqtt
    openhab> diag 291
    openHAB Add-ons :: Bundles :: MySensors Binding (291)
    -----------------------------------------------------
    Status: Installed
    Unsatisfied Requirements:
    osgi.wiring.package; filter:="(osgi.wiring.package=org.openhab.binding.mqtt.handler)"
    osgi.wiring.package; filter:="(osgi.wiring.package=org.openhab.binding.mysensors.action)"
    osgi.wiring.package; filter:="(osgi.wiring.package=org.openhab.binding.mysensors.config)"
    osgi.wiring.package; filter:="(osgi.wiring.package=org.openhab.binding.mysensors.factory)"
    Declarative Services
    
    OpenHAB

  • OH3 - MySensors Binding
    N niccodemi

    Hi,

    I just upgraded Linux Openhab version from "openHAB 3.1.0.M2" to "openHAB 3.1.0.M3". Since upgrade I cannot use / activate MySensors binding anymore (it worked in previous version - M2).
    I cleaned openhab cache, rebooted computer; feature:install openhab-transport-serial and feature:install openhab-core-io-transport-mqtt are properly installed and active. When I place Mysensors.jar to Addons folder the file gets recognized but it is listed only as Installed, not active.

    openhab> bundle:list | grep MySensors
    266 x Installed x  80 x 3.1.0.202012312203      x openHAB Add-ons :: Bundles :: MySensors Binding
    

    Log shows following error:

     [WARN ] [org.apache.felix.fileinstall         ] - Error while starting bundle: file:/usr/share/openhab/addons/org.openhab.binding.mysensors-3.1.0.jar
    org.osgi.framework.BundleException: Could not resolve module: org.openhab.binding.mysensors [266]
      Unresolved requirement: Import-Package: org.apache.commons.lang; version="[2.6.0,3.0.0)"
    
            at org.eclipse.osgi.container.Module.start(Module.java:444) ~[org.eclipse.osgi-3.12.100.jar:?]
            at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:383) ~[org.eclipse.osgi-3.12.100.jar:?]
            at org.apache.felix.fileinstall.internal.DirectoryWatcher.startBundle(DirectoryWatcher.java:1260) [bundleFile:3.6.4]
            at org.apache.felix.fileinstall.internal.DirectoryWatcher.startBundles(DirectoryWatcher.java:1233) [bundleFile:3.6.4]
            at org.apache.felix.fileinstall.internal.DirectoryWatcher.doProcess(DirectoryWatcher.java:520) [bundleFile:3.6.4]
            at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:365) [bundleFile:3.6.4]
            at org.apache.felix.fileinstall.internal.DirectoryWatcher.run(DirectoryWatcher.java:316) [bundleFile:3.6.4]
    
    

    Does anyone know how to resolve this issue / install missing requirement?

    OpenHAB

  • Openhab multiple gateways
    N niccodemi

    @TimO thanks, that's great. Do I have to change the bridge name (gateway) for the second bridge to something else? Can I use same node IDs on both gateways?

    Bridge mysensors:bridge-ser:gateway [ serialPort="/dev/pts/2", sendDelay=200 ] {
    	humidity 		hum01 	[ nodeId=172, childId=0 ]
    	temperature		temp01 	[ nodeId=172, childId=1 ]
            light			light01 [ nodeId=105, childId=0  ]
            light			light02 [ nodeId=105, childId=1 ]
      }
    Bridge mysensors:bridge-eth:gateway [ ipAddress="127.0.0.1", tcpPort=5003, sendDelay=200 ] {
    	humidity 		hum01 	[ nodeId=172, childId=0 ]
    	temperature		temp01 	[ nodeId=172, childId=1 ]
            light			light01 [ nodeId=105, childId=0 ]
            light			light02 [ nodeId=105, childId=1 ]
      }
    
    OpenHAB

  • Openhab multiple gateways
    N niccodemi

    Hi,

    is it possible to configure multiple MySensors gateways (ie one serial and one ethernet) on single Openhab server?

    OpenHAB

  • water flow sensor YF-B5
    N niccodemi

    @yveaux is there any way to convert flow in l/min to pulses per liter?

    Another user posted below info; is that accurate?

      • Flow meter using Honeywell C7195A2001B which has a hall sensor that pulses at 7 Hz per liter/min
    • we count only upgoing pulses, so in our case we get:
    • 7 pulses per second at 1 l/min
    • 420 pulses per liter
    • 420000 pulses per m3
    • Flow meter Caleffi 316 which has a hall sensor that pulses at 8.8 Hz per liter/min (according to specs)
    • In reality the frequency is about 30% lower in my case, so we have to correct this with a factor of 1.3.
    • 8.8 pulses per second at 1 l/min
    • 528 pulses per liter
    • 528000 pulses per m3
    • 528000/1.3 = 406154
    Troubleshooting

  • water flow sensor YF-B5
    N niccodemi

    Hi,

    I would like to use YF-B5 water flow sensor with default mysensors water-meter sketch. I need help getting correct PULSE_FACTOR value based on below specs:

    1 Appearance Product identification clear, accurate and meet the requirements
    2 water pressure> 1.75MPa
    3 Operating voltage range DC5 ~ 15V
    4 Insulation resistance> 100MΩ
    5 Accuracy (in 1 ~ 25L \ MIN) ± 3%
    6 Flow Pulse Characteristics (6.6 * Q) Q = L / Min ± 3%
    7 Output pulse high> DC 4.7V (input voltage DC 5V)
    8 Output pulse low level <DC 0.5V (input voltage DC 5V)
    9 Output pulse duty cycle 50% ± 10%

    #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_NRF5_ESB
    //#define MY_RADIO_RFM69
    //#define MY_RADIO_RFM95
    
    #include <MySensors.h>
    
    #define DIGITAL_INPUT_SENSOR 3                  // The digital input you attached your sensor.  (Only 2 and 3 generates interrupt!)
    
    #define PULSE_FACTOR 1000                       // Number of blinks per m3 of your meter (One rotation/liter)
    
    #define SLEEP_MODE false                        // flowvalue can only be reported when sleep mode is false.
    
    #define MAX_FLOW 40                             // Max flow (l/min) value to report. This filters outliers.
    
    Troubleshooting

  • Relay control - bistable switch instead of monostable.
    N niccodemi

    I am using below sketch; make sure that number of relays matches number of relayPins and buttonPins.

    //MultiRelayButton Sketch, MySensors 1.6, toggle switch
    
    #define MY_RADIO_NRF24
    
    #define MY_REPEATER_FEATURE
    
    //Set Static node id
    //#define MY_NODE_ID 250
    
    #include <MySensors.h>
    #include <SPI.h>
    #include <Bounce2.h>
    #define RELAY_ON 0                      // switch around for ACTIVE LOW / ACTIVE HIGH relay
    #define RELAY_OFF 1
    //
    
    #define noRelays 2                     //2-4
    const int relayPin[] = {14,15};          //  switch around pins to your desire
    const int buttonPin[] = {3,4};      //  switch around pins to your desire
    
    class Relay             // relay class, store all relevant data (equivalent to struct)
    {
    public:                                      
      int buttonPin;                   // physical pin number of button
      int relayPin;             // physical pin number of relay
      boolean relayState;               // relay status (also stored in EEPROM)
    };
    
    Relay Relays[noRelays]; 
    Bounce debouncer[noRelays];
    MyMessage msg[noRelays];
    
    void setup(){
        sendHeartbeat();
        wait(100);
        // Initialize Relays with corresponding buttons
        for (int i = 0; i < noRelays; i++){
        Relays[i].buttonPin = buttonPin[i];              // assign physical pins
        Relays[i].relayPin = relayPin[i];
        msg[i].sensor = i;                                   // initialize messages
        msg[i].type = V_LIGHT;   
        pinMode(Relays[i].buttonPin, INPUT_PULLUP);
        wait(100);
        pinMode(Relays[i].relayPin, OUTPUT);
        Relays[i].relayState = loadState(i);                               // retrieve last values from EEPROM
        digitalWrite(Relays[i].relayPin, Relays[i].relayState? RELAY_ON:RELAY_OFF);   // and set relays accordingly
        send(msg[i].set(Relays[i].relayState? true : false));                  // make controller aware of last status  
        wait(50);
        debouncer[i] = Bounce();                        // initialize debouncer
        debouncer[i].attach(buttonPin[i]);
        debouncer[i].interval(20);
        wait(50);
        }
    }
    void presentation()  {
          sendSketchInfo("MultiRelayButton", "1.0");
          wait(100);
          for (int i = 0; i < noRelays; i++)
          present(i, S_LIGHT);                               // present sensor to gateway
          wait(100);
    }
    void loop()
    {
        for (byte i = 0; i < noRelays; i++) {
            if (debouncer[i].update()) {
                Relays[i].relayState = !Relays[i].relayState;
                digitalWrite(Relays[i].relayPin, Relays[i].relayState?RELAY_ON:RELAY_OFF);
                send(msg[i].set(Relays[i].relayState? true : false));
                // save sensor state in EEPROM (location == sensor number)
                saveState( i, Relays[i].relayState );
            }                 
        }
        wait(20);
    }
    // process incoming message 
    void receive(const MyMessage &message){        
       if (message.type == V_LIGHT){ 
       if (message.sensor <noRelays){            // check if message is valid for relays..... previous line  [[[ if (message.sensor <=noRelays){ ]]]
       Relays[message.sensor].relayState = message.getBool(); 
       digitalWrite(Relays[message.sensor].relayPin, Relays[message.sensor].relayState? RELAY_ON:RELAY_OFF); // and set relays accordingly
       saveState( message.sensor, Relays[message.sensor].relayState ); // save sensor state in EEPROM (location == sensor number)
       }
      }
      wait(20);
    }
    Troubleshooting

  • Remote Access
    N niccodemi

    @Mitja-Blazinsek I had similar issue. I found the cause was port 8443 itself. When I changed Mycontroller config to use another port (8442 or 8444) and opened it, I was able to access Mycontroller from external networks.

    MyController.org

  • How to scan rf remote
    N niccodemi

    as emc2 said; alternatively if rc-switch doesn't work for you (unlikely) you can also try with Remoteswitch library.

    Development

  • Anyone tried the $199 Monoprice 3D printer?
    N niccodemi

    @NeverDie they do, but many people don't notice it or find it unbearable. It also depends on type of filament; ABS smells like hot plastic, PLA like something sweet (it is derived from sugar). I keep mine in the house but I put it inside DIY enclosure - mainly to improve ABS printing quality but as side effect it also contains smell.

    Enclosures / 3D Printing

  • Remote Access
    N niccodemi

    @Velo17 I am still on IPv4. I use DDClient as an update agent. I think it works with majority of providers such as NO-IP and DYNU.

    MyController.org

  • Remote Access
    N niccodemi

    @Velo17 One of my linux servers is also behind double NAT network but I can still use DDNS service however update client has to be installed / configured on the server itself not on the router.

    Other option (if you are running Raspbian) would be Teamviewer.

    MyController.org

  • Rain Guage
    N niccodemi

    @mrc-core Remove folder "Time" from your libraries folder, then download the "MySensorsArduinoExamples" zip from this link and extract Time library to your libraries folder. Restart Arduino IDE and try again.

    My Project

  • Rain Guage
    N niccodemi

    @mrc-core is this the sketch you are using?

    /*
     Arduino Tipping Bucket Rain Gauge
    
     April 26, 2015
    
     Version 1.4.1 alpha
    
     Arduino Tipping Bucket Rain Gauge
    
     Utilizing a tipping bucket sensor, your Vera home automation controller and the MySensors.org
     gateway you can measure and sense local rain.  This sketch will create two devices on your
     Vera controller.  One will display your total precipitation for the last 5 days.  The other, 
     a sensor that changes state if there is recent rain (up to last 120 hours)  above a threshold.  
     Both these settings are user definable.
    
     There is a build overview video here: https://youtu.be/1eMfKQaLROo
    
     This sketch features the following:
    
     * Allows you to set the rain threshold in mm
     * Allows you to determine the tripped indicator window up to 120 hours.
     * Displays the last 5 days of rain in Variable1 through Variable5
       of the Rain Sensor device
     * Configuration changes to Sensor device updated every hour
     * Should run on any Arduino
     * Will retain Tripped/Not Tripped status and data in a power interruption, saving small amount
       of data to EEPROM (Circular Buffer to maximize life of EEPROM)
     * LED status indicator
     * Optional Temp/Humidity (DHT-22 or DHT-11) and Light LUX (BH1750) sensors. To use, uncomment
       #define DHT_ON  and/or #define LUX_ON
     * Optionally send total accumulation of each day's rainfall or send only individual days rainfall totals.
       Comment out #define USE_DAILY to display individual daily rainfall.
    
     by @BulldogLowell and @PeteWill for free public use
    
     */
    
    // 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 7
    
    #include <SPI.h>
    #include <MySensors.h>
    #include <math.h>
    #include <Time.h>
    
    #define SKETCH_NAME "Rain Gauge"
    #define SKETCH_VERSION "1.4.1a"
    
    #define DWELL_TIME 125  // this allows for radio to come back to power after a transmission, ideally 0 
    
    //#define DEBUG_ON  // comment out this line to disable serial debug
    #define DHT_ON // uncomment out this line to enable DHT sensor
    #define LUX_ON // uncomment out this line to enable BH1750 sensor
    //#define USE_DAILY // displays each time segment as an accumulation of prior periods inclusive.  Comment out to display individual daily rainfall totals in the variables sent to your controller.
    
    #define TIP_SENSOR_PIN 3
    
    #define CALIBRATE_FACTOR 60 // amount of rain per rain bucket tip e.g. 5 is .05mm
    #define DHT_LUX_DELAY 300000  //Delay in milliseconds that the DHT and LUX sensors will wait before sending data
    
    #define CHILD_ID_RAIN_LOG 3  // Keeps track of accumulated rainfall
    #define CHILD_ID_TRIPPED_INDICATOR 4  // Indicates Tripped when rain detected
    #define EEPROM_BUFFER_LOCATION 0  // location of the EEPROM circular buffer
    #define E_BUFFER_LENGTH 240
    #define RAIN_BUCKET_SIZE 120
    
    #ifdef  DEBUG_ON
      #define DEBUG_PRINT(x)   Serial.print(x)
      #define DEBUG_PRINTLN(x) Serial.println(x)
      #define SERIAL_START(x)  Serial.begin(x)
      #else
      #define DEBUG_PRINT(x)
      #define DEBUG_PRINTLN(x)
      #define SERIAL_START(x)
    #endif
    //
    MyMessage msgRainRate(CHILD_ID_RAIN_LOG, V_RAINRATE);
    MyMessage msgRain(CHILD_ID_RAIN_LOG, V_RAIN);
    //
    MyMessage msgRainVAR1(CHILD_ID_RAIN_LOG, V_VAR1);
    MyMessage msgRainVAR2(CHILD_ID_RAIN_LOG, V_VAR2);
    MyMessage msgRainVAR3(CHILD_ID_RAIN_LOG, V_VAR3);
    MyMessage msgRainVAR4(CHILD_ID_RAIN_LOG, V_VAR4);
    MyMessage msgRainVAR5(CHILD_ID_RAIN_LOG, V_VAR5);
    //
    MyMessage msgTripped(CHILD_ID_TRIPPED_INDICATOR, V_TRIPPED);
    MyMessage msgTrippedVar1(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
    MyMessage msgTrippedVar2(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
    //
    #ifdef DHT_ON
      #include <DHT.h>
      #define CHILD_ID_HUM 0
      #define CHILD_ID_TEMP 1
      #define HUMIDITY_SENSOR_DIGITAL_PIN 8
      DHT dht;
      float lastTemp;
      float lastHum;
      boolean metric = true;
      MyMessage msgHum(CHILD_ID_HUM, V_HUM);
      MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    #endif
    //
    #ifdef LUX_ON
      //BH1750 is connected to SCL (analog input A5) and SDA (analog input A4)
      #include <BH1750.h>
      #include <Wire.h>
      #define CHILD_ID_LIGHT 2
      BH1750 lightSensor;
      MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL);
      unsigned int lastlux;
      byte heartbeat = 10; //Used to send the light lux to gateway as soon as the device is restarted and after the DHT_LUX_DELAY has happened 10 times
    #endif
    unsigned long sensorPreviousMillis;
    int eepromIndex;
    int ledPin = 5; // Pin the LED is connected to.  PWM capable pin required
    unsigned long dataMillis;
    unsigned long serialInterval = 600000UL;
    const unsigned long oneHour = 3600000UL;
    unsigned long lastTipTime;
    unsigned long lastRainTime; //Used for rainRate calculation
    unsigned int rainBucket [RAIN_BUCKET_SIZE] ; /* 24 hours x 5 Days = 120 hours */
    unsigned int rainRate = 0;
    byte rainWindow = 72;         //default rain window in hours.  Will be overwritten with msgTrippedVar1.
    volatile int wasTippedBuffer = 0;
    int rainSensorThreshold = 50; //default rain sensor sensitivity in hundredths.  Will be overwritten with msgTrippedVar2.
    byte state = 0;
    byte oldState = -1;
    unsigned int lastRainRate = 0;
    int lastMeasure = 0;
    boolean gotTime = false;
    byte lastHour;
    byte currentHour;
    //
    void setup()
    {
      SERIAL_START(115200);
      //
      // Set up the IO
      pinMode(TIP_SENSOR_PIN, INPUT_PULLUP);
      attachInterrupt (digitalPinToInterrupt(TIP_SENSOR_PIN), sensorTipped, FALLING);  // depending on location of the hall effect sensor may need CHANGE
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, HIGH);
      //
      //Sync time with the server, this will be called hourly in order to keep time from creeping with the crystal
      //
      unsigned long functionTimeout = millis();
      while (timeStatus() == timeNotSet && millis() - functionTimeout < 30000UL)
      {
        requestTime();
        DEBUG_PRINTLN(F("Getting Time"));
        wait(1000); // call once per second
        DEBUG_PRINTLN(F("."));
      }
      currentHour = hour();
      lastHour = hour();
      //
      //retrieve from EEPROM stored values on a power cycle.
      //
      boolean isDataOnEeprom = false;
      for (int i = 0; i < E_BUFFER_LENGTH; i++)
      {
        byte locator = loadState(EEPROM_BUFFER_LOCATION + i);
        if (locator == 0xFE)  // found the EEPROM circular buffer index
        {
          eepromIndex = EEPROM_BUFFER_LOCATION + i;
          DEBUG_PRINT(F("EEPROM Index "));
          DEBUG_PRINTLN(eepromIndex);
          //Now that we have the buffer index let's populate the rainBucket[] with data from eeprom
          loadRainArray(eepromIndex);
          isDataOnEeprom = true;
          break;
        }
      }
      //
      if (!isDataOnEeprom) // Added for the first time it is run on a new Arduino
      {
        DEBUG_PRINTLN(F("I didn't find valid EEPROM Index, so I'm writing one to location 0"));
        eepromIndex = EEPROM_BUFFER_LOCATION;
        saveState(eepromIndex, 0xFE);
        saveState(eepromIndex + 1, 0xFE);
        //then I will clear out any bad data
        for (int i = 2; i <= E_BUFFER_LENGTH; i++)
        {
          saveState(i, 0x00);
        }
      }
      dataMillis = millis();
      lastTipTime = millis() - oneHour; //why is this -oneHour?? Doesn't millis() start at 0 when first powered on?
      //
      request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
      wait(DWELL_TIME);
      request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
      wait(DWELL_TIME);
      //
    #ifdef DHT_ON
      dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN);
      wait(DWELL_TIME);
      metric = getConfig().isMetric;
    #endif
      //
    #ifdef LUX_ON
      wait(DWELL_TIME);
      lightSensor.begin();
    #endif
      //
      DEBUG_PRINTLN(F("Radio Setup Complete!"));
      transmitRainData();
    }
    
    
    void presentation()  {
      // Register all sensors to gw (they will be created as child devices)
      sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
      wait(DWELL_TIME);
      present(CHILD_ID_RAIN_LOG, S_RAIN);
      wait(DWELL_TIME);
      present(CHILD_ID_TRIPPED_INDICATOR, S_MOTION);
      wait(DWELL_TIME);
    
    #ifdef DHT_ON
      present(CHILD_ID_HUM, S_HUM);
      wait(DWELL_TIME);
      present(CHILD_ID_TEMP, S_TEMP);
      wait(DWELL_TIME);
    #endif
    
    
    #ifdef LUX_ON
      present(CHILD_ID_LIGHT, S_LIGHT_LEVEL);
    #endif
    
      DEBUG_PRINTLN(F("Sensor Presentation Complete"));
    }
    
    void loop()
    {
      if (state)
      {
        prettyFade();  // breathe if tripped
      }
      else
      {
        slowFlash();   // blink if not tripped
      }
    #ifdef DEBUG_ON  // Serial Debug Block
      if ( (millis() - dataMillis) >= serialInterval)
      {
        for (int i = 24; i <= 120; i = i + 24)
        {
          updateSerialData(i);
        }
        dataMillis = millis();
      }
    #endif
      //
      // let's constantly check to see if the rain in the past rainWindow hours is greater than rainSensorThreshold
      //
      int measure = 0; // Check to see if we need to show sensor tripped in this block
      for (int i = 0; i < rainWindow; i++)
      {
        measure += rainBucket [i];
        if (measure != lastMeasure)
        {
          //      DEBUG_PRINT(F("measure value (total rainBucket within rainWindow): "));
          //      DEBUG_PRINTLN(measure);
          lastMeasure = measure;
        }
      }
      //
      state = (measure >= (rainSensorThreshold * 100));
      if (state != oldState)
      {
        send(msgTripped.set(state));
        wait(DWELL_TIME);
        DEBUG_PRINT(F("New Sensor State... Sensor: "));
        DEBUG_PRINTLN(state ? "Tripped" : "Not Tripped");
        oldState = state;
      }
      //
      unsigned long tipDelay = millis() - lastRainTime;
      if (wasTippedBuffer) // if was tipped, then update the 24hour total and transmit to Vera
      {
        DEBUG_PRINTLN(F("Sensor Tipped"));
        DEBUG_PRINT(F("rainBucket [0] value: "));
        DEBUG_PRINTLN(rainBucket [0]);
        send(msgRain.set((float)rainTotal(currentHour) / 100, 1)); //Calculate the total rain for the day
        wait(DWELL_TIME);
        wasTippedBuffer--;
        rainRate = ((oneHour) / tipDelay);
        if (rainRate != lastRainRate)
        {
          send(msgRainRate.set(rainRate, 1));
          wait(DWELL_TIME);
          DEBUG_PRINT(F("RainRate= "));
          DEBUG_PRINTLN(rainRate);
          lastRainRate = rainRate;
        }
        lastRainTime = lastTipTime;
      }
      //
      currentHour = hour();
      if (currentHour != lastHour)
      {
        DEBUG_PRINTLN(F("One hour elapsed."));
        send(msgRain.set((float)rainTotal(currentHour) / 100, 1)); // send today's rainfall
        wait(DWELL_TIME);
        saveState(eepromIndex, highByte(rainBucket[0]));
        saveState(eepromIndex + 1, lowByte(rainBucket[0]));
        DEBUG_PRINT(F("Saving rainBucket[0] to eeprom. rainBucket[0] = "));
        DEBUG_PRINTLN(rainBucket[0]);
        for (int i = RAIN_BUCKET_SIZE - 1; i >= 0; i--)//cascade an hour of values back into the array
        {
          rainBucket [i + 1] = rainBucket [i];
        }
        request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
        wait(DWELL_TIME);
        request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
        wait(DWELL_TIME);
        rainBucket[0] = 0;
        eepromIndex = eepromIndex + 2;
        if (eepromIndex > EEPROM_BUFFER_LOCATION + E_BUFFER_LENGTH)
        {
          eepromIndex = EEPROM_BUFFER_LOCATION;
        }
        DEBUG_PRINT(F("Writing to EEPROM.  Index: "));
        DEBUG_PRINTLN(eepromIndex);
        saveState(eepromIndex, 0xFE);
        saveState(eepromIndex + 1, 0xFE);
        requestTime(); // sync the time every hour
        wait(DWELL_TIME);
        transmitRainData();
        rainRate = 0;
        send(msgRainRate.set(rainRate, 1));
        wait(DWELL_TIME);
        DEBUG_PRINTLN(F("Sending rainRate is 0 to controller"));
        lastHour = currentHour;
      }
      if (millis() - sensorPreviousMillis > DHT_LUX_DELAY)
      {
        #ifdef DHT_ON  //DHT Code
          doDHT();
        #endif
        #ifdef LUX_ON
          doLUX();
        #endif
        sensorPreviousMillis = millis();
      }
    }
    //
    #ifdef DHT_ON
    void doDHT(void)
    {
      float temperature = dht.getTemperature();
        if (isnan(temperature)) 
        {
          DEBUG_PRINTLN(F("Failed reading temperature from DHT"));
        } else if (temperature != lastTemp) 
        {
          lastTemp = temperature;
          if (!metric) 
          {
            temperature = dht.toFahrenheit(temperature);
          }
          send(msgTemp.set(temperature, 1));
          wait(DWELL_TIME);
          DEBUG_PRINT(F("Temperature is: "));
          DEBUG_PRINTLN(temperature);
        }
        float humidity = dht.getHumidity();;
        if (isnan(humidity)) 
        {
          DEBUG_PRINTLN(F("Failed reading humidity from DHT"));
        } else if (humidity != lastHum) 
        {
          lastHum = humidity;
          send(msgHum.set(humidity, 1));
          wait(DWELL_TIME);
          DEBUG_PRINT(F("Humidity is: "));
          DEBUG_PRINTLN(humidity);
        }
    }
    #endif
    //
    #ifdef LUX_ON
    void doLUX(void)
    {
      unsigned int lux = lightSensor.readLightLevel();// Get Lux value
      DEBUG_PRINT(F("Current LUX Level: "));
      DEBUG_PRINTLN(lux);
      heartbeat++;
      if (lux != lastlux || heartbeat > 10) 
      {
        send(msg.set(lux));
        lastlux = lux;
      }
      if (heartbeat > 10) 
      {
        heartbeat = 0;
      }
    }
    #endif
    //
    void sensorTipped()
    {
      unsigned long thisTipTime = millis();
      if (thisTipTime - lastTipTime > 100UL)
      {
        rainBucket[0] += CALIBRATE_FACTOR; // adds CALIBRATE_FACTOR hundredths of unit each tip
        wasTippedBuffer++;
      }
      lastTipTime = thisTipTime;
    }
    //
    int rainTotal(int hours)
    {
      int total = 0;
      for ( int i = 0; i <= hours; i++)
      {
        total += rainBucket [i];
      }
      return total;
    }
    
    void updateSerialData(int x)
    {
      DEBUG_PRINT(F("Rain last "));
      DEBUG_PRINT(x);
      DEBUG_PRINTLN(F(" hours: "));
      float tipCount = 0;
      for (int i = 0; i < x; i++)
      {
        tipCount = tipCount + rainBucket [i];
      }
      tipCount = tipCount / 100;
      DEBUG_PRINTLN(tipCount);
    }
    
    void loadRainArray(int value) // retrieve stored rain array from EEPROM on powerup
    {
      for (int i = 0; i < RAIN_BUCKET_SIZE; i++)
      {
        value = value - 2;
        if (value < EEPROM_BUFFER_LOCATION)
        {
          value = EEPROM_BUFFER_LOCATION + E_BUFFER_LENGTH;
        }
        DEBUG_PRINT(F("EEPROM location: "));
        DEBUG_PRINTLN(value);
        byte rainValueHigh = loadState(value);
        byte rainValueLow = loadState(value + 1);
        unsigned int rainValue = rainValueHigh << 8;
        rainValue |= rainValueLow;
        rainBucket[i + 1] = rainValue;
        //
        DEBUG_PRINT(F("rainBucket[ value: "));
        DEBUG_PRINT(i + 1);
        DEBUG_PRINT(F("] value: "));
        DEBUG_PRINTLN(rainBucket[i + 1]);
      }
    }
    
    void transmitRainData(void)
    {
      DEBUG_PRINT(F("In transmitRainData. currentHour = "));
      DEBUG_PRINTLN(currentHour);
      int rainUpdateTotal = 0;
      for (int i = currentHour; i >= 0; i--)
      {
        rainUpdateTotal += rainBucket[i];
        DEBUG_PRINT(F("Adding rainBucket["));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F("] to rainUpdateTotal."));
      }
      DEBUG_PRINT(F("TX Day 1: rainUpdateTotal = "));
      DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
      send(msgRainVAR1.set((float)rainUpdateTotal / 100.0, 1)); //Send current day rain totals (resets at midnight)
      wait(DWELL_TIME);
    #ifdef USE_DAILY
      rainUpdateTotal = 0;
    #endif
      for (int i = currentHour + 24; i > currentHour; i--)
      {
        rainUpdateTotal += rainBucket[i];
        DEBUG_PRINT(F("Adding rainBucket["));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F("] to rainUpdateTotal."));
      }
      DEBUG_PRINT(F("TX Day 2: rainUpdateTotal = "));
      DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
      send(msgRainVAR2.set((float)rainUpdateTotal / 100.0, 1));
      wait(DWELL_TIME);
    #ifdef USE_DAILY
      rainUpdateTotal = 0;
    #endif
      for (int i = currentHour + 48; i > currentHour + 24; i--)
      {
        rainUpdateTotal += rainBucket[i];
        DEBUG_PRINT(F("Adding rainBucket["));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F("] to rainUpdateTotal."));
      }
      DEBUG_PRINT(F("TX Day 3: rainUpdateTotal = "));
      DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
      send(msgRainVAR3.set((float)rainUpdateTotal / 100.0, 1));
      wait(DWELL_TIME);
    #ifdef USE_DAILY
      rainUpdateTotal = 0;
    #endif
      for (int i = currentHour + 72; i > currentHour + 48; i--)
      {
        rainUpdateTotal += rainBucket[i];
        DEBUG_PRINT(F("Adding rainBucket["));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F("] to rainUpdateTotal."));
      }
      DEBUG_PRINT(F("TX Day 4: rainUpdateTotal = "));
      DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
      send(msgRainVAR4.set((float)rainUpdateTotal / 100.0, 1));
      wait(DWELL_TIME);
    #ifdef USE_DAILY
      rainUpdateTotal = 0;
    #endif
      for (int i = currentHour + 96; i > currentHour + 72; i--)
      {
        rainUpdateTotal += rainBucket[i];
        DEBUG_PRINT(F("Adding rainBucket["));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F("] to rainUpdateTotal."));
      }
      DEBUG_PRINT(F("TX Day 5: rainUpdateTotal = "));
      DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
      send(msgRainVAR5.set((float)rainUpdateTotal / 100.0, 1));
      wait(DWELL_TIME);
    }
    
    void receive(const MyMessage &message)
    {
      if (message.sensor == CHILD_ID_RAIN_LOG)
      {
        // nothing to do here
      }
      else if (message.sensor == CHILD_ID_TRIPPED_INDICATOR)
      {
        if (message.type == V_VAR1)
        {
          rainWindow = atoi(message.data);
          if (rainWindow > 120)
          {
            rainWindow = 120;
          }
          else if (rainWindow < 1)
          {
            rainWindow = 1;
          }
          if (rainWindow != atoi(message.data))   // if I changed the value back inside the boundries, push that number back to Vera
          {
            send(msgTrippedVar1.set(rainWindow));
          }
        }
        else if (message.type == V_VAR2)
        {
          rainSensorThreshold = atoi(message.data);
          if (rainSensorThreshold > 10000)
          {
            rainSensorThreshold = 10000;
          }
          else if (rainSensorThreshold < 1)
          {
            rainSensorThreshold = 1;
          }
          if (rainSensorThreshold != atoi(message.data))  // if I changed the value back inside the boundries, push that number back to Vera
          {
            send(msgTrippedVar2.set(rainSensorThreshold));
          }
        }
      }
    }
    
    void prettyFade(void)
    {
      float val = (exp(sin(millis() / 2000.0 * PI)) - 0.36787944) * 108.0;
      analogWrite(ledPin, val);
    }
    
    void slowFlash(void)
    {
      static boolean ledState = true;
      static unsigned long pulseStart = millis();
      if (millis() - pulseStart < 100UL)
      {
        digitalWrite(ledPin, !ledState);
        pulseStart = millis();
      }
    }
    
    void receiveTime(unsigned long time)
    {
      DEBUG_PRINTLN(F("Time received..."));
      setTime(time);
      char theTime[6];
      sprintf(theTime, "%d:%2d", hour(), minute());
      DEBUG_PRINTLN(theTime);
    }
    

    It compiles fine with Arduino IDE 1.6.5, Mysensors 2.0.0 and libraries (Time, BH1750).

    My Project

  • Upgrading to 2.0 sketch dificulty
    N niccodemi

    @andmaster

    I've used below sketch with 1.6 development version; it compiles also with 2.0.0 but I have not tested it. This sketch uses toggle buttons.

    //MultiRelayButton Sketch, MySensors 1.6, toggle switch
    
    #define MY_RADIO_NRF24
    
    #define MY_REPEATER_FEATURE
    
    #include <MySensors.h>
    #include <SPI.h>
    #include <Bounce2.h>
    #define RELAY_ON 0                      // switch around for ACTIVE LOW / ACTIVE HIGH relay
    #define RELAY_OFF 1                     // switch around for ACTIVE LOW / ACTIVE HIGH relay
    //
    
    #define noRelays 4                     //2-4, define number of relays
    const int relayPin[] = {14,15,16,17};          //  relay pins - should match noRelays
    const int buttonPin[] = {3,4,5,6};      //  button pins - should match noRelays
    
    class Relay             // relay class, store all relevant data (equivalent to struct)
    {
    public:                                      
      int buttonPin;                   // physical pin number of button
      int relayPin;             // physical pin number of relay
      boolean relayState;               // relay status (also stored in EEPROM)
    };
    
    Relay Relays[noRelays]; 
    Bounce debouncer[noRelays];
    MyMessage msg[noRelays];
    
    void setup(){
        sendHeartbeat();
        wait(100);
        // Initialize Relays with corresponding buttons
        for (int i = 0; i < noRelays; i++){
        Relays[i].buttonPin = buttonPin[i];              // assign physical pins
        Relays[i].relayPin = relayPin[i];
        msg[i].sensor = i;                                   // initialize messages
        msg[i].type = V_LIGHT;   
        pinMode(Relays[i].buttonPin, INPUT_PULLUP);
        wait(100);
        pinMode(Relays[i].relayPin, OUTPUT);
        Relays[i].relayState = loadState(i);                               // retrieve last values from EEPROM
        digitalWrite(Relays[i].relayPin, Relays[i].relayState? RELAY_ON:RELAY_OFF);   // and set relays accordingly
        send(msg[i].set(Relays[i].relayState? true : false));                  // make controller aware of last status  
        wait(50);
        debouncer[i] = Bounce();                        // initialize debouncer
        debouncer[i].attach(buttonPin[i]);
        debouncer[i].interval(20);
        wait(50);
        }
    }
    void presentation()  {
          sendSketchInfo("MultiRelayButton", "1.0");
          wait(100);
          for (int i = 0; i < noRelays; i++)
          present(i, S_LIGHT);                               // present sensor to gateway
          wait(100);
    }
    void loop()
    {
        for (byte i = 0; i < noRelays; i++) {
            if (debouncer[i].update()) {
                Relays[i].relayState = !Relays[i].relayState;
                digitalWrite(Relays[i].relayPin, Relays[i].relayState?RELAY_ON:RELAY_OFF);
                send(msg[i].set(Relays[i].relayState? true : false));
                // save sensor state in EEPROM (location == sensor number)
                saveState( i, Relays[i].relayState );
            }                 
        }
        wait(20);
    }
    // process incoming message 
    void receive(const MyMessage &message){        
       if (message.type == V_LIGHT){ 
       if (message.sensor <noRelays){            // check if message is valid for relays..... previous line  [[[ if (message.sensor <=noRelays){ ]]]
       Relays[message.sensor].relayState = message.getBool(); 
       digitalWrite(Relays[message.sensor].relayPin, Relays[message.sensor].relayState? RELAY_ON:RELAY_OFF); // and set relays accordingly
       saveState( message.sensor, Relays[message.sensor].relayState ); // save sensor state in EEPROM (location == sensor number)
       }
      }
      wait(20);
    }
    
    Troubleshooting

  • ESP8266 OTA (SOLVED)
    N niccodemi

    @mfalkvidd I reinstalled Arduino IDE and libraries and that seems to fixed the issue.

    Troubleshooting
  • Login

  • Don't have an account? Register

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