Navigation

    • Register
    • Login
    • OpenHardware.io
    • Categories
    • Recent
    • Tags
    • Popular
    1. Home
    2. flopp
    3. Best
    • Profile
    • Following
    • Followers
    • Topics
    • Posts
    • Best
    • Groups

    Best posts made by flopp

    • Solar Powered Soil Moisture Sensor

      I have build an Solar panel-powered Soil moisture sensor.

      Photos

      I bought the lamps on Jula.
      Lamp1 Battery 2/3 AAA 100 mAh, 10 SEK, 1 euro
      Lamp2 Battery 2/3 AA 200 mAh, 5 SEK, 0,5 euro
      Lamp3 Battery LR44 40 mAh, 10 SEK, 1 euro, NOT TESTED YET

      I removed all the electronic on the PCB and used the PCB as a connection board.
      The solar panel gives around 1,4 V during a very sunny day.
      I had to add a step-up(0,8->3,3V) to be able to run a ATMEGA. My first idea was to connect 2 batteries in series, but that was too much work. Now everything fits in the parts that is included.

      Lamp1 is using a Pro Mini(fake), glued soil sensor on "arrow"
      Lamp2 is using my designed PCB with ATMEGA328p, soil sensor just put in soil, not glued at all.
      Both MCU are using Optiboot, https://forum.mysensors.org/topic/3018/tutorial-how-to-burn-1mhz-8mhz-bootloader-using-arduino-ide-1-6-5-r5.
      Pro Mini:Power-on LED removed and also step-down. Activity-LED is still in use.
      My designed PCB:https://oshpark.com/shared_projects/F7esJEMY, also with LED for startup and send OK

      I am using @mfalkvidd sketch, thank you. I have only add a few rows(LED and resend function)
      It sends data(Humidity/Volt/VoltPercent every 10 second, just for testing the hardware later on I will send maybe twice an hour or once an hour.
      I am measuring the battery voltage on a analog input.

      #include <SPI.h>
      #include <MySensor.h>
      
      #define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
      #define N_ELEMENTS(array) (sizeof(array)/sizeof((array)[0]))
      
      #define CHILD_ID_MOISTURE 0
      #define CHILD_ID_BATTERY 1
      #define SLEEP_TIME 10000 // Sleep time between reads (in milliseconds)
      #define THRESHOLD 1.1 // Only make a new reading with reverse polarity if the change is larger than 10%.
      #define STABILIZATION_TIME 1000 // Let the sensor stabilize before reading
      default BOD settings.
      const int SENSOR_ANALOG_PINS[] = {A4, A5}; // Sensor is connected to these two pins. Avoid A3 if using ATSHA204. A6 and A7 cannot be used because they don't have pullups.
      
      MySensor gw;
      MyMessage msg(CHILD_ID_MOISTURE, V_HUM);
      MyMessage voltage_msg(CHILD_ID_BATTERY, V_VOLTAGE);
      long oldvoltage = 0;
      byte direction = 0;
      int oldMoistureLevel = -1;
      float batteryPcnt;
      float batteryVolt;
      int LED = 5;
      
      void setup()
      {
        pinMode(LED, OUTPUT);
        digitalWrite(LED, HIGH);
        delay(200);
        digitalWrite(LED, LOW);
        delay(200);
        digitalWrite(LED, HIGH);
        delay(200);
        digitalWrite(LED, LOW);
        
        gw.begin();
      
        gw.sendSketchInfo("Plant moisture w solar", "1.0");
      
        gw.present(CHILD_ID_MOISTURE, S_HUM);
        delay(250);
        gw.present(CHILD_ID_BATTERY, S_MULTIMETER);
        for (int i = 0; i < N_ELEMENTS(SENSOR_ANALOG_PINS); i++) {
          pinMode(SENSOR_ANALOG_PINS[i], OUTPUT);
          digitalWrite(SENSOR_ANALOG_PINS[i], LOW);
        }
      }
      
      void loop()
      {
        int moistureLevel = readMoisture();
      
        // Send rolling average of 2 samples to get rid of the "ripple" produced by different resistance in the internal pull-up resistors
        // See http://forum.mysensors.org/topic/2147/office-plant-monitoring/55 for more information
        if (oldMoistureLevel == -1) { // First reading, save current value as old
          oldMoistureLevel = moistureLevel;
        }
        if (moistureLevel > (oldMoistureLevel * THRESHOLD) || moistureLevel < (oldMoistureLevel / THRESHOLD)) {
          // The change was large, so it was probably not caused by the difference in internal pull-ups.
          // Measure again, this time with reversed polarity.
          moistureLevel = readMoisture();
        }
        gw.send(msg.set((moistureLevel + oldMoistureLevel) / 2.0 / 10.23, 1));
        oldMoistureLevel = moistureLevel;
        
        int sensorValue = analogRead(A0);
        Serial.println(sensorValue);
        float voltage=sensorValue*(3.3/1023);
        Serial.println(voltage);
        batteryPcnt = (sensorValue - 248) * 0.72;
        batteryVolt = voltage;
        gw.sendBatteryLevel(batteryPcnt);
        resend((voltage_msg.set(batteryVolt, 3)), 10);
      
        digitalWrite(LED, HIGH);
        delay(200);
        digitalWrite(LED, LOW);
        
        gw.sleep(SLEEP_TIME);
      }
      
      void resend(MyMessage &msg, int repeats)
      {
        int repeat = 1;
        int repeatdelay = 0;
        boolean sendOK = false;
      
        while ((sendOK == false) and (repeat < repeats)) {
          if (gw.send(msg)) {
            sendOK = true;
          } else {
            sendOK = false;
            Serial.print("Error ");
            Serial.println(repeat);
            repeatdelay += 500;
          } repeat++; delay(repeatdelay);
        }
      }
      
      
      int readMoisture() {
        pinMode(SENSOR_ANALOG_PINS[direction], INPUT_PULLUP); // Power on the sensor
        analogRead(SENSOR_ANALOG_PINS[direction]);// Read once to let the ADC capacitor start charging
        gw.sleep(STABILIZATION_TIME);
        int moistureLevel = (1023 - analogRead(SENSOR_ANALOG_PINS[direction]));
      
        // Turn off the sensor to conserve battery and minimize corrosion
        pinMode(SENSOR_ANALOG_PINS[direction], OUTPUT);
        digitalWrite(SENSOR_ANALOG_PINS[direction], LOW);
      
        direction = (direction + 1) % 2; // Make direction alternate between 0 and 1 to reverse polarity which reduces corrosion
        return moistureLevel;
      }
      
      

      0_1465299264398_IMG_1337.JPG
      0_1465928822164_SolarPanel (2).png

      posted in My Project
      flopp
      flopp
    • RE: Merry X-mas and Happy New 2018

      Merry Christmas and a Happy New Year and as thank you I donated some money to you.

      posted in Announcements
      flopp
      flopp
    • LUA, send email when device has not report

      I had lots of problem for my nodes that they sometimes didn't send data and I could never know when, I wanted to know when it happen just to know if I did something with Domoticz or something else I did.
      This script will read when the Device sent data last time and if it is more than 30 minutes Domoticz will send me an email, when the Device has sent within 30 minutes it send a new email. I now have 100% control when it is not working.
      I also add a function to write to a file, so I could see if it stopped working on same time of day or it was something else.
      I have written the file content to be possible to view in a PHP file, to see the OK and NOT OK easier

      PHP file looks like this

      <html>
      <head>
      <title>Title</title>
      <body bgcolor="white">
      <meta http-equiv="Content-Type" content="text/html;charset=utf-8" / >
      </head>
      
      <?php
          $myfilename = "c:\progra~2\domoticz\sensor.txt";
          if(file_exists($myfilename)){
            echo file_get_contents($myfilename);
          }
      ?>
      </html>
      

      picture how it looks in PHP
      0_1466712672460_sensor.png

      Translation first row
      YYYY-MM-DD HH:MM:SS No data for 40 minutes from "device", last data was YYYY-MM-DD HH:MM:SS
      Translation seconds row
      Data from "device" is OK again, last data YYYY-MM-DD HH:MM:SS

      In Domoticz create a new Event, LUA and Device as trigger
      You also need to create a Variable(integer) with the same name as the Device, value=0
      Name your device a unique name, like "flopp" 🙂 when it works you can rename it
      LUA code

      commandArray = {}
      local function update(cmd)
      vari = "Variable:"  .. cmd --add Variable: before device
      t1 = os.time() --get date/time right now in seconds
      t3  = os.date("%Y-%m-%d %H:%M:%S") --get date/time right now in normal format
      s = otherdevices_lastupdate[cmd] --read last date/time for device
      --print(cmd)
      --print(s)
      year = string.sub(s, 1, 4)
      month = string.sub(s, 6, 7)
      day = string.sub(s, 9, 10)
      hour = string.sub(s, 12, 13)
      minutes = string.sub(s, 15, 16)
      seconds = string.sub(s, 18, 19)
      
      t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
      difference = (os.difftime (t1, t2)) --compare right now with device
      
      if (difference > 2400) and (uservariables[cmd] == 0) then --if device date/time is more than 30 minutes
          file = io.open("sensor.txt", "a") -- Opens a file named sensor.txt(stored under Domoticz folder) in append mode
          commandArray['SendEmail']=''..cmd..' äldre än 40 min#'..s..' är senaste tid#abc@hotmail.com' --send mail
          commandArray[vari] = "1" --set variable to 1
          --write to opened file
          file:write(t3 .. " Ingen data på 40 min från ")
          file:write("<font color=red>")
          file:write(cmd .."</font>")
          file:write(", senaste data " .. s .."<br>","\n")
          file:close() --closes the open file
          
      elseif (difference < 2400) and (uservariables[cmd] == 1) then --if device date/time is less than 30 minutes
          file = io.open("sensor.txt", "a")
          commandArray[vari] = "0"
          commandArray['SendEmail']=''..cmd..' ok igen#'..s..' är senaste tid#abc@hotmail.com'
          file:write(t3 .. " Data från ")
          file:write("<font color=blue>")
          file:write(cmd .."</font>")
          file:write(" är OK igen, senaste data " .. s .. "<br>","\n")
          file:close()
      end 
      
      end
      
      update ('Ute_V') --device name can be temperature or voltage
      update ('AppleTV')
      update ('PS3')
      update ('Stereo')
      update ('Captest')
      update ('Captest_V')
      
      return commandArray
      
      posted in Domoticz
      flopp
      flopp
    • IKEA Spöke/Spoke(ghost)

      I have rebuilt IKEA Spöke(ghost) to be used with MyS and Pro Mini 5V
      I replaced LED with 4 pcs WS2812B LED's.
      Removed all components on POWER PCB, I only use the PCB to get 5V.
      Button is removed.
      No battery is used, only power from 5v adapter. To drive nRF I used step-down 5->3.3V
      When you solder the Ground pin on the PCB, check carefully from where you take the GND, when the plug is inserted you will NOT get GND from all GND spots/places.
      If you will build this think about this/next version:
      Use more LED's, maybe 6 or 8. Change in sketch!!
      Remove LED on step-down and LED on Pro Mini, will light up alot during night if lamp is off
      Add function for button, so you can start it without access to your controller
      Add Repeater function, why not it is on power all the time

      Video: https://youtu.be/sNSBahc-79s
      Link to IKEA Spoke http://www.ikea.com/gb/en/products/childrens-ikea-products/children-3-7/childrens-lighting/spöka-led-night-light-animal-white-turquoise-art-00150985/

      I use the color to tell my kids when it is OK to wake up :), sometimes they wake up at 6 am!!. When time is ok to go up from bed it shows green otherwise it shows red/purple light during whole night.

      To put the silicon back I forst used a lot of power, then I tried with alcohol it was a piece of cake. The alcohol will vaporize.
      This is the sketch

      /*PROJECT: MySensors / RGB test for Light & Sensor
       PROGRAMMER: AWI/GizMoCuz
       DATE: september 27, 2015/ last update: October 10, 2015
       FILE: AWI_RGB.ino
       LICENSE: Public domain
      
       Hardware: Nano and MySensors 1.5
          
       Special:
        uses Fastled library with NeoPixel (great & fast RBG/HSV universal library)       https://github.com/FastLED/FastLED
       
       Remarks:
        Fixed node-id
        Added option to request/apply last light state from gateway
        
       Domoticz typicals - 2015 10 10:
        - Domoticz is using HUE values internally, there might be a slight difference then using direct RGB colors.
      */
      
      #include <MySensor.h>
      #include <SPI.h>
      #include <FastLED.h>
      
      
      const int stripPin = 4 ;                  // pin where 2812 LED strip is connected
      
      const int numPixel = 4 ;                  // set to number of pixels
      
      #define NODE_ID 254                       // fixed MySensors node id
      
      #define CHILD_ID 0                  // Child Id's
      
      CRGB leds[numPixel];
      
      char actRGBvalue[] = "000000";               // Current RGB value
      uint16_t actRGBbrightness = 0xFF ;         // Controller Brightness 
      int actRGBonoff=0;                        // OnOff flag
      
      MySensor gw;
      
      MyMessage lastColorStatusMsg(CHILD_ID,V_VAR1);
      
      void setup() {
        FastLED.addLeds<NEOPIXEL, stripPin >(leds, numPixel); // initialize led strip
      
        gw.begin(incomingMessage, AUTO, false);      // initialize MySensors
        gw.sendSketchInfo("AWI RGB Light", "1.1");
        gw.present(CHILD_ID, S_RGB_LIGHT);        // present to controller
      
        // Flash the "hello" color sequence: R, G, B, black. 
        colorBars();
      
        //Request the last stored colors settings
        gw.request(CHILD_ID, V_VAR1);
      }
      
      void loop() {
        gw.process();                       // wait for incoming messages
      }
      
      void colorBars()
      {
        SendColor2AllLEDs( CRGB::Red );   FastLED.show(); delay(500);
        SendColor2AllLEDs( CRGB::Green ); FastLED.show(); delay(500);
        SendColor2AllLEDs( CRGB::Blue );  FastLED.show(); delay(500);
        SendColor2AllLEDs( CRGB::Black ); FastLED.show(); delay(500);
      } 
      
      void SendColor2AllLEDs(const CRGB lcolor)
      {
        for(int i = 0 ; i < numPixel ; i++) {
          leds[i] = lcolor;
        }
      }
      
      void SendLastColorStatus()
      {
        String cStatus=actRGBvalue+String("&")+String(actRGBbrightness)+String("&")+String(actRGBonoff);
        gw.send(lastColorStatusMsg.set(cStatus.c_str()));
      }
      
      String getValue(String data, char separator, int index)
      {
       int found = 0;
        int strIndex[] = {0, -1};
        int maxIndex = data.length()-1;
        for(int i=0; i<=maxIndex && found<=index; i++){
        if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
       }
        return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
      }
      
      void incomingMessage(const MyMessage &message) {
        if (message.type == V_RGB) {            // check for RGB type
          actRGBonoff=1;
          strcpy(actRGBvalue, message.getString());    // get the payload
          SendColor2AllLEDs(strtol(actRGBvalue, NULL, 16));
          SendLastColorStatus();
        }
        else if (message.type == V_DIMMER) {           // if DIMMER type, adjust brightness
          actRGBonoff=1;
          actRGBbrightness = map(message.getLong(), 0, 100, 0, 255);
          FastLED.setBrightness( actRGBbrightness );
          SendLastColorStatus();
        }
        else if (message.type == V_STATUS) {           // if on/off type, toggle brightness
          actRGBonoff = message.getInt();
          FastLED.setBrightness((actRGBonoff == 1)?actRGBbrightness:0);
          SendLastColorStatus();
        }
        else if (message.type==V_VAR1) {            // color status
          String szMessage=message.getString();
          strcpy(actRGBvalue, getValue(szMessage,'&',0).c_str());
          actRGBbrightness=atoi(getValue(szMessage,'&',1).c_str());
          actRGBonoff=atoi(getValue(szMessage,'&',2).c_str());
          SendColor2AllLEDs(strtol(actRGBvalue, NULL, 16));
          FastLED.setBrightness((actRGBonoff == 1)?actRGBbrightness:0);
        }
        FastLED.show();
      }
      
      

      0_1485641197144_IMG_3696.JPG
      0_1485641206076_IMG_3698.JPG
      0_1485641215595_IMG_3694.JPG

      posted in My Project
      flopp
      flopp
    • nRF24L01+ long range, learn from my mistake

      If you would like to buy a new nRF24L01+ so you can get more range, don't do like I did. I will tell you what i did.
      I bought this(link below) and was waiting and waiting and today finally it arrives, yeah. Kids had gone to bed and I was going around my house checking range before change.
      Changed the nRF24L01+ with standard PCB antenna to new NRF(link), checked mA and the new NRF was 1 mA below!!!, I have heard that long range NRF should draw much more that you need external power source. Not this one!!! 😟
      PCB antenna ~13 mA, long range 60 mA maybe?
      I walked around my house again and still same range like old NRF, strange. Went in to this forum and found my mistake.
      I had bought a normal NRF but with an SMA antenna, WHAT???😡 Like always I am so excite to order quickly so I didn't see that this is NOT PA and NOT LNA.

      So before you order check that the NRF is PA and LNA. Sometimes I order same item but from 2 different sellers and sometimes even from 2 different placed like ebay and aliexpress, if the item disappear or take extra long time to arrive. I checked my second order and that was a PA and LNA, yeah, so now i am back to wait until it arrives. Puhh

      Good luck😃

      http://www.ebay.com/itm/281962954019?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

      posted in Hardware
      flopp
      flopp
    • RE: Merry Christmas and Happy New Year

      Replying to an old topic.

      Happy christmas everyone.

      Please donate to mysensors project, so this very good project gets even better.

      posted in General Discussion
      flopp
      flopp
    • RE: Raspberry Pi2 GPIO interface for NRF24L01+

      @mfalkvidd said:

      @flopp feeding the nrf with 5V is a bad idea. It wants 3.3V.

      I was not clear enough. I have edit my text.
      Thanks

      posted in OpenHardware.io
      flopp
      flopp
    • LUA, send email when Temperature is high

      I am using this script to detect if the drawer is open for my "TV-electronics". My kids start PS3 but forget to open the drawer. That's why I made this 🙂

      Create a user variable named "AppleTVVarm", of course you can name it to what you like but use my names first then after you tested it and it works you can change the names. Device name must be change to your device name If variable is 1 it means that the temperature has reached its limit.
      If the temperature get above 35 it will send me an email and when it goes below 30 it will send a new email, so I know it gets cooled down.
      Varm means Warm
      Sval means cool

      commandArray = {}
      
      local function update(cmd)
      if devicechanged[cmd] then
          local vari = "Variable:"  .. cmd .. "Varm" --add Varibale: before device and Varm after device
          local varm = cmd .. "Varm" --add Varm after device
          --print(cmd)
          --print(varm)
          --print(vari)
      
          temperature = tonumber(devicechanged[''..cmd..'_Temperature']) --read temperature from device, if device have more than only temperature
          if (temperature > 35) and (uservariables[varm] == 0) then --if temperature is above 35 for the first time
              commandArray['SendEmail']=''..cmd..' varm#""#abc@hotmail.com' --send email
              commandArray[vari] = "1" --set variable to 1
          end
          if (temperature < 30) and (uservariables[varm] == 1) then --if temperature is below 30
              commandArray['SendEmail']=''..cmd..' sval#""#abc@hotmail.com' --send email
              commandArray[vari] = "0" --set variable to 0
          end
      end
      
      end
      
      update ('AppleTV') --device to read temperature from
      update ('PS3')
      update ('Stereo')
      
      return commandArray
      

      copy the code and create a new script in Domoticz, select LUA and Device otherwise it will not work

      posted in Domoticz
      flopp
      flopp
    • RE: Power external sensors on demand

      That I am also using.

      Read here https://forum.mysensors.org/topic/2147/office-plant-monitoring/64 and here https://forum.mysensors.org/topic/4045/solar-powered-soil-moisture-sensor/45

      posted in Hardware
      flopp
      flopp
    • RE: MySensors protocol page improvement recommendation

      also found typo
      V_STATUS missing S_BINARY, S_WATER_QUALITY
      V_LIGHT missing S_BINARY
      V_WATT missing S_BINARY, S_RGB_LIGHT, S_RGBW_LIGHT
      V_PERCENTAGE missing S_COVER
      V_TEMP missing S_WATER_QUALITY
      S_HEATER missing V_STATUS, V_HVAC_SETPOINT_HEAT
      S_HVAC missing V_STATUS, V_TEMP, V_HVAC_SPEED

      V_HVAC_SETPOINT_COLD is missing

      posted in General Discussion
      flopp
      flopp
    • RE: Solar Powered Soil Moisture Sensor

      @NeverDie said:

      Interesting project. To what degree, if any, has corrosion been a problem after you switched to soldered connections? Obviously the operating environment (near the ground outdoors) can be intrinsically humid.

      I have not checked how the sensor look like now, but I have only run it for 6 months. I have always used soldered connections.

      Also, can someone please post a larger photo of how the sensor is attached at the base?

      1_1479545970922_20160606_131714652_iOS.jpg 0_1479545970922_20160606_131710115_iOS.jpg

      posted in My Project
      flopp
      flopp
    • Repeater Node, problems

      RPi with Domoticz, MySensors 1.5.1

      I had an Ethernet GW(UNO) and a Repeater Node(NANO clone) working OK but sometimes the nodes couldn't send data, maybe 4 times per day, I could live with that but of course 100% data is much nicer 🙂 my nodes sends data every 30/60 min.

      I changed to a Serial GW because my router sometimes stopped working so I had no connection to Ethernet GW.
      Since that time I lost lots of data, I have always though the problem was the Serial GW until yesterday. I checked my Logfile that write every time a node is not sending data for more than 70 minutes, it was always the nodes that was sending data through the Repeater Node, since the nodes are far away from Serial GW.

      Yesterday I changed to have NO DEBUG and from baud rate from 57600 to 9600 and since then I have data all the time.

      Can it be that critical to NOT have DEBUG?
      Could it be the baud rate that made my problems before?
      Maybe the sketch was not 100% complete and after I upload the new sketch it was 100% correct?

      posted in Domoticz
      flopp
      flopp
    • RE: New 2.2.0 Signal report function

      I tried to send RSSI with nRF and it seemed to work, I could get a value that was changing if I moved away from Gateway.

      i was using this variable, transportGetSignalReport(SR_TX_RSSI)

      so to send the RSSI create a Child, I think you can pick anyone that can handle value from 0-1024 then use below message to send the value

      send(RSSIMsg.set(transportGetSignalReport(SR_TX_RSSI)));

      I am using Domoticz as Controller

      posted in Hardware
      flopp
      flopp
    • RE: Solar Powered Soil Moisture Sensor

      WARNING!!!
      I opened one of my items which didn't worked since many weeks ago.
      I putted it on a table and should just open the stuff when I saw some brown water coming out from the pole.
      My first guess was that it was water mixed with mud but the smell was strange. It can be that the battery has leaked.

      If you will build this item please seal the battery to 100%. I just put the battery in the pole but unfortunately water came in and what I think destroyed the battery!

      Be careful

      posted in My Project
      flopp
      flopp
    • Copy code from posts

      I have seen on some pages that there is a button to copy the code easy or similar Select all.

      Would that be possible to implement?

      posted in Feature Requests
      flopp
      flopp
    • RE: MySensors 2.3.0 released

      @nagelc said in MySensors 2.3.0 released:

      I recently upgraded my NRF24 serial gateway from 1.5 to 2.3.0 and did not have any issues. I upgraded my RFM69 gateway a while ago with no issues. If it is RFM 69, check the frequency because MyConfig.h will have gone back to the default (I use 915 mhx which is not default). Do you get any error messages? Maybe one of the more experienced MySensors users could help with those.

      Thank you, you put me in the right direction.
      I created a network for my friend(on 2.3)on different channel than I use, I didn’t change the channel in myconfig.h before I updated my GW

      posted in Announcements
      flopp
      flopp
    • RE: two energy meter

      I couldn't just lay down in the sofa so I started to test and now I got a code that seems to work. I have tested it for a few days and it seems to count correct.

      I made some changes so it will send data every minute and it will send Watt-value even if it is the same value since last time.

      I am using VAR2 for second energy meter since I don't know how to config Incomingmessage and seperate VAR1 from different Child_IDs.

      I change corrupted interrupts from 10000L to 40000L otherwise it reported interrupts twice.

      /**
       * 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
       * Use this sensor to measure kWh and Watt of your house meter
       * You need to set the correct pulsefactor of your meter (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>  
      unsigned long SEND_FREQUENCY = 60000; // Minimum time between send (in milliseconds). We don't want to spam the gateway.
      #define SLEEP_MODE false        // Watt-value can only be reported when sleep mode is false.
      
      //sensor 1
      #define DIGITAL_INPUT_SENSOR_1 2 // The digital input you attached your light sensor.  (Only 2 and 3 generates interrupt!)
      #define PULSE_FACTOR_1 1000       // Number of blinks per KWH of your meeter
      #define MAX_WATT_1 10000          // Max watt value to report. This filters outliers.
      #define INTERRUPT_1 DIGITAL_INPUT_SENSOR_1-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
      #define CHILD_ID_1 1              // Id of the sensor child
      
      //sensor 2
      #define DIGITAL_INPUT_SENSOR_2 3 // The digital input you attached your light sensor.  (Only 2 and 3 generates interrupt!)
      #define PULSE_FACTOR_2 10000       // Number of blinks per KWH of your meeter
      #define MAX_WATT_2 10000          // Max watt value to report. This filters outliers.
      #define INTERRUPT_2 DIGITAL_INPUT_SENSOR_2-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
      #define CHILD_ID_2 2              // Id of the sensor child
      
      MySensor gw;
      
      //sensor 1
      double ppwh_1 = ((double)PULSE_FACTOR_1)/1000; // Pulses per watt hour
      boolean pcReceived_1 = false;
      volatile unsigned long pulseCount_1 = 0;   
      volatile unsigned long lastBlink_1 = 0;
      volatile unsigned long watt_1 = 0;
      unsigned long oldPulseCount_1 = 0;   
      unsigned long oldWatt_1 = 0;
      double oldKwh_1;
      unsigned long lastSend_1;
      
      //sensor 2
      double ppwh_2 = ((double)PULSE_FACTOR_2)/1000; // Pulses per watt hour
      boolean pcReceived_2 = false;
      volatile unsigned long pulseCount_2 = 0;   
      volatile unsigned long lastBlink_2 = 0;
      volatile unsigned long watt_2 = 0;
      unsigned long oldPulseCount_2 = 0;   
      unsigned long oldWatt_2 = 0;
      double oldKwh_2;
      unsigned long lastSend_2;
      
      //sensor 1
      MyMessage wattMsg_1(CHILD_ID_1,V_WATT);
      MyMessage kwhMsg_1(CHILD_ID_1,V_KWH);
      MyMessage pcMsg_1(CHILD_ID_1,V_VAR1);
      
      //sensor 2
      MyMessage wattMsg_2(CHILD_ID_2,V_WATT);
      MyMessage kwhMsg_2(CHILD_ID_2,V_KWH);
      MyMessage pcMsg_2(CHILD_ID_2,V_VAR2);
      
      
      void setup()  
      {  
        gw.begin(incomingMessage);
      
        // Send the sketch version information to the gateway and Controller
        gw.sendSketchInfo("Energy Double", "1.0");
      
        // Register this device as power sensor
        //sensor 1
        gw.present(CHILD_ID_1, S_POWER);
        //sensor 2
        gw.present(CHILD_ID_2, S_POWER);
      
        //Send new VAR to Gateway
        //gw.send(pcMsg_1.set(xxxxxxxxx));  // Send pulse count value to gw 
        //gw.send(pcMsg_2.set(1895931000));  // Send pulse count value to gw 
        
        // Fetch last known pulse count value from gw
        //sensor 1
        gw.request(CHILD_ID_1, V_VAR1);
        //sensor 2
        gw.request(CHILD_ID_2, V_VAR2);
      
        //sensor 1
        attachInterrupt(INTERRUPT_1, onPulse_1, RISING);
        //sensor 2
        attachInterrupt(INTERRUPT_2, onPulse_2, RISING);
        
        lastSend_1=millis();
        lastSend_2=millis();
      }
      
      
      void loop()     
      { 
        gw.process();
      
        //sensor 1
        unsigned long now_1 = millis();
        // Only send values at a maximum frequency or woken up from sleep
        bool sendTime_1 = now_1 - lastSend_1 > SEND_FREQUENCY;
        if (pcReceived_1 && (SLEEP_MODE || sendTime_1)) {
          // New watt value has been calculated  
          //if (!SLEEP_MODE && watt_1 != oldWatt_1) {
            // Check that we dont get unresonable large watt value. 
            // could hapen when long wraps or false interrupt triggered
            if (watt_1<((unsigned long)MAX_WATT_1)) {
              gw.send(wattMsg_1.set(watt_1));  // Send watt value to gw 
            }  
            Serial.print("Watt_1:");
            Serial.println(watt_1);
            oldWatt_1 = watt_1;
          //}    
        
          // Pulse cout has changed
          if (pulseCount_1 != oldPulseCount_1) {
            gw.send(pcMsg_1.set(pulseCount_1));  // Send pulse count value to gw 
            double kwh_1 = ((double)pulseCount_1/((double)PULSE_FACTOR_1));     
            oldPulseCount_1 = pulseCount_1;
            //if (kwh_1 != oldKwh_1) {
              gw.send(kwhMsg_1.set(kwh_1, 4));  // Send kwh value to gw 
              oldKwh_1 = kwh_1;
            //}
          }    
          lastSend_1 = now_1;
        } else if (sendTime_1 && !pcReceived_1) {
          // No count received. Try requesting it again
          gw.request(CHILD_ID_1, V_VAR1);
          lastSend_1=now_1;
        }
      
          //sensor 2
        unsigned long now_2 = millis();
        // Only send values at a maximum frequency or woken up from sleep
        bool sendTime_2 = now_2 - lastSend_2 > SEND_FREQUENCY;
        if (pcReceived_2 && (SLEEP_MODE || sendTime_2)) {
          // New watt value has been calculated  
          //if (!SLEEP_MODE && watt_2 != oldWatt_2) {
            // Check that we dont get unresonable large watt value. 
            // could hapen when long wraps or false interrupt triggered
            if (watt_2<((unsigned long)MAX_WATT_2)) {
              gw.send(wattMsg_2.set(watt_2));  // Send watt value to gw 
            }  
            Serial.print("Watt_2:");
            Serial.println(watt_2);
            oldWatt_2 = watt_2;
          //}    
        
          // Pulse cout has changed
          if (pulseCount_2 != oldPulseCount_2) {
            gw.send(pcMsg_2.set(pulseCount_2));  // Send pulse count value to gw 
            double kwh_2 = ((double)pulseCount_2/((double)PULSE_FACTOR_2));     
            oldPulseCount_2 = pulseCount_2;
            //if (kwh_2 != oldKwh_2) {
              gw.send(kwhMsg_2.set(kwh_2, 4));  // Send kwh value to gw 
              oldKwh_2 = kwh_2;
            //}
          }    
          lastSend_2 = now_2;
        } else if (sendTime_2 && !pcReceived_2) {
          // No count received. Try requesting it again
          gw.request(CHILD_ID_2, V_VAR2);
          lastSend_2=now_2;
        }
        
        if (SLEEP_MODE) {
          gw.sleep(SEND_FREQUENCY);
        }
      }
      
      void incomingMessage(const MyMessage &message) {
        if (message.type==V_VAR1) {  
          pulseCount_1 = oldPulseCount_1 = message.getLong();
          Serial.print("Received_1 last pulse count from gw:");
          Serial.println(pulseCount_1);
          pcReceived_1 = true;
        }
        if (message.type==V_VAR2) {  
          pulseCount_2 = oldPulseCount_2 = message.getLong();
          Serial.print("Received_2 last pulse count from gw:");
          Serial.println(pulseCount_2);
          pcReceived_2 = true;
        }
      }
      
      void onPulse_1()     
      { 
        if (!SLEEP_MODE) {
          unsigned long newBlink_1 = micros();  
          unsigned long interval_1 = newBlink_1-lastBlink_1;
          if (interval_1<40000L) { // Sometimes we get interrupt on RISING
            return;
          }
          watt_1 = (3600000000.0 /interval_1) / ppwh_1;
          lastBlink_1 = newBlink_1;
        } 
        //Serial.println(pulseCount_1);
        pulseCount_1++;
        //Serial.println(pulseCount_1);
      }
      
      void onPulse_2()     
      { 
        if (!SLEEP_MODE) {
          unsigned long newBlink_2 = micros();  
          unsigned long interval_2 = newBlink_2-lastBlink_2;
          if (interval_2<40000L) { // Sometimes we get interrupt on RISING
            return;
          }
          watt_2 = (3600000000.0 /interval_2) / ppwh_2;
          lastBlink_2 = newBlink_2;
        } 
        //Serial.println(pulseCount_2);
          pulseCount_2++;
        //Serial.println(pulseCount_2);
      }
      
      
      posted in My Project
      flopp
      flopp
    • RE: Energy Meter - not sending at expected

      @sundberg84
      i also had a lot of problem with my Rain data in Domoticz.
      read more here https://www.domoticz.com/forum/viewtopic.php?f=28&t=11088

      if your Sensor timeout is 2 hours you need to send rain VAR within 2 hours otherwise your graph will look strange.

      Yes, if you change the VAR during the day to a lower value you will get minus value. Took me a few days to understand how Domoticz DB file was working.

      Keep up the good work 👊

      posted in Troubleshooting
      flopp
      flopp
    • Water leak sensor

      Finally I made my water leak sensor that I have been dreaming about for a long time now 🙂
      I used those items:
      Enclosure
      2 x AA batteris incl holder
      nRF24L01+
      Home made PCB with ATmega328P-PU
      red, green LED
      si7021, temp & hum
      some capactitors and resistors
      Kitchen aluminum foil
      Copper wire

      I am measuring temperature and humidity with a Si7021, measuring battery voltage with voltage divider and internal reference, just to test which one that shows most correct.

      /**
       * 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
       * 
       */
      // Enable and select radio type attached
      #define MY_RADIO_NRF24
      
      // Enable debug prints to serial monitor
      #define MY_DEBUG
      
      #define MY_NODE_ID 27
      
      #include <SPI.h>
      #include <MySensors.h>
      #include <Wire.h>
      #include <SI7021.h>
      
      #define CHILD_SIHUM 0
      #define CHILD_SITEMP 1
      #define CHILD_BATT 2
      #define CHILD_SIDEW 3
      #define CHILD_BATTRES 4
      
      #define CHILD_WATER 10
      
      #define CHILD_FAILS 250
      #define CHILD_PARENT 251
      #define CHILD_DISTANCE 252
      #define CHILD_SLEEPTIME 253
      
      //LED
      int GREEN = 7;
      int RED = 8;
      
      //Water alarm
      int Interrupt = 1; // pin 3 on UNO/Nano
      
      //SleepTime
      float SleepTime = 30; // Sleep time between reads (in minutes)
      int OldSleepTime = -1;
      int SleepTimeLoopCount = 10;
      
      //ReadVCC
      long result;
      float BatteryVolt;
      float OldBatteryVolt;
      int BatteryVoltLoopCount = 5;
      
      //ReadVCCRes
      int sensorValue;
      float BatteryResVolt;
      int BATTERY_SENSE_PIN = A2;  // select the input pin for the battery sense point
      
      //SI7021
      SI7021 SI;
      int SILoopCount = 5;
      int SIHum;
      int OldSIHum = -1;
      float SITemp;
      float OldSITemp = -1;
      float SIDew;
      float OldSIDew = -1;
      
      //NRF
      int Fails = 0;
      int OldFails = -1;
      int FailsLoopCount = 10;
      int OldParentNode = -1;
      int ParentNodeLoopCount = 10;
      int OldDistanceNode = -1;
      int DistanceLoopCount = 10;
      
      MyMessage msgSIHum(CHILD_SIHUM, V_HUM);
      MyMessage msgSITemp(CHILD_SITEMP, V_TEMP);
      MyMessage msgSIDew(CHILD_SIDEW, V_TEMP);
      MyMessage msgBatt(CHILD_BATT, V_VOLTAGE);
      MyMessage msgBattRes(CHILD_BATTRES, V_VOLTAGE);
      
      MyMessage msgWater(CHILD_WATER, V_TRIPPED);
      
      MyMessage msgFails(CHILD_FAILS, V_VA);
      MyMessage msgParent(CHILD_PARENT, V_VA);
      MyMessage msgDistance(CHILD_DISTANCE, V_VA);
      MyMessage msgSleepTime(CHILD_SLEEPTIME, V_VA);
      
      void setup() {
      
        //Water Alarm
        pinMode(3, INPUT_PULLUP);
        attachInterrupt(Interrupt, Water, FALLING);
      
        //Battery measurement
        analogReference(INTERNAL); // use the 1.1 V internal reference
        sensorValue = analogRead(BATTERY_SENSE_PIN); // read once to activate the change of reference
      
        pinMode(GREEN, OUTPUT);
        pinMode(RED, OUTPUT);
        digitalWrite(GREEN, HIGH);
        digitalWrite(RED, HIGH);
        delay(200);
        digitalWrite(GREEN, LOW);
        digitalWrite(RED, LOW);
      
        SI.begin();
      }
      void presentation() {
        // Send the sketch version information to the gateway and Controller
        sendSketchInfo("Temp/Humidity/WaterLeak", "20180226");
        // Register all sensors to gateway (they will be created as child devices)
        present(CHILD_SIHUM, S_HUM, "SIHum");
        present(CHILD_SITEMP, S_TEMP, "SITemp");
        present(CHILD_SIDEW, S_TEMP, "SIDew");
        present(CHILD_BATT, S_MULTIMETER, "Volt");
        present(CHILD_BATTRES, S_MULTIMETER, "VoltRes");
      
        present(CHILD_WATER, S_WATER_LEAK, "Water Alarm");
        
        present(CHILD_FAILS, S_POWER, "Fails");
        present(CHILD_PARENT, S_POWER, "Parent");
        present(CHILD_DISTANCE, S_POWER, "Distance");  
        present(CHILD_SLEEPTIME, S_DIMMER, "SleepTime");
      }
      void loop() {
        //Voltage
        readVcc();
        sensorValue = analogRead(BATTERY_SENSE_PIN);
        BatteryResVolt  = sensorValue * 0.003363075;
        
        //SI read both temperature and humidity
        si7021_env SIdata = SI.getHumidityAndTemperature();
        
        //SI Humidity  
        SIHum = SIdata.humidityPercent;
        //Serial.print("SIHum=");
        //Serial.println(SIHum);
        if(SIHum >99)
        {
          SIHum = 99;
        }
        if(SIHum < 1)
        {
          SIHum = 0;
        }
        
        //SI Temperature
        SITemp = SIdata.celsiusHundredths / 100.0;
        SITemp = round(SITemp*10)/10.0;
        //Serial.print("SITemp=");
        //Serial.println(SITemp,1);
      
        //SI Dew
        double a = 17.271;
        double b = 237.7;
        double dewtemp = (a * SITemp) / (b + SITemp) + log(SIHum*0.01);
        SIDew = (b * dewtemp) / (a - dewtemp);
      
        //Get SleepTime from controller
        request(CHILD_SLEEPTIME, V_PERCENTAGE);
        wait(1000);
      
        //Water Alarm
        int WaterLeak = digitalRead(3);
        if (WaterLeak == 0){
          resend((msgWater.set(1)), 100);
        } 
        else{
          resend((msgWater.set(0)), 100);
        }
      
        //Send data to controller
        if ((OldBatteryVolt != BatteryVolt) | (BatteryVoltLoopCount >= 5))
        {
          send(msgBatt.set(BatteryVolt, 3));
          send(msgBattRes.set(BatteryResVolt, 3));
          OldBatteryVolt = BatteryVolt;
          BatteryVoltLoopCount = 0;
        }
          
        if ((OldSIHum != SIHum) | (OldSITemp != SITemp) | (OldSIDew != SIDew) | (SILoopCount >= 5))
        {
          resend((msgSIHum.set(SIHum)), 1);
          resend((msgSITemp.set(SITemp, 1)), 1);
          resend((msgSIDew.set(SIDew, 1)), 1);
          OldSIHum = SIHum;
          OldSITemp = SITemp;
          OldSIDew = SIDew;
          SILoopCount = 0;
        }
        
        if ((OldParentNode != _transportConfig.parentNodeId) | (ParentNodeLoopCount >= 10))
        {
          resend((msgParent.set(_transportConfig.parentNodeId)),1);
          OldParentNode = _transportConfig.parentNodeId;
          ParentNodeLoopCount = 0;
        }
          
        if ((OldDistanceNode != _transportConfig.distanceGW) | (DistanceLoopCount >= 10))
        {
          resend((msgDistance.set(_transportConfig.distanceGW)),1);
          OldDistanceNode = _transportConfig.distanceGW;
          DistanceLoopCount = 0;
        }
      
        if ((OldSleepTime != SleepTime) | (SleepTimeLoopCount >= 10))
        {
          resend((msgSleepTime.set(SleepTime,0)),10);
          OldSleepTime = SleepTime;
          SleepTimeLoopCount = 0;
        }
      
        if ((OldFails != Fails) | (FailsLoopCount >= 10))
        {
          failsend((msgFails.set(Fails)),1);
          OldFails = Fails;
          FailsLoopCount = 0;
        }
           
        BatteryVoltLoopCount++;
        SILoopCount++;
        ParentNodeLoopCount++;
        DistanceLoopCount++;
        SleepTimeLoopCount++;
        FailsLoopCount++;
      
        digitalWrite(GREEN, HIGH);
        delay(200);
        digitalWrite(GREEN, LOW);
        
        sleep(SleepTime*60000); //sleep a bit
      }
      void readVcc() {
        //Serial.println("readVcc");
        // Read 1.1V reference against AVcc
        ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
        delay(2); // Wait for Vref to settle
        ADCSRA |= _BV(ADSC); // Convert
        while (bit_is_set(ADCSRA, ADSC));
        result = ADCL;
        result |= ADCH << 8;
        result = 1126400L / result; // Back-calculate AVcc in mV
        //batteryPcnt = (result - 1900) * 0.090909;
        BatteryVolt = result / 1000.000;
        //sendBatteryLevel(batteryPcnt);
        //Serial.print("battery volt:");
        //Serial.println(batteryVolt, 3);
        //Serial.print("battery percent:");
        //Serial.println(batteryPcnt);
      }
      void resend(MyMessage & msg, int repeats) {
        int repeat = 0;
        int repeatdelay = 0;
        boolean sendOK = false;
        while ((sendOK == false) and(repeat < repeats))
        {
          if (send(msg))
          {
            sendOK = true;
          }
          else
          {
            
            digitalWrite(RED, HIGH);
            delay(200);
            digitalWrite(RED, LOW);
            Fails++;
            sendOK = false;
            Serial.print("Error ");
            Serial.println(repeat);
            repeatdelay += 250;
            repeat++;
            sleep(repeatdelay);
          }
        }
      }
      
      void failsend(MyMessage &msg, int repeats) {
        int repeat = 0;
        int repeatdelay = 0;
        boolean sendOK = false;
      
        while ((sendOK == false) and (repeat < repeats)) {
          if (send(msg))
          {
            Fails = 0;
            sendOK = true;
          }
          else
          {
            Fails++;
            sendOK = false;
            Serial.print("Error ");
            Serial.println(repeat);
            repeatdelay += 250;
            repeat++;
            sleep(repeatdelay);
          }
        }
      }
      
      void receive(const MyMessage &message) {
        if (message.sender == 0) {
          if(message.type == V_PERCENTAGE) {
            //Serial.println( "V_PERCENTAGE command received..." );
            SleepTime = atoi(message.data);
            if ((SleepTime <= 0) | (SleepTime >= 700))
            {
              SleepTime = 30;
            }
            else
            {
              SleepTime = SleepTime / 6.6;
              //Serial.println(SleepTime);
              if (SleepTime < 1)
              {
                SleepTime = 1;  
              }
            }
            //Serial.println(SleepTime);
          }
        } 
      }
      
      void Water() {
        Serial.println("Water");
        resend((msgWater.set(1)), 1000);
        digitalWrite(GREEN, HIGH);
        delay(200);
        digitalWrite(GREEN, LOW);
      }
      

      0_1519677466024_20180226_193839617_iOS.jpg
      0_1519677539241_20180226_193922845_iOS.jpg

      posted in My Project
      flopp
      flopp
    • Shunt motor/valve

      My heating system was not putting out any heated water to our radiators. A friend gave the idea to put an accelerator-meter to the pin.

      This is what I made.
      MySensors - Shunt motor valve – 00:27
      — Daniel Nilsson

      On the monitor you see 2666, that is the raw value from the sensor, below that you see how much the shunt is opened in percent.

      Grapg from Grafana, top graph shows raw value from accelerator-meter, bottom graph with percent opened and outdoor temp:
      0_1557840289633_db87a8e8-79cb-4596-8661-3f5019c8e26f-image.png

      The code I am using:

      // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
      // 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
      // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
      //
      // Changelog:
      //      2013-05-08 - added multiple output formats
      //                 - added seamless Fastwire support
      //      2011-10-07 - initial release
      
      /* ============================================
      I2Cdev device library code is placed under the MIT license
      Copyright (c) 2011 Jeff Rowberg
      
      Permission is hereby granted, free of charge, to any person obtaining a copy
      of this software and associated documentation files (the "Software"), to deal
      in the Software without restriction, including without limitation the rights
      to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      copies of the Software, and to permit persons to whom the Software is
      furnished to do so, subject to the following conditions:
      
      The above copyright notice and this permission notice shall be included in
      all copies or substantial portions of the Software.
      
      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      THE SOFTWARE.
      ===============================================
      */
      
      /**
       * 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.
       *
       *******************************
      */
      
      // Enable and select radio type attached
      #define MY_RADIO_RF24
      
      // Enable debug prints to serial monitor
      #define MY_DEBUG
      
      #include <SPI.h>
      #include <MySensors.h>
      #include <Wire.h>
      
      #define CHILD_SHUNT 0
      #define CHILD_SHUNTDATA 1
      
      #define CHILD_FAILS 250
      #define CHILD_PARENT 251
      #define CHILD_DISTANCE 252
      
      //NRF
      int Fails = 0;
      int OldFails = -1;
      int FailsLoopCount = 10;
      int OldParentNode = -1;
      int ParentNodeLoopCount = 10;
      int OldDistanceNode = -1;
      int DistanceLoopCount = 10;
      
      MyMessage msgShunt(CHILD_SHUNT, V_WATT);
      MyMessage msgShuntData(CHILD_SHUNTDATA, V_WATT);
      
      MyMessage msgFails(CHILD_FAILS, V_VA);
      MyMessage msgParent(CHILD_PARENT, V_VA);
      MyMessage msgDistance(CHILD_DISTANCE, V_VA);
      
      // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
      // for both classes must be in the include path of your project
      #include "I2Cdev.h"
      #include "MPU6050.h"
      
      // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
      // is used in I2Cdev.h
      #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
          #include "Wire.h"
      #endif
      
      // class default I2C address is 0x68
      // specific I2C addresses may be passed as a parameter here
      // AD0 low = 0x68 (default for InvenSense evaluation board)
      // AD0 high = 0x69
      MPU6050 accelgyro;
      //MPU6050 accelgyro(0x69); // <-- use for AD0 high
      
      int16_t ax, count;
      long axx;
      
      
      
      // uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
      // list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
      // not so easy to parse, and slow(er) over UART.
      #define OUTPUT_READABLE_ACCELGYRO
      
      // uncomment "OUTPUT_BINARY_ACCELGYRO" to send all 6 axes of data as 16-bit
      // binary, one right after the other. This is very fast (as fast as possible
      // without compression or data loss), and easy to parse, but impossible to read
      // for a human.
      //#define OUTPUT_BINARY_ACCELGYRO
      
      void setup() {
          // join I2C bus (I2Cdev library doesn't do this automatically)
          #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
              Wire.begin();
          #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
              Fastwire::setup(400, true);
          #endif
      
          // initialize serial communication
          // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
          // it's really up to you depending on your project)
          //Serial.begin(38400);
      
          // initialize device
          Serial.println("Initializing I2C devices...");
          accelgyro.initialize();
      
          // verify connection
          Serial.println("Testing device connections...");
          Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
      
          // use the code below to change accel/gyro offset values
          /*
          Serial.println("Updating internal sensor offsets...");
          // -76	-2359	1688	0	0	0
          Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
          Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
          Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
          Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
          Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
          Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
          Serial.print("\n");
          accelgyro.setXGyroOffset(220);
          accelgyro.setYGyroOffset(76);
          accelgyro.setZGyroOffset(-85);
          Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
          Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
          Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
          Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
          Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
          Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
          Serial.print("\n");
          */
      
      }
      
      void presentation() {
        // Send the sketch version information to the gateway and Controller
        sendSketchInfo("Shuntventil", "20190505");
        // Register all sensors to gateway (they will be created as child devices)
        present(CHILD_SHUNT, S_POWER, "Procent");
        present(CHILD_SHUNTDATA, S_POWER, "ShuntData");  
        present(CHILD_FAILS, S_POWER, "Fails");
        present(CHILD_PARENT, S_POWER, "Parent");
        present(CHILD_DISTANCE, S_POWER, "Distance");  
      }
      
      void loop() {
          for (count = 0 ; count < 10 ; count++) {
          
          // read raw accel/gyro measurements from device
          //accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
      
          // these methods (and a few others) are also available
          //accelgyro.getAcceleration(&ax, &ay, &az);
          //accelgyro.getRotation(&gx, &gy, &gz);
          ax = accelgyro.getAccelerationX();
          #ifdef OUTPUT_READABLE_ACCELGYRO
              // display tab-separated accel/gyro x/y/z values
              //Serial.print("a/g:\t");
              //Serial.print(ax);// Serial.print("\t");
              //Serial.println(axa);// Serial.print("\t");
              //Serial.print(az); Serial.print("\t");
              //Serial.print(gx); Serial.print("\t");
              //Serial.print(gy); Serial.print("\t");
              //Serial.println(gz);
          #endif
      
          
          axx = axx + ax;  
         
          }
          axx = axx / 10;
          //Serial.println(axx);
          resend((msgShuntData.set(axx)),3);
          long y = map(axx,-12300,12500,0,100);
          //Serial.println(y);
          resend((msgShunt.set(y)),3);
          axx = 0;
      
          if ((OldParentNode != _transportConfig.parentNodeId) | (ParentNodeLoopCount >= 10))
        {
          resend((msgParent.set(_transportConfig.parentNodeId)),3);
          OldParentNode = _transportConfig.parentNodeId;
          ParentNodeLoopCount = 0;
        }
          
        if ((OldDistanceNode != _transportConfig.distanceGW) | (DistanceLoopCount >= 10))
        {
          resend((msgDistance.set(_transportConfig.distanceGW)),3);
          OldDistanceNode = _transportConfig.distanceGW;
          DistanceLoopCount = 0;
        }
      
        if ((OldFails != Fails) | (FailsLoopCount >= 3))
        {
          failsend((msgFails.set(Fails)),3);
          OldFails = Fails;
          FailsLoopCount = 0;
        }
           
        ParentNodeLoopCount++;
        DistanceLoopCount++;
        FailsLoopCount++;
      
          sleep(30000);
      }
      
      //skicka axx(som är delat på 10) till DZ, så man kan kalibrera värden
      
      
      void resend(MyMessage & msg, int repeats) {
        int repeat = 0;
        int repeatdelay = 0;
        boolean sendOK = false;
        while ((sendOK == false) and(repeat < repeats))
        {
          if (send(msg))
          {
            sendOK = true;
          }
          else
          {
            Fails++;
            sendOK = false;
            Serial.print("Error ");
            Serial.println(repeat);
            repeatdelay += 250;
            repeat++;
            sleep(repeatdelay);
          }
        }
      }
      
      void failsend(MyMessage &msg, int repeats) {
        int repeat = 1;
        int repeatdelay = 0;
        boolean sendOK = false;
      
        while ((sendOK == false) and (repeat < repeats)) {
          if (send(msg))
          {
            Fails = 0;
            sendOK = true;
          }
          else
          {
            Fails++;
            sendOK = false;
            Serial.print("Error ");
            Serial.println(repeat);
            repeatdelay += 250;
            repeat++;
            sleep(repeatdelay);
          }
        }
      }
      
      posted in My Project
      flopp
      flopp
    • RE: Domotiocz + Rain gauge

      @TheoL said:

      @flopp Thank you. What do you mean by sending data correctly? Do you have an example sketch?

      Not correctly, I wrote depending.

      If you send data every 2 hours and ot every time the buck has tiped the rate will not be correct. Lets say you send/report every 2 hour, you report 10 mm, that means you have "collect" 10 mm for 2 hours. Maybe the hour was not raining, then the rate will show you 10mm/h, sorry if I confusing you.

      What I mean is that you should send/report directly when the buck has tiped then the rate in DZ will be correct rate/h.

      my sketch

      #include <SPI.h>
      #include <MySensor.h> 
      
      // Running this in Domoticz stable version 2.5 will not work - upgrade to beta.
      
      #define DIGITAL_INPUT_SENSOR 3 // The reed switch you attached. (Only 2 and 3 generates interrupt!)
      #define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
      
      #define CHILD_ID 1 // Id of the sensor child
      #define BATT_CHILD 2
      #define NODE_ID AUTO // or AUTO to let controller assign
      #define SKETCH_NAME "Rain Gauge" // Change to a fancy name you like
      #define SKETCH_VERSION "1.8" // Your version
      
      unsigned long SLEEP_TIME = 180*60000; // Sleep time (in milliseconds).
      //unsigned long SLEEP_TIME = 20000; // use this instead for debug
      
      float hwRainVolume = 0; // Current rainvolume calculated in hardware.
      int hwPulseCounter = 0; // Pulsecount recieved from GW
      float fullCounter = 0; // Counts when to send counter
      float bucketSize = 0.5; // Bucketsize mm, needs to be 1, 0.5, 0.25, 0.2 or 0.1
      boolean pcReceived = false; // If we have recieved the pulscount from GW or not 
      boolean reedState; // Current state the reedswitch is in
      boolean oldReedState; // Old state (last state) of the reedswitch
      unsigned long lastSend =0; // Time we last tried to fetch counter.
      
      MySensor gw;
      MyMessage volumeMsg(CHILD_ID,V_RAIN);
      MyMessage lastCounterMsg(CHILD_ID,V_VAR1);
      MyMessage battMsg(BATT_CHILD, V_VOLTAGE);
      
      //=========================
      // BATTERY VOLTAGE DIVIDER SETUP
      // 1M, 470K divider across battery and using internal ADC ref of 1.1V
      // Sense point is bypassed with 0.1 uF cap to reduce noise at that point
      // ((1e6+470e3)/470e3)*1.1 = Vmax = 3.44 Volts
      // 3.44/1023 = Volts per bit = 0.003363075
      /*
      #define VBAT_PER_BITS 0.003363075 
      #define VMIN 1.9 // Vmin (radio Min Volt)=1.9V (564v)
      #define VMAX 3.0 // Vmax = (2xAA bat)=3.0V (892v)
      int batteryPcnt = 0; // Calc value for battery %
      int batLoop = 0; // Loop to help calc average
      int batArray[3]; // Array to store value for average calc.
      int BATTERY_SENSE_PIN = A0; // select the input pin for the battery sense point
      //=========================
      */
      
      long result;
      float batteryPcnt;
      float batteryVolt;
      
      void setup() 
      { 
      pinMode(6,OUTPUT);
      digitalWrite(6,HIGH);
      // use the 1.1 V internal reference
      //analogReference(INTERNAL); // For battery sensing
      
      pinMode(DIGITAL_INPUT_SENSOR, INPUT_PULLUP); // sets the reed sensor digital pin as input
      
      reedState = digitalRead(DIGITAL_INPUT_SENSOR); // Read what state the reedswitch is in
      oldReedState = reedState; // Set startup position for reedswitch
      
      delay(500); // Allow time for radio if power used as reset
      
      //Begin (Change if you dont want static node_id! (NODE_ID to AUTO)
      gw.begin(incomingMessage, NODE_ID, false);
      
      // Send the Sketch Version Information to the Gateway
      gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
      
      // Register this device as Rain sensor (will not show in Domoticz until first value arrives)
      gw.present(CHILD_ID, S_RAIN); 
      gw.present(BATT_CHILD, S_MULTIMETER);
      
      Serial.println("Startup completed");
      }
      
      void loop() 
      { 
      
      digitalWrite(6,HIGH);
      delay(100);
      
      gw.process();
      //gw.begin(incomingMessage, NODE_ID, false);
      unsigned long currentTime = millis();
      
      //See if we have the counter/pulse from Domoticz - and ask for it if we dont.
      if (!pcReceived && (currentTime - lastSend > 5000)) { 
      gw.begin(incomingMessage, NODE_ID, false);
      gw.request(CHILD_ID, V_VAR1);
      Serial.println("Request pulsecount");
      lastSend=currentTime;
      gw.process();
      return;
      }
      if (!pcReceived) {
      return;
      }
      
      //Read if the bucket tipped over
      reedState = digitalRead(DIGITAL_INPUT_SENSOR);
      boolean tipped = oldReedState != reedState; 
      
      //BUCKET TIPS!
      if (tipped==true) {
      gw.begin(incomingMessage, NODE_ID, false);
      Serial.println("The bucket has tipped over...");
      oldReedState = reedState;
      hwRainVolume = hwRainVolume + bucketSize;
      gw.send(volumeMsg.set((float)hwRainVolume,1));
      gw.wait(1000);
      fullCounter = fullCounter + bucketSize;
      
      //Count so we send the counter for every 1mm
      if(fullCounter >= 1){
      hwPulseCounter++;
      gw.send(lastCounterMsg.set(hwPulseCounter));
      gw.wait(1000);
      fullCounter = 0;
      }
      readVcc(); 
      }
      
      if (tipped==false) {
      
      //No bucket tipped over last sleep-period, check battery then...
      readVcc(); 
      }
      
      lastSend=currentTime;
      Serial.println("sleep");
      digitalWrite(6,LOW);
      delay(1000);
      gw.sleep(INTERRUPT, CHANGE, SLEEP_TIME); 
      //The interupt can be CHANGE or FALLING depending on how you wired the hardware.
      }
      
      //Read if we have a incoming message.
      void incomingMessage(const MyMessage &message) {
      if (message.type==V_VAR1) {
      hwPulseCounter = message.getULong();
      hwRainVolume = hwPulseCounter;
      pcReceived = true;
      Serial.print("Received last pulse count from gw: ");
      Serial.println(hwPulseCounter); 
      }
      }
      /*
      void batM() //The battery calculations
      {
      delay(500);
      // Battery monitoring reading
      int sensorValue = analogRead(BATTERY_SENSE_PIN); 
      delay(500);
      
      // Calculate the battery in %
      float Vbat = sensorValue * VBAT_PER_BITS;
      int batteryPcnt = static_cast<int>(((Vbat-VMIN)/(VMAX-VMIN))*100.);
      Serial.print("Battery percent: "); Serial.print(batteryPcnt); Serial.println(" %"); 
      
      // Add it to array so we get an average of 3 (3x20min)
      batArray[batLoop] = batteryPcnt;
      
      if (batLoop > 1) { 
      batteryPcnt = (batArray[0] + batArray[1] + batArray[2]);
      batteryPcnt = batteryPcnt / 3;
      
      if (batteryPcnt > 100) {
      batteryPcnt=100;
      }
      
      Serial.print("Battery Average (Send): "); Serial.print(batteryPcnt); Serial.println(" %");
      gw.sendBatteryLevel(batteryPcnt);
      batLoop = 0;
      
      //Sends 1 per hour as a heartbeat.
      gw.send(volumeMsg.set((float)hwRainVolume,1));
      gw.send(lastCounterMsg.set(hwPulseCounter));
      }
      else 
      {
      batLoop++;
      }
      }
      */
      long readVcc() {
      Serial.println("readVcc");
      // Read 1.1V reference against AVcc
      ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      delay(2); // Wait for Vref to settle
      ADCSRA |= _BV(ADSC); // Convert
      while (bit_is_set(ADCSRA,ADSC));
      result = ADCL;
      result |= ADCH<<8;
      result = 1126400L / result; // Back-calculate AVcc in mV
      //return result;
      gw.begin(incomingMessage, NODE_ID, false);
      batteryPcnt = (result - 3300) * 0.111111;
      batteryVolt = result/1000.000;
      gw.sendBatteryLevel(batteryPcnt);
      gw.send(battMsg.set(batteryVolt, 3));
      /*Serial.print("battery volt:");
      Serial.println(batteryVolt, 3);
      Serial.print("battery percent:");
      Serial.println(batteryPcnt);
      */
      }
      
      posted in Domoticz
      flopp
      flopp
    • RE: Sensor NRF24L01+ sleep current

      I change the NRF for sensor and now I measure 0,04mA(41,8uA) with all equipment connected

      I am happy

      posted in Troubleshooting
      flopp
      flopp
    • RE: 💬 Power Meter Pulse Sensor

      @asgardro
      What does the serial output in arduino says?

      posted in Announcements
      flopp
      flopp
    • RE: Water tank instant volume

      @brix7be said:

      The UI edit button is included to the domoticz frontend or it is in backend(to change the icon and the axis label)?

      Here you can read how to add custom icons in Domoticz
      http://www.domoticz.com/wiki/Custom_icons_for_webinterface

      posted in Domoticz
      flopp
      flopp
    • RE: 💬 Air Humidity Sensor - DHT

      @hek @mfalkvidd I read that you discussed about PIN 2 and 3.

      Code say PIN 2, Wiring things up say PIN 2 and picture shows PIN 3.

      It can't use PIN 2 or can it, PIN 2 is used by the radio, or am I to tired :)?

      posted in Announcements
      flopp
      flopp
    • RE: Count car-starts

      New version 1.1

      // Made by Daniel Nilsson
      // Tested with Domoticz 2.4440
      // 2016-03-12
      
      #include <SPI.h>
      #include <MySensor.h>
      
      #define CHILD_ID 0                          // Id of the sensor child
      #define NODE_ID AUTO                        // a number or AUTO to let controller assign
      #define SKETCH_NAME "Car start counter"     // Change to a fancy name you like
      #define SKETCH_VERSION "1.1"                // Your version
      
      int Controller;                             // Current start counts from Controller, like Domoticz
      boolean pcReceived = false;                 // If we have recieved the start counts from Controller or not 
      int starts;                                 // summary of all starts to be sent to Controller
      int eeprom;                                 // start counts read from/to be stored in EEPROM
      
      MySensor gw;
      MyMessage volumeMsg(CHILD_ID,V_RAIN);
      MyMessage lastCounterMsg(CHILD_ID,V_VAR1);
      
      void setup()
      {          
        delay(500);   // wait for radio
        delay(2*60000);  // Allow time if USB/cigarett plug is powered before you turned the key
      
        //Begin
        gw.begin(incomingMessage, NODE_ID, false);
        
        // Send the Sketch Version Information to the Gateway
        gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
      
        // Register this device as Rain sensor (will not show in Domoticz until first value arrives)
        gw.present(CHILD_ID, S_RAIN);       
        Serial.println("");
        eeprom = gw.loadState(0);                       // read EEPROM
        Serial.print(eeprom);                           // print EEPROM
        Serial.println(" starts have not been sent");
        Serial.println("add 1 start");
        Serial.print(eeprom);
        Serial.print("+1=");
        eeprom = eeprom + 1;
        Serial.println(eeprom);
        gw.saveState(0,eeprom);                         // store to EEPROM at position 0
        Serial.println("");
        
        Serial.println("Startup completed");
      }
      
      void loop()
      { 
        
      //gw.process();
      
          //See if we have the start counts from Controller - and ask for it if we dont.
          if (!pcReceived) {
            
            Serial.println("Request start counts");
            gw.request(CHILD_ID, V_VAR1);
            //gw.process();
            gw.wait(5000);
            return;
          }
      
      Serial.println("");
      eeprom = gw.loadState(0);                     // read EEPROM
      Serial.print(eeprom);
      Serial.println(" starts have not been sent");
      Serial.print(Controller);
      Serial.println(" starts from Controller = ");    
      starts = Controller + eeprom;                 // total starts
      Serial.print(eeprom);
      Serial.print("+");
      Serial.print(Controller);
      Serial.print("=");
      Serial.println(starts);
      Serial.print("Send ");
      Serial.print(starts);
      Serial.println(" to Controller");
      Serial.println("");
      
      resend((volumeMsg.set(starts)), 5);
      //gw.send(volumeMsg.set(starts));
      resend((lastCounterMsg.set(starts)), 5);
      //gw.send(lastCounterMsg.set(starts));
      gw.wait(1000);
      Serial.println("");
      Serial.println("store 0 to EEPROM");
      gw.saveState(0,0);                            // set 0 start to EEPROM, all have been sent
      Serial.println("sleep");                      // mission accomplished
      while(1){}
      
      }
      
      // check if "st:fail" during gw.send, thanks n3ro
      void resend(MyMessage &msg, int repeats)
      {
        int repeat = 1;
        boolean sendOK = false;
        int repeatdelay = 2000;
      
      
        while ((sendOK == false) and (repeat < repeats)) {
          if (gw.send(msg)) {
            sendOK = true;
          }
          else {
            sendOK = false;
            Serial.print("Error ");
            Serial.println(repeat);
          }
          repeat++; delay(repeatdelay);
        }
        if (sendOK == false && repeat == repeats){
          loop();
        }
      }
      
      //Read if we have a incoming message.
      void incomingMessage(const MyMessage &message) {
        if (message.type==V_VAR1) {
          Controller = message.getULong();
          pcReceived = true;
          Serial.print("Received start counts from Controller: ");
          Serial.println(Controller);   
        }
      }
      

      thanks to @n3ro for st:fail and @sundberg84 for the hint
      @mfalkvidd maybe next version will have timestamp from Domoticz, i am still waiting for an answer if I can send date and time to database. As you can see I have removed while-loop until it successfully sent data to Controller

      posted in My Project
      flopp
      flopp
    • RE: Creating a RGB selector and adding it to Domoticz

      This is the code i am using and it is working fine with MyS 1.5.1 and Domoticz 3.5877.

      /*PROJECT: MySensors / RGB test for Light & Sensor
       PROGRAMMER: AWI/GizMoCuz
       DATE: september 27, 2015/ last update: October 10, 2015
       FILE: AWI_RGB.ino
       LICENSE: Public domain
      
       Hardware: Nano and MySensors 1.5
          
       Special:
        uses Fastled library with NeoPixel (great & fast RBG/HSV universal library)       https://github.com/FastLED/FastLED
       
       Remarks:
        Fixed node-id
        Added option to request/apply last light state from gateway
        
       Domoticz typicals - 2015 10 10:
        - Domoticz is using HUE values internally, there might be a slight difference then using direct RGB colors.
      */
      
      #include <MySensor.h>
      #include <SPI.h>
      #include <FastLED.h>
      
      
      const int stripPin = 4 ;                  // pin where 2812 LED strip is connected
      
      const int numPixel = 3 ;                  // set to number of pixels
      
      #define NODE_ID 254                       // fixed MySensors node id
      
      #define CHILD_ID 0                  // Child Id's
      
      CRGB leds[numPixel];
      
      char actRGBvalue[] = "000000";               // Current RGB value
      uint16_t actRGBbrightness = 0xFF ;         // Controller Brightness 
      int actRGBonoff=0;                        // OnOff flag
      
      MySensor gw;
      
      MyMessage lastColorStatusMsg(CHILD_ID,V_VAR1);
      
      void setup() {
        FastLED.addLeds<NEOPIXEL, stripPin >(leds, numPixel); // initialize led strip
      
        gw.begin(incomingMessage, NODE_ID, false);      // initialize MySensors
        gw.sendSketchInfo("AWI RGB Light", "1.1");
        gw.present(CHILD_ID, S_RGB_LIGHT);        // present to controller
      
        // Flash the "hello" color sequence: R, G, B, black. 
        colorBars();
      
        //Request the last stored colors settings
        gw.request(CHILD_ID, V_VAR1);
      }
      
      void loop() {
        gw.process();                       // wait for incoming messages
      }
      
      void colorBars()
      {
        SendColor2AllLEDs( CRGB::Red );   FastLED.show(); delay(500);
        SendColor2AllLEDs( CRGB::Green ); FastLED.show(); delay(500);
        SendColor2AllLEDs( CRGB::Blue );  FastLED.show(); delay(500);
        SendColor2AllLEDs( CRGB::Black ); FastLED.show(); delay(500);
      } 
      
      void SendColor2AllLEDs(const CRGB lcolor)
      {
        for(int i = 0 ; i < numPixel ; i++) {
          leds[i] = lcolor;
        }
      }
      
      void SendLastColorStatus()
      {
        String cStatus=actRGBvalue+String("&")+String(actRGBbrightness)+String("&")+String(actRGBonoff);
        gw.send(lastColorStatusMsg.set(cStatus.c_str()));
      }
      
      String getValue(String data, char separator, int index)
      {
       int found = 0;
        int strIndex[] = {0, -1};
        int maxIndex = data.length()-1;
        for(int i=0; i<=maxIndex && found<=index; i++){
        if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
       }
        return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
      }
      
      void incomingMessage(const MyMessage &message) {
        if (message.type == V_RGB) {            // check for RGB type
          actRGBonoff=1;
          strcpy(actRGBvalue, message.getString());    // get the payload
          SendColor2AllLEDs(strtol(actRGBvalue, NULL, 16));
          SendLastColorStatus();
        }
        else if (message.type == V_DIMMER) {           // if DIMMER type, adjust brightness
          actRGBonoff=1;
          actRGBbrightness = map(message.getLong(), 0, 100, 0, 255);
          FastLED.setBrightness( actRGBbrightness );
          SendLastColorStatus();
        }
        else if (message.type == V_STATUS) {           // if on/off type, toggle brightness
          actRGBonoff = message.getInt();
          FastLED.setBrightness((actRGBonoff == 1)?actRGBbrightness:0);
          SendLastColorStatus();
        }
        else if (message.type==V_VAR1) {            // color status
          String szMessage=message.getString();
          strcpy(actRGBvalue, getValue(szMessage,'&',0).c_str());
          actRGBbrightness=atoi(getValue(szMessage,'&',1).c_str());
          actRGBonoff=atoi(getValue(szMessage,'&',2).c_str());
          SendColor2AllLEDs(strtol(actRGBvalue, NULL, 16));
          FastLED.setBrightness((actRGBonoff == 1)?actRGBbrightness:0);
        }
        FastLED.show();
      }
      
      

      When you get the RGB Light in Device, add it and edit the Device to be a Dimmer instead then click on the three cubes and start to select the color you like

      posted in Domoticz
      flopp
      flopp
    • RE: Question about sleep until interrupt

      @TheoL
      You can read here, under Sleeping
      http://www.mysensors.org/download/sensor_api_15

      posted in Troubleshooting
      flopp
      flopp
    • RE: 💬 Power Meter Pulse Sensor

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

      posted in Announcements
      flopp
      flopp
    • RE: Oil burner

      Hi, I am using a node that count how many times I start my car.
      I am using the S_Rain type since that data is resets every midnight.
      But I am facing problems with Domotics. If no data is sent to Domoticz after 3 hours it will be showing next value in the past
      See my question on Domoticz forum here https://www.domoticz.com/forum/viewtopic.php?f=28&t=11088
      my sketch is here http://forum.mysensors.org/topic/3355/count-car-starts/2

      posted in My Project
      flopp
      flopp
    • RE: Example code - DallasTemperatureSensor.ino

      @mfalkvidd
      💃

      posted in Feature Requests
      flopp
      flopp
    • RE: nRF frequency and channels

      @mfalkvidd
      Thanks

      #define MY_RF24_CHANNEL X, where X is the number to the left below

      0 => 2400 Mhz (RF24 channel 1)
      1 => 2401 Mhz (RF24 channel 2)
      76 => 2476 Mhz (RF24 channel 77) standard
      83 => 2483 Mhz (RF24 channel 84)
      124 => 2524 Mhz (RF24 channel 125)
      125 => 2525 Mhz (RF24 channel 126)

      Below is the Control Channel for WiFi and frequency.
      0_1473089615990_0917tab01.jpg
      12, 13, 14 not available in all countries

      1 GHz = 1000 MHz

      posted in Troubleshooting
      flopp
      flopp
    • RE: MySensors 2.2.0 released

      Thank you very much. I donated USD 10 as a small thank you for all your work. I hope more people do the same.

      Very nice text when you start a node, I have only tried 2.2 on my GW and it looks like some of my sending errors disappeared.

      This is what you see when you start a node

      __  __       ____
      |  \/  |_   _/ ___|  ___ _ __  ___  ___  _ __ ___
      | |\/| | | | \___ \ / _ \ `_ \/ __|/ _ \| `__/ __|
      | |  | | |_| |___| |  __/ | | \__ \  _  | |  \__ \
      |_|  |_|\__, |____/ \___|_| |_|___/\___/|_|  |___/
             |___/                      2.2.0
      

      Why not add two | in the "o" then i will look like this

      
       __  __       ____
      |  \/  |_   _/ ___|  ___ _ __  ___  ___  _ __ ___
      | |\/| | | | \___ \ / _ \ `_ \/ __|/ _ \| `__/ __|
      | |  | | |_| |___| |  __/ | | \__ \ |_| | |  \__ \
      |_|  |_|\__, |____/ \___|_| |_|___/\___/|_|  |___/
              |___/                      2.2.0
      
      
      posted in Announcements
      flopp
      flopp
    • RE: Count car-starts

      Keep-alive version. I noticed when this Node didn't get any response from Controller it send back 0, which means that this day will be very many starts

      // Made by Daniel Nilsson
      // Tested with Domoticz 3.4967
      // Version 1.1
      // 2016-05-10
      
      //Keep-alive since Domoticz seems to not storing data if not data comes in for 3 hours(user setting)
      
      #include <SPI.h>
      #include <MySensor.h>
      
      #define CHILD_ID 0                          // Id of the sensor child
      #define NODE_ID 7                        // same ID as real Car Counter
      
      int Controller;                             // Current start counts from Controller, like Domoticz
      
      MySensor gw;
      MyMessage volumeMsg(CHILD_ID,V_RAIN);
      MyMessage lastCounterMsg(CHILD_ID,V_VAR1);
      
      void setup()
      {          
        delay(500);   // wait for radio
        
        //Begin
        gw.begin(incomingMessage, NODE_ID);
        // Register this device as Rain sensor (will not show in Domoticz until first value arrives)
        gw.present(CHILD_ID, S_RAIN);       
      }
      
      void loop()
      { 
        
          //Ask for starts from Controller.
        
            Serial.println("Request start counts");
            //gw.request(CHILD_ID, V_VAR1);
            while (Controller == 0) {
              gw.request(CHILD_ID, V_VAR1);
              Serial.println("No response from Controller");
              gw.wait(60000);
              }
            gw.wait(5000);
            
      if (!resend((volumeMsg.set(Controller)), 5))return;
      gw.wait(1000);
      gw.sleep(120*60000); //less then timeout in Controller
      }
      
      // check if "st:fail" during gw.send, thanks n3ro
      bool resend(MyMessage &msg, int repeats)
      {
        int repeat = 1;
        boolean sendOK = false;
        int repeatdelay = 2000;
      
        while ((sendOK == false) and (repeat < repeats)) {
          if (gw.send(msg)) {
            sendOK = true;
          }
          else {
            sendOK = false;
            Serial.print("Error ");
            Serial.println(repeat);
          }
          repeat++; delay(repeatdelay);
        }
        if (sendOK == false && repeat == repeats){
          return false;
        }
        return true;
      }
      
      //Read if we have a incoming message.
      void incomingMessage(const MyMessage &message) {
        if (message.type==V_VAR1) {
          Controller = message.getULong();
          //pcReceived = true;
          Serial.print("Received start counts from Controller: ");
          Serial.println(Controller);   
        }
      }
      
      posted in My Project
      flopp
      flopp
    • RE: [Tutorial] How to burn 1Mhz & 8Mhz bootloader using Arduino IDE 1.6.5-r5

      I tried with above 8MHz setting and then I can upload to ATmega with a FTDI.

      I will try to change settings one-by-one until I cant upload and write back here.

      posted in Development
      flopp
      flopp
    • Help with Controller choice

      I have used MySensors for one week now.
      Right now I am using Domoticz.
      But today I understood that the data will not be stored more than a week or so. Yearly data will only be maximum and minimum values.

      I like Domoticz but I am missing the data storage. I want to compare data from other years. I only have sensors today, temperature, humidity, pressure.

      I have a 24/7 running Windows 7 at home where I today gave Domoticz. I have a WiFi CC3000 gateway.
      I am looking for a software that can collect data in my house but I want to be able to send the data to my web hotel, I have MySQL running there. This is to be able to reach the data from anywhere. I know I can open ports in my firewall but even then, e.g. from my office I can't reach it because our IT have blocked almost everything.

      Any ideas what I can run?

      Is it possible to run like Domoticz on Amazon Server, Microsoft Azure, data center?

      posted in Controllers
      flopp
      flopp
    • RE: Force re-routing

      In version 1.5.1 the node need 6 failures in a row to start looking for new way to GW.

      You can hold your hands around the node to make the signal weak.

      Maybe power off GW and wait 6 sends to make the node to look for new way then when you see LED flashing in repeater you can power on the GW again.

      posted in Troubleshooting
      flopp
      flopp
    • RE: Solar Powered Soil Moisture Sensor

      update
      I've let it be outdoor in the sun during 2-3 days now and it works well.
      yesterday I took one of them and placed it in the garage, totally black whole day not even a lamp.
      red line is when I moved it to the garage.
      it is sending every 10 second. After ~20 hours the battery was to low to be able to run Pro Mini
      0_1465505284492_volt.png

      posted in My Project
      flopp
      flopp
    • RE: How to find out if message was successfully delivered?

      @arraWX
      I solved it by doing this, it is just a few rows from the sketch

      
      MyMessage voltage_msg(CHILD_ID_BATTERY, V_VOLTAGE);
      ...
      void setup()
      gw.present(CHILD_ID_BATTERY, S_MULTIMETER);
      ...
      void loop()
      ...
      int sensorValue = analogRead(A0);
      float batteryVolt=sensorValue*(3.3/1023);
      resend((voltage_msg.set(batteryVolt, 3)), 10);
      
      void resend(MyMessage &msg, int repeats)
      {
        int repeat = 1;
        int repeatdelay = 0;
        boolean sendOK = false;
      
        while ((sendOK == false) and (repeat < repeats)) {
          if (gw.send(msg)) {
            sendOK = true;
          } else {
            sendOK = false;
            Serial.print("Error ");
            Serial.println(repeat);
            repeatdelay += 500;
          } repeat++; delay(repeatdelay);
        }
      }
      
      

      which means, it will send batteryVolt with 3 decimals to Controller and try 10 times.
      If it doesn't get OK after 10 times it will not try again until it is time to send data next time.

      posted in Development
      flopp
      flopp
    • RE: Lua script

      This my script with decimals

      commandArray = {}
      
      if devicechanged['Panna_V'] or devicechanged['Huset_V'] then
          local panna_v = otherdevices_svalues["Panna_V"]
          local huset_v = otherdevices_svalues["Huset_V"]
          local hushall_kwh = uservariables['Hushåll_kWh']
          local huset_kwh = uservariables['Huset_kWh']
          local panna_kwh = uservariables['Panna_kWh']
          
          local panna, energy, huset, energy2
          --print(pan)
          --print(hus)
          
          _,_,panna, energy = string.find(panna_v, "(.+);(.+)")
          _,_,huset, energy2 = string.find(huset_v, "(.+);(.+)")
          --print(panna)
          --print(huset)
          --print(energy)
          --print ("energy2="..energy2)
          --print ("huset_kwh="..huset_kwh)
          husetdiff_kwh = energy2 - huset_kwh
          --print ("husetdiff kwh")
          --print (husetdiff_kwh)
          
          --print ("energy="..energy)
          --print ("panna_kwh="..panna_kwh)
          pannadiff_kwh = energy - panna_kwh
          --print ("pannadiff kwh")
          --print (pannadiff_kwh)
          
          hushal_kwh = husetdiff_kwh - pannadiff_kwh
          hushall_kwh = hushall_kwh + hushal_kwh
          --print ("hushåll_kwh")
          --print (hushall_kwh)
          panna = tonumber(panna)
          huset = tonumber(huset)
          hush = huset - panna
          ener = energy2 - energy
          
          --print(hush)
          --print(ener)
          if hush > 0 then
          
              --print(el)
              commandArray['Variable:Hushåll_kWh']= tostring(hushall_kwh)
              commandArray['Variable:Huset_kWh']= tostring(energy2)
              commandArray['Variable:Panna_kWh']= tostring(energy)
                  
              abc = tostring(hush)
              def = tostring(hushall_kwh)
              commandArray['UpdateDevice'] = '272|0|'..abc..';'..def..''
          else
          end
          
      end
      return commandArray
      

      I am using Dummy, Electric(Instant&Counter) version 3.5721 of DZ

      Panna_V(heating system) and Huset_V(whole house) is electric usage meters that report every 5 minute. I use my Dummy to show my electric consumption without(minus) my heating system

      posted in Troubleshooting
      flopp
      flopp
    • RE: Solar Powered Soil Moisture Sensor

      @martinhjelmare said:

      @flopp

      I like this design. Do you think it will survive the Swedish winter days with their limited sun hours?

      Yes, I think so. Today I send data every 10 seconds so if I send it once an hour it should not be a problem during winter. It will test to simulate rain and see if it is sealed enough.

      posted in My Project
      flopp
      flopp
    • RE: How to find out if message was successfully delivered?

      @BartE said:

      gw.begin(incomingMessage, AUTO, true);
      

      you can actually remove TRUE, that mean this is a Repeater Node

      posted in Development
      flopp
      flopp
    • RE: Not able to add sensors as device in Domoticz

      You cant use V_LEVEL for S_HUM

      For S_HUM you must use V_HUM

      https://www.mysensors.org/download/serial_api_20

      posted in Troubleshooting
      flopp
      flopp
    • RE: Solar Powered Soil Moisture Sensor

      @pettib said:

      @flopp Maybe i miss something but I think the connector should be mounted between the battery and the Vin on the step-up. You mounted it on the A0, it´s just the voltage check port.

      Thanks, I was to quick when adding the connectors

      In the original lamp there was what i think is a charge regulator between the solar cell and the batteri, did you keep that one or you just put the solar cell to the battery ?

      I removed the small IC, YX8108. Below is a schematic for YX8108
      0_1465929144673_yx8108.png

      posted in My Project
      flopp
      flopp
    • RE: Radio FAIL after ~3 weeks [SOLVED]

      @Reza
      What kind of nRF do you use?

      I power my nRF directly from Arduino Nano.

      I don't have problem anymore but maybe it will be a problem again in the future. I think your problem can be that the node doesn't have contact with your gateway.

      Try to put a repeater in the middle between node and GW

      posted in Troubleshooting
      flopp
      flopp
    • RE: Office plant monitoring

      @Fat-Fly
      I have used the latest version of this sketch and it worked perfect.
      If you use the latest version it must be something with your PC/Arduino IDE

      posted in My Project
      flopp
      flopp
    • RE: BH1750 library issue with using sleep

      @Rayne
      Can you upload your code. Two days ago I built a battery powered node with BH1750 and don't have any problem.
      MySensors version?
      Running on a Arduino Nano?
      Battery powered?
      Serial/Ethernet GW?

      posted in Development
      flopp
      flopp
    • RE: Solar Powered Soil Moisture Sensor

      @Nca78 said:

      First, thank you very much for making these tests, I found some similar garden lamps in a local store and thought they were cheap so I bought one to have a look. Seems they were not so cheap as I paid nearly 3$ despite living in a developing country 😄

      Thank you. $3 is not bad but expensive compared to mine 🙂

      I will make a test with it as soon as I find a step up accepting the 1.xV of the battery, but I'm not sure if it will really work as the battery inside mine is a tiny V80h with a very limited 60mAh capacity, not sure if it will survive the sending of data...

      This is what I use as step-up, search for that product you will find cheaper than $1.49
      http://www.ebay.com/itm/DC-DC-0-8-3V-to-3-3V-Step-UP-Boost-Power-Board-Module-Converter-Voltage-RF-/282029936915?hash=item41aa4b5113:g:3GAAAOSw1DtXLS7Q

      I would put some hot glue there too, no ? When all connections are checked and the board is running fine you could even sink the whole electronic in hot glue to solve these problems "forever" ?

      Yes, why not, sounds like a good idea. But keep TX, RX, RESET and GND available to be able to update the sketch

      posted in My Project
      flopp
      flopp
    • RE: Temperature sensor on ESP8266

      @martinus
      Hi
      I have been using esp8266 for temp/hum sensors that sends the data to a php webpage.
      I will try I later but I just reed that it seems to be possible to use same thing for Domoticz.

      http://www.domoticz.com/wiki/Domoticz_API/JSON_URL's

      posted in Hardware
      flopp
      flopp
    • RE: [Solved] Repeater node causing Problems

      I have had very strange errors and I don't know what I found out. 😐
      I had a repeater with a nRF24 PA+LNA working good for about 1 year, suddenly this repeater causing that the GW got hanged, no data was received from any nodes.
      I power off the repeater down, restarted GW and everything started to work normally.
      Last week I took time to solve the problem, it was still annoying me!!!
      Reprogram the same Arduino Nano and nRF with PA+LNA, worked for 2 days, then stopped.
      Same Arduino Nano but changed to nRF24 without PA+LNA, worked 1-2 days then stopped.
      Changed to Arduino UNO and nRF with PA+LNA, worked 2 days.
      Arduino UNO and nRF24 without PA+LNA worked 2 days.

      I was so frustrated and didn't had any idea. I had been running 2.3.0 on almost all my nodes, so I tried to change GW to version 2.3.1 and Repeater to version 2.3.1(Arduino UNO with nRF24 without PA+LNA) now it has worked for at least 1 week.

      My Arduino Nano is fake and UNO is genuine.

      Maybe you can get some help from this? 🙂

      posted in Troubleshooting
      flopp
      flopp
    • RE: two energy meter

      @mfalkvidd

      Thanks.

      Wow 12 counts!!!

      I will go for 2 MCU's then I can lay down in the sofa rest of the day instead 😄

      posted in My Project
      flopp
      flopp
    • RE: Temperature sensor on ESP8266

      This is my code. Tested and working fine on a ESP-01, powered from PC USB.

      Question, shall I include the license text below?
      "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."

      License text copied from an example from MySensors.org

      /*
       * Created by Daniel Nilsson
       *
       * 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 - Daniel Nilsson
       * 
       * DESCRIPTION
       * This sketch provides an example how to implement a Dallas OneWire temperature sensor (DS18B20 or equal) to send data to Domoticz-server (www.domoticz.com)
       * Sleep function is disable as default
       * Temperature value will be -555 as an indication that the sensor is not working properly, value will be -555 if one of the following criteria are met; above 80; below -100; exakt 0.00
       */
      
      /* remove this line to activate
      // ***sleep function starts here***
      // you must connect a cable from pin 8 on ESP8266 IC to Reset pin otherwise sleep doesn't work
      
      extern "C" {
      #include "user_interface.h" //for sleep
      }
      
      // ***sleep function ends here***
      */ //remove this line to activate
      
      #include <ESP8266WiFi.h>
      
      const char* ssid = "SSID"; // ***your WiFi name***
      const char* password = "password"; // ***your WiFi password***
      const char* server = "123.123.123.123"; // ***IP adress for Domoticz***
      int port = 8080; // ***port for Domoticz***
      String idx = "1"; // ***id for your sensor***
      
      WiFiClient client;
      
      #include <OneWire.h> //OneWire library
      #include <DallasTemperature.h> // Dallas library
      
      #define ONE_WIRE_BUS 2 // Data wire is plugged into port 2 on the ESP
      
      OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
      
      DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature. 
      
      void setup() {
        Serial.begin(115200);
        delay(10);
        sensors.begin(); //start Dallas sensor
       
        WiFi.begin(ssid, password); // connect to WiFi
       
        Serial.println();
        Serial.println();
        Serial.print("Connecting to ");
        Serial.println(ssid);
       
        WiFi.begin(ssid, password);
       
        while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          Serial.print(".");
        }
        Serial.println("");
        Serial.println("WiFi connected");
       
      }
       
      void loop() {
        
        float temp;
        // call sensors.requestTemperatures() to issue a global temperature 
        // request to all devices on the bus
        Serial.print("Requesting temperatures...");
        sensors.requestTemperatures(); // Send the command to get temperatures
        Serial.println("DONE");
        
        Serial.print("Temperature for the device 1 (index 0) is: ");
        Serial.println(sensors.getTempCByIndex(0));  
        temp=sensors.getTempCByIndex(0);
       
        if (client.connect(server,port)) {
      
        client.print("GET /json.htm?type=command&param=udevice&idx="+idx+"&nvalue=0&svalue=");
          if(temp>80 || temp<-100 || temp==0.00) { // limits if sensor is broken or not connected
            client.print( "-555" ); //Bad value indication
            }
          else{
            client.print( temp );
            }
        
        client.println( " HTTP/1.1");
        client.print( "Host: " );
        client.println(server);
        client.println( "Connection: close" );
        client.println();
        client.println();
        client.stop();
      
        Serial.print("Temperature: ");
        Serial.print(temp);
        Serial.println(" degrees Celcius");
        
        }
        
        Serial.println("Waiting...");
        delay(60000); // 60 seconds
      }
      
      posted in Hardware
      flopp
      flopp
    • Dust Sensor

      I think my dust sensor is working fine with the second sketch i have attached in this post.
      I think some rows are missing in the MySensors sketch

      I can be wrong but my dust sensor didn't work with MySensors sketch, i had to modify it.

      Anyone that have this sensor and a working sketch?

      /**
       * 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 - epierre
       * Converted to 1.4 by Henrik Ekblad
       * 
       * DESCRIPTION
       * Arduino Dust Sensort
       *
       * connect the sensor as follows :
       * 
       *   VCC       >>> 5V
       *   A         >>> A0
       *   GND       >>> GND
       *
       * Based on: http://www.dfrobot.com/wiki/index.php/Sharp_GP2Y1010AU 
       * Authors: Cyrille Médard de Chardon (serialC), Christophe Trefois (Trefex)
       * 
       * http://www.mysensors.org/build/dust
       * 
       */
      
      #include <MySensor.h>  
      #include <SPI.h>
      
      #define CHILD_ID_DUST 0
      #define DUST_SENSOR_ANALOG_PIN 1
      
      unsigned long SLEEP_TIME = 30*1000; // Sleep time between reads (in milliseconds)
      //VARIABLES
      int val = 0;           // variable to store the value coming from the sensor
      float valDUST =0.0;
      float lastDUST =0.0;
      int samplingTime = 280;
      int deltaTime = 40;
      int sleepTime = 9680;
      float voMeasured = 0;
      float calcVoltage = 0;
      float dustDensity = 0;
      
      MySensor gw;
      MyMessage dustMsg(CHILD_ID_DUST, V_LEVEL);
      
      void setup()  
      {
        gw.begin();
      
        // Send the sketch version information to the gateway and Controller
        gw.sendSketchInfo("Dust Sensor", "1.1");
      
        // Register all sensors to gateway (they will be created as child devices)
        gw.present(CHILD_ID_DUST, S_DUST);  
         
      }
      
      void loop()      
      {    
        uint16_t voMeasured = analogRead(DUST_SENSOR_ANALOG_PIN);// Get DUST value
      
        // 0 - 5V mapped to 0 - 1023 integer values
        // recover voltage
        calcVoltage = voMeasured * (5.0 / 1024.0);
      
        // linear eqaution taken from http://www.howmuchsnow.com/arduino/airquality/
        // Chris Nafis (c) 2012
        dustDensity = (0.17 * calcVoltage - 0.1)*1000;
       
        Serial.print("Raw Signal Value (0-1023): ");
        Serial.print(voMeasured);
        
        Serial.print(" - Voltage: ");
        Serial.print(calcVoltage);
        
        Serial.print(" - Dust Density: ");
        Serial.println(dustDensity); // unit: ug/m3
       
        if (ceil(dustDensity) != lastDUST) {
            gw.send(dustMsg.set((int)ceil(dustDensity)));
            lastDUST = ceil(dustDensity);
        }
       
        gw.sleep(SLEEP_TIME);
      }
      
      Int val = 0;
      

      this is not in use anywhere in the code and if you comment it out it will still compile
      can be deleted
      2.
      You need to connect 6 cables otherwise it will not work.
      In beginning it says

       *   VCC       >>> 5V
       *   A         >>> A0
       *   GND       >>> GND
      

      Here you can find how it must be connected
      https://www.sparkfun.com/datasheets/Sensors/gp2y1010au_e.pdf
      and here
      http://arduinodev.woofex.net/2012/12/01/standalone-sharp-dust-sensor/

      Original sketch for Sharp GP2Y1010AU0F is like this

      /*
       Standalone Sketch to use with a Arduino Fio and a
       Sharp Optical Dust Sensor GP2Y1010AU0F
       
       Blog: http://arduinodev.woofex.net/2012/12/01/standalone-sharp-dust-sensor/
       Code: https://github.com/Trefex/arduino-airquality/
       
       For Pin connections, please check the Blog or the github project page
       Authors: Cyrille Médard de Chardon (serialC), Christophe Trefois (Trefex)
       Changelog:
         2012-Dec-01:  Cleaned up code
       
       This work is licensed under the
       Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
       To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
       or send a letter to Creative Commons, 444 Castro Street, Suite 900,
       Mountain View, California, 94041, USA.
      */
       
      int measurePin = 6;
      int ledPower = 12;
       
      int samplingTime = 280;
      int deltaTime = 40;
      int sleepTime = 9680;
       
      float voMeasured = 0;
      float calcVoltage = 0;
      float dustDensity = 0;
       
      void setup(){
        Serial.begin(9600);
        pinMode(ledPower,OUTPUT);
      }
       
      void loop(){
        digitalWrite(ledPower,LOW); // power on the LED
        delayMicroseconds(samplingTime);
       
        voMeasured = analogRead(measurePin); // read the dust value
       
        delayMicroseconds(deltaTime);
        digitalWrite(ledPower,HIGH); // turn the LED off
        delayMicroseconds(sleepTime);
       
        // 0 - 3.3V mapped to 0 - 1023 integer values
        // recover voltage
        calcVoltage = voMeasured * (3.3 / 1024);
       
        // linear eqaution taken from http://www.howmuchsnow.com/arduino/airquality/
        // Chris Nafis (c) 2012
        dustDensity = 0.17 * calcVoltage - 0.1;
       
        Serial.print("Raw Signal Value (0-1023): ");
        Serial.print(voMeasured);
       
        Serial.print(" - Voltage: ");
        Serial.print(calcVoltage);
       
        Serial.print(" - Dust Density: ");
        Serial.println(dustDensity);
       
        delay(1000);
      }
      
      1. MySensors sketch doesn't include any POWERLED, without this it cant work
      int ledPower = 12;
      
      posted in Bug Reports
      flopp
      flopp
    • RE: Unique ID-value DS18B20 Temperature sensors

      I solved it like this
      https://forum.mysensors.org/topic/4143/about-ds18b20-onewire/2

      posted in My Project
      flopp
      flopp
    • RE: LDO 9 volt

      @ahmedadelhosni
      Thanks, yes that one looks perfect.
      http://www.farnell.com/datasheets/1268701.pdf

      posted in Hardware
      flopp
      flopp
    • EnergyMeterPulseSensor

      Found some spelling mistake in the text

       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
      

      disctance sensor HC-SR04 = LM393

      #define PULSE_FACTOR 1000       // Nummber of blinks per KWH of your meeter
      

      nummber = number
      meeter = meter

      unsigned long SEND_FREQUENCY = 20000; // Minimum time between send (in milliseconds). We don't wnat to spam the gateway.
      

      wnat = want

      // could hapen when long wraps or false interrupt triggered
      

      hapen = happen

      // Pulse cout has changed
      

      cout = count

      #define MAX_WATT 10000          // Max watt value to report. This filetrs outliers.
      

      filetrs = filters

      posted in Bug Reports
      flopp
      flopp
    • RE: Solar Powered Soil Moisture Sensor

      Just wanna update you all how the battery has been since start.
      No restart since 1st September.
      A few days ago we moved the plant indoor and I forgot to take out the sensor, I moved the sensor outdoor the day after

      0_1481267772602_chart.png

      posted in My Project
      flopp
      flopp
    • RE: About DS18B20 onewire.

      I have now tested this and the answer is YES, if B disconnects C will be the new B

      posted in Hardware
      flopp
      flopp
    • RE: ClearEepromConfig

      I think I have very old MySensor library, 1 year at least.

      Thank you you can close this

      posted in Bug Reports
      flopp
      flopp
    • RE: How To - Doorbell Automation Hack

      @flopp
      Found one mistake. I wrote some Serial.print to see where in the code my problem was and I wrote in a wrong place, so the code was looping on a wrong way.

      When that was corrected I found out that my relay needed to get 1 when it was off, so I just changed to below and now I don't get a green light as soon as I power on the arduino

      #define RELAY_ON 0
      #define RELAY_OFF 1
      
      posted in My Project
      flopp
      flopp
    • RE: Fusebit doctor

      @mfalkvidd
      Hehe, yes but that's to easy 🙂

      I have an atmega328p-au mounted that I can't remove on a pcb(GertSanders stamp size), I can access all pins so I wanna try to recover it with this board

      posted in General Discussion
      flopp
      flopp
    • RE: Dallas OneWire questions

      This is how I solved it with identification(DeviceAddress)

      https://forum.mysensors.org/topic/4143/about-ds18b20-onewire

      posted in Hardware
      flopp
      flopp
    • RE: Sensor Repeat

      If the sensor is a normal node it will not repeat any sensor data.

      You can install a Repeater between the not working sensor and the GW.

      posted in General Discussion
      flopp
      flopp
    • RE: fody weather station, wind sensor

      EDIT: I use digital input with pullup to see what sensor that receives the light
      So far I have a code for reading the direction and sending it to Controller.
      I will continue to add code for WindSpeed, Temp, Hum and Rain

      posted in Hardware
      flopp
      flopp
    • RE: Sensor Repeat

      @t1m0
      Repeater-sensor-node is a Repeater node
      What I meant with Normal node is Sensor node and they don't send others data to GW

      Sorry if I was not clear 😉

      posted in General Discussion
      flopp
      flopp
    • RE: fody weather station, wind sensor

      It was a HT-01D sensor for measuring temp/hum. It is I2C and address is 0x28.
      I found code for HYT 221 that worked fine.
      https://github.com/stylesuxx/Arduino-HYT-221-I2C

      posted in Hardware
      flopp
      flopp
    • RE: Question about step-down-module.

      @Cliff-Karlsson
      Yes that would be possible but it depends of the components that step-down the voltage.
      If the seller wrote 12v 10A, I understand that as 10A.
      Normally when you half the voltage you can double the amps. 12v* 10A= 120 watts
      So maybe you can draw 24 amp from the step-down at 5v.
      120watts / 5v= 24 amps
      Google ohm's law

      posted in General Discussion
      flopp
      flopp
    • RE: temp sensor keep on loging status switch

      The nodes send the data every 30 second, the log is ok.
      You will get one line in the log very time a node report something.
      It look like you also have an Event that gets trigger every time one of the nodes send data.

      posted in General Discussion
      flopp
      flopp
    • RE: fody weather station, wind sensor

      @sundberg84
      Can upload some later today.
      I found that I have some problem with the NRf, so I need to open it up.
      Will upload new code later today, as well.

      posted in Hardware
      flopp
      flopp
    • RE: temp sensor keep on loging status switch

      Ok.

      Then change Sleeptime to 900000, today you have 30000

      900000 = 60000 * 15 minutes

      posted in General Discussion
      flopp
      flopp
    • RE: Read voltage VCC, strange measurement[solved]

      @Yveaux
      I don't know because the battery was old when I started to use it.
      Home made pcb. Report every 30 minutes. No cap on battery.
      Take a look at this graph. This may be a new battery, don't remember. Has been running since 1/4 2016
      0_1483800257269_IMG_3616.PNG

      posted in General Discussion
      flopp
      flopp
    • RE: fody weather station, wind sensor

      some pictures
      0_1493054883191_20170424_160412832_iOS.jpg 0_1493054891231_20170424_160402858_iOS.jpg 0_1493054901570_20170424_160025939_iOS.jpg 0_1493054908764_20170424_160020368_iOS.jpg

      posted in Hardware
      flopp
      flopp
    • Discount on Z-wave, clas ohlson

      http://m.clasohlson.com/se/Inbyggnadsmottagare-dimmer-Aeon-Labs-DSC19103,-Z-wave/36-5745

      http://m.clasohlson.com/se/Inbyggnadsmottagare-på-av-Aeon-Labs-DSC18103,-Z-wave/36-5744

      posted in General Discussion
      flopp
      flopp
    • RE: 3.3V step up regulator voltage monitoring

      @fhenryco
      If you measure after the step-up you will never know when it will "die".
      You need to measure before step-up to see battery level

      posted in Hardware
      flopp
      flopp
    • RE: Discount on Z-wave, clas ohlson

      @bjacobse
      💃

      posted in General Discussion
      flopp
      flopp
    • RE: 3.3V step up regulator voltage monitoring

      @fhenryco
      If battery is below 0,8 step-up will not work and your Arduino will not work.
      If battery is 2.3 you will get 3.3 output from step-up

      posted in Hardware
      flopp
      flopp
    • RE: How to purchase mysensors SW protocol stack, instead of donation

      I continue in this thread, please tell me if you want me to create a new thread.

      I am thinking of selling a complete kit with sensors using MySensors protocol. I will sell as a private person, as a hobby. So no taxes will be payed or billed.

      Is this possible to do, according to your license?

      posted in General Discussion
      flopp
      flopp
    • RE: New 2.2.0 Signal report function

      I just now found some other maybe interested variables

      transportGetReceivingRSSI()
      transportGetSendingRSSI()
      transportGetReceivingSNR()
      transportGetSendingSNR()
      transportGetTxPowerLevel()
      transportGetTxPowerPercent()
      transportInternalToRSSI(_transportSM.uplinkQualityRSSI)

      i have not tested anyone of them, but it seems that "transportGetSendingRSSI()" will give same result as "transportGetSignalReport(SR_TX_RSSI)"
      so the message may look like this instead

      send(RSSIMsg.set(transportGetSendingRSSI()));

      posted in Hardware
      flopp
      flopp
    • RE: does someone use pcbs.io ?

      Hi, I have used Pcbs.io three times, first and second was good shipping time, both was 3 weeks from order to arrival.
      but now the third time I ordered 27/1 2018 and today 19/3 2018 I have still not received it.
      I got an email that my Pcbs were on the way at the 7/3 2018 but USPS have still not get them from Pcbs.io.
      So do not use Pcbs.io

      posted in Hardware
      flopp
      flopp
    • RE: About DS18B20 onewire.

      @pepson said in About DS18B20 onewire.:

      byte D[3][8] = {
      { 0x28, 0xFB, 0x8F, 0x77, 0x91, 0x15, 0x02, 0x32 },
      { 0x28, 0xFF, 0x37, 0x77, 0x91, 0x18, 0x02, 0x16 }
      };
      

      D[3] means 3 attached DS18B20, but you only have address for 2

      posted in Hardware
      flopp
      flopp