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

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo
  1. Home
  2. My Project
  3. Sensebender Micro + button

Sensebender Micro + button

Scheduled Pinned Locked Moved My Project
sensebendersensebender micbutton
27 Posts 5 Posters 10.5k Views 8 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • martinhjelmareM Offline
    martinhjelmareM Offline
    martinhjelmare
    Plugin Developer
    wrote on last edited by martinhjelmare
    #2

    Hi!

    Regarding the scrolling not working while in edit, yeah, I experiencing that also. I'm on Chrome 47, Ubuntu. I always have to edit in full screen.

    This is my sketch for a sensebender connected to my door bell:

    2016-02-29: Updated sketch to fix bug in siVolt calculation and set max vcc to 3.2 V.

    /**
     * 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 - Thomas Bowman Mørch
     *
     * DESCRIPTION
     * Default sensor sketch for Sensebender Micro module
     * Act as a temperature / humidity sensor by default.
     *
     * If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals
     *
     * Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below)
     *
     *
     * Version 1.3 - Thomas Bowman Mørch
     * Improved transmission logic, eliminating spurious transmissions (when temperatuere / humidity fluctuates 1 up and down between measurements)
     *
     * Added OTA boot mode, need to hold A1 low while applying power. (uses slightly more power as it's waiting for bootloader messages)
     *
     * MODIFIED by Martin Hjelmare
     * Sensebender Micro default sketch with addition of binary switch and interrupt,
     * taken from Patrick 'Anticimex' Fallberg's sketch BinarySwitchSleepSensor.
     * Also fixed the bug with the diff calculation for the temperature, and changed
     * vcc 100% rating to 3V, instead of 3.3V.
     */
    
    
    #include <MySensor.h>
    #include <Wire.h>
    #include <SI7021.h>
    #include <SPI.h>
    #include "utility/SPIFlash.h"
    #include <EEPROM.h>
    #include <sha204_lib_return_codes.h>
    #include <sha204_library.h>
    #include <RunningAverage.h>
    //#include <avr/power.h>
    
    // Define a static node address, remove if you want auto address assignment
    #define NODE_ADDRESS   1
    
    // Uncomment the line below, to transmit battery voltage as a normal sensor value
    #define BATT_SENSOR    199
    
    #define RELEASE "1.3"
    
    #define AVERAGES 2
    
    // Child sensor ID's
    #define CHILD_ID_TEMP  1
    #define CHILD_ID_HUM   2
    
    // How many milli seconds between each measurement
    #define MEASURE_INTERVAL 60000
    
    // How many milli seconds should we wait for OTA?
    #define OTA_WAIT_PERIOD 300
    
    // FORCE_TRANSMIT_INTERVAL, this number of times of wakeup, the sensor is forced to report all values to the controller
    #define FORCE_TRANSMIT_INTERVAL 30
    
    // When MEASURE_INTERVAL is 60000 and FORCE_TRANSMIT_INTERVAL is 30, we force a transmission every 30 minutes.
    // Between the forced transmissions a tranmission will only occur if the measured value differs from the previous measurement
    
    // HUMI_TRANSMIT_THRESHOLD tells how much the humidity should have changed since last time it was transmitted. Likewise with
    // TEMP_TRANSMIT_THRESHOLD for temperature threshold.
    #define HUMI_TRANSMIT_THRESHOLD 0.5
    #define TEMP_TRANSMIT_THRESHOLD 1.0
    
    // Pin definitions
    #define TEST_PIN       A0
    #define OTA_ENABLE     A1
    #define LED_PIN        A2
    #define ATSHA204_PIN   17 // A3
    
    const int sha204Pin = ATSHA204_PIN;
    atsha204Class sha204(sha204Pin);
    
    SI7021 humiditySensor;
    SPIFlash flash(8, 0x1F65);
    
    MySensor gw;
    
    // Sensor messages
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    
    #ifdef BATT_SENSOR
    MyMessage msgBatt(BATT_SENSOR, V_VOLTAGE);
    #endif
    
    #define CHILD_ID_BUTTON 3
    
    #define BUTTON_PIN 3   // Arduino Digital I/O pin for button/reed switch
    
    #if (BUTTON_PIN < 2 || BUTTON_PIN > 3)
    #error BUTTON_PIN must be either 2 or 3 for interrupts to work
    #endif
    
    // Change to V_LIGHT if you use S_LIGHT in presentation below
    MyMessage msg(CHILD_ID_BUTTON, V_TRIPPED);
    
    // Global settings
    int measureCount = 0;
    int sendBattery = 0;
    boolean isMetric = true;
    boolean highfreq = true;
    boolean ota_enabled = false;
    boolean transmission_occured = false;
    
    // Storage of old measurements
    float lastTemperature = -100;
    int lastHumidity = -100;
    long lastBattery = -100;
    
    int oldValue = -1;
    
    RunningAverage raHum(AVERAGES);
    
    /****************************************************
     *
     * Setup code
     *
     ****************************************************/
    void setup() {
    
      pinMode(LED_PIN, OUTPUT);
      digitalWrite(LED_PIN, LOW);
    
      Serial.begin(115200);
      Serial.print(F("Sensebender Micro FW "));
      Serial.print(RELEASE);
      Serial.flush();
    
      // First check if we should boot into test mode
    
      pinMode(TEST_PIN,INPUT_PULLUP);
      //digitalWrite(TEST_PIN, HIGH); // Enable pullup
      if (!digitalRead(TEST_PIN)) testMode();
    
      pinMode(OTA_ENABLE, INPUT);
      digitalWrite(OTA_ENABLE, HIGH);
      if (!digitalRead(OTA_ENABLE)) {
        ota_enabled = true;
      }
    
      // Make sure that ATSHA204 is not floating
      pinMode(ATSHA204_PIN, INPUT);
      digitalWrite(ATSHA204_PIN, HIGH);
    
      digitalWrite(TEST_PIN,LOW);
      digitalWrite(OTA_ENABLE, LOW); // remove pullup, save some power.
    
      // Setup the button
      pinMode(BUTTON_PIN, INPUT_PULLUP);
    
      digitalWrite(LED_PIN, HIGH);
    
    #ifdef NODE_ADDRESS
      gw.begin(NULL, NODE_ADDRESS, false);
    #else
      gw.begin(NULL,AUTO,false);
    #endif
    
      humiditySensor.begin();
    
      digitalWrite(LED_PIN, LOW);
    
      Serial.flush();
      Serial.println(F(" - Online!"));
      gw.sendSketchInfo("Sensebender Micro Bell", RELEASE);
    
      gw.present(CHILD_ID_TEMP,S_TEMP);
      gw.present(CHILD_ID_HUM,S_HUM);
    
    #ifdef BATT_SENSOR
      gw.present(BATT_SENSOR, S_MULTIMETER);
    #endif
    
      // Register binary input sensor to sensor_node (they will be created as child devices)
      // You can use S_DOOR, S_MOTION or S_LIGHT here depending on your usage.
      // If S_LIGHT is used, remember to update variable type you send in. See "msg" above.
      gw.present(CHILD_ID_BUTTON, S_DOOR);
    
      isMetric = gw.getConfig().isMetric;
      Serial.print(F("isMetric: ")); Serial.println(isMetric);
      raHum.clear();
      sendTempHumidityMeasurements(false);
      sendBattLevel(false);
      if (ota_enabled) Serial.println("OTA FW update enabled");
    
    }
    
    
    /***********************************************
     *
     *  Main loop function
     *
     ***********************************************/
    void loop() {
    
      measureCount ++;
      sendBattery ++;
      bool forceTransmit = false;
      transmission_occured = false;
      if ((measureCount == 5) && highfreq)
      {
        if (!ota_enabled) clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power.
        highfreq = false;
      }
    
      if (measureCount > FORCE_TRANSMIT_INTERVAL) { // force a transmission
        forceTransmit = true;
        measureCount = 0;
      }
    
      gw.process();
    
      sendTempHumidityMeasurements(forceTransmit);
      if (sendBattery > 60)
      {
         sendBattLevel(forceTransmit); // Not needed to send battery info that often
         sendBattery = 0;
      }
    
      if (ota_enabled & transmission_occured) {
          gw.wait(OTA_WAIT_PERIOD);
      }
    
      // Short delay to allow buttons to properly settle
      gw.sleep(5);
    
      int buttonValue = digitalRead(BUTTON_PIN);
    
      if (buttonValue != oldValue) {
         // Send in the new buttonValue
         gw.send(msg.set(buttonValue==HIGH ? 0 : 1));
         oldValue = buttonValue;
      }
    
      // Sleep until something happens with the sensor
      gw.sleep(BUTTON_PIN-2, CHANGE, MEASURE_INTERVAL);
    }
    
    
    /*********************************************
     *
     * Sends temperature and humidity from Si7021 sensor
     *
     * Parameters
     * - force : Forces transmission of a value (even if it's the same as previous measurement)
     *
     *********************************************/
    void sendTempHumidityMeasurements(bool force)
    {
      bool tx = force;
    
      si7021_env data = humiditySensor.getHumidityAndTemperature();
    
      raHum.addValue(data.humidityPercent);
    
      float diffTemp = abs(lastTemperature - (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths)/100.0);
      float diffHum = abs(lastHumidity - raHum.getAverage());
    
      Serial.print(F("TempDiff :"));Serial.println(diffTemp);
      Serial.print(F("HumDiff  :"));Serial.println(diffHum);
    
      if (isnan(diffHum)) tx = true;
      if (diffTemp > TEMP_TRANSMIT_THRESHOLD) tx = true;
      if (diffHum > HUMI_TRANSMIT_THRESHOLD) tx = true;
    
      if (tx) {
        measureCount = 0;
        float temperature = (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths) / 100.0;
    
        int humidity = data.humidityPercent;
        Serial.print("T: ");Serial.println(temperature);
        Serial.print("H: ");Serial.println(humidity);
    
        gw.send(msgTemp.set(temperature,1));
        gw.send(msgHum.set(humidity));
        lastTemperature = temperature;
        lastHumidity = humidity;
        transmission_occured = true;
      }
    }
    
    /********************************************
     *
     * Sends battery information (battery percentage)
     *
     * Parameters
     * - force : Forces transmission of a value
     *
     *******************************************/
    void sendBattLevel(bool force)
    {
      if (force) lastBattery = -1;
      long vcc = readVcc();
      if (vcc != lastBattery) {
        lastBattery = vcc;
      float siVolt = vcc / 1000.0;
    #ifdef BATT_SENSOR
        gw.send(msgBatt.set(siVolt, 2));
    #endif
    
        // Calculate percentage
        vcc = min(vcc, 3200L); // vcc max is 3200
        vcc = vcc  - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
    
        long percent = vcc / 13.0;
        gw.sendBatteryLevel(percent);
        transmission_occured = true;
      }
    }
    
    /*******************************************
     *
     * Internal battery ADC measuring
     *
     *******************************************/
    long readVcc() {
      // Read 1.1V reference against AVcc
      // set the reference to Vcc and the measurement to the internal 1.1V reference
      #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
        ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
        ADMUX = _BV(MUX5) | _BV(MUX0);
      #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
        ADcdMUX = _BV(MUX3) | _BV(MUX2);
      #else
        ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      #endif
    
      delay(2); // Wait for Vref to settle
      ADCSRA |= _BV(ADSC); // Start conversion
      while (bit_is_set(ADCSRA,ADSC)); // measuring
    
      uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
      uint8_t high = ADCH; // unlocks both
    
      long result = (high<<8) | low;
    
      result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
      return result; // Vcc in millivolts
    
    }
    
    /****************************************************
     *
     * Verify all peripherals, and signal via the LED if any problems.
     *
     ****************************************************/
    void testMode()
    {
      uint8_t rx_buffer[SHA204_RSP_SIZE_MAX];
      uint8_t ret_code;
      byte tests = 0;
    
      digitalWrite(LED_PIN, HIGH); // Turn on LED.
      Serial.println(F(" - TestMode"));
      Serial.println(F("Testing peripherals!"));
      Serial.flush();
      Serial.print(F("-> SI7021 : "));
      Serial.flush();
    
      if (humiditySensor.begin())
      {
        Serial.println(F("ok!"));
        tests ++;
      }
      else
      {
        Serial.println(F("failed!"));
      }
      Serial.flush();
    
      Serial.print(F("-> Flash : "));
      Serial.flush();
      if (flash.initialize())
      {
        Serial.println(F("ok!"));
        tests ++;
      }
      else
      {
        Serial.println(F("failed!"));
      }
      Serial.flush();
    
    
      Serial.print(F("-> SHA204 : "));
      ret_code = sha204.sha204c_wakeup(rx_buffer);
      Serial.flush();
      if (ret_code != SHA204_SUCCESS)
      {
        Serial.print(F("Failed to wake device. Response: ")); Serial.println(ret_code, HEX);
      }
      Serial.flush();
      if (ret_code == SHA204_SUCCESS)
      {
        ret_code = sha204.getSerialNumber(rx_buffer);
        if (ret_code != SHA204_SUCCESS)
        {
          Serial.print(F("Failed to obtain device serial number. Response: ")); Serial.println(ret_code, HEX);
        }
        else
        {
          Serial.print(F("Ok (serial : "));
          for (int i=0; i<9; i++)
          {
            if (rx_buffer[i] < 0x10)
            {
              Serial.print('0'); // Because Serial.print does not 0-pad HEX
            }
            Serial.print(rx_buffer[i], HEX);
          }
          Serial.println(")");
          tests ++;
        }
    
      }
      Serial.flush();
    
      Serial.println(F("Test finished"));
    
      if (tests == 3)
      {
        Serial.println(F("Selftest ok!"));
        while (1) // Blink OK pattern!
        {
          digitalWrite(LED_PIN, HIGH);
          delay(200);
          digitalWrite(LED_PIN, LOW);
          delay(200);
        }
      }
      else
      {
        Serial.println(F("----> Selftest failed!"));
        while (1) // Blink FAILED pattern! Rappidly blinking..
        {
        }
      }
    }
    
    
    Pierre PP 1 Reply Last reply
    0
    • Pierre PP Offline
      Pierre PP Offline
      Pierre P
      wrote on last edited by
      #3

      Thanks a lot !
      There is many improvements between the very first sketch !
      And with OTA... Thanks !

      No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

      1 Reply Last reply
      0
      • martinhjelmareM martinhjelmare

        Hi!

        Regarding the scrolling not working while in edit, yeah, I experiencing that also. I'm on Chrome 47, Ubuntu. I always have to edit in full screen.

        This is my sketch for a sensebender connected to my door bell:

        2016-02-29: Updated sketch to fix bug in siVolt calculation and set max vcc to 3.2 V.

        /**
         * 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 - Thomas Bowman Mørch
         *
         * DESCRIPTION
         * Default sensor sketch for Sensebender Micro module
         * Act as a temperature / humidity sensor by default.
         *
         * If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals
         *
         * Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below)
         *
         *
         * Version 1.3 - Thomas Bowman Mørch
         * Improved transmission logic, eliminating spurious transmissions (when temperatuere / humidity fluctuates 1 up and down between measurements)
         *
         * Added OTA boot mode, need to hold A1 low while applying power. (uses slightly more power as it's waiting for bootloader messages)
         *
         * MODIFIED by Martin Hjelmare
         * Sensebender Micro default sketch with addition of binary switch and interrupt,
         * taken from Patrick 'Anticimex' Fallberg's sketch BinarySwitchSleepSensor.
         * Also fixed the bug with the diff calculation for the temperature, and changed
         * vcc 100% rating to 3V, instead of 3.3V.
         */
        
        
        #include <MySensor.h>
        #include <Wire.h>
        #include <SI7021.h>
        #include <SPI.h>
        #include "utility/SPIFlash.h"
        #include <EEPROM.h>
        #include <sha204_lib_return_codes.h>
        #include <sha204_library.h>
        #include <RunningAverage.h>
        //#include <avr/power.h>
        
        // Define a static node address, remove if you want auto address assignment
        #define NODE_ADDRESS   1
        
        // Uncomment the line below, to transmit battery voltage as a normal sensor value
        #define BATT_SENSOR    199
        
        #define RELEASE "1.3"
        
        #define AVERAGES 2
        
        // Child sensor ID's
        #define CHILD_ID_TEMP  1
        #define CHILD_ID_HUM   2
        
        // How many milli seconds between each measurement
        #define MEASURE_INTERVAL 60000
        
        // How many milli seconds should we wait for OTA?
        #define OTA_WAIT_PERIOD 300
        
        // FORCE_TRANSMIT_INTERVAL, this number of times of wakeup, the sensor is forced to report all values to the controller
        #define FORCE_TRANSMIT_INTERVAL 30
        
        // When MEASURE_INTERVAL is 60000 and FORCE_TRANSMIT_INTERVAL is 30, we force a transmission every 30 minutes.
        // Between the forced transmissions a tranmission will only occur if the measured value differs from the previous measurement
        
        // HUMI_TRANSMIT_THRESHOLD tells how much the humidity should have changed since last time it was transmitted. Likewise with
        // TEMP_TRANSMIT_THRESHOLD for temperature threshold.
        #define HUMI_TRANSMIT_THRESHOLD 0.5
        #define TEMP_TRANSMIT_THRESHOLD 1.0
        
        // Pin definitions
        #define TEST_PIN       A0
        #define OTA_ENABLE     A1
        #define LED_PIN        A2
        #define ATSHA204_PIN   17 // A3
        
        const int sha204Pin = ATSHA204_PIN;
        atsha204Class sha204(sha204Pin);
        
        SI7021 humiditySensor;
        SPIFlash flash(8, 0x1F65);
        
        MySensor gw;
        
        // Sensor messages
        MyMessage msgHum(CHILD_ID_HUM, V_HUM);
        MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
        
        #ifdef BATT_SENSOR
        MyMessage msgBatt(BATT_SENSOR, V_VOLTAGE);
        #endif
        
        #define CHILD_ID_BUTTON 3
        
        #define BUTTON_PIN 3   // Arduino Digital I/O pin for button/reed switch
        
        #if (BUTTON_PIN < 2 || BUTTON_PIN > 3)
        #error BUTTON_PIN must be either 2 or 3 for interrupts to work
        #endif
        
        // Change to V_LIGHT if you use S_LIGHT in presentation below
        MyMessage msg(CHILD_ID_BUTTON, V_TRIPPED);
        
        // Global settings
        int measureCount = 0;
        int sendBattery = 0;
        boolean isMetric = true;
        boolean highfreq = true;
        boolean ota_enabled = false;
        boolean transmission_occured = false;
        
        // Storage of old measurements
        float lastTemperature = -100;
        int lastHumidity = -100;
        long lastBattery = -100;
        
        int oldValue = -1;
        
        RunningAverage raHum(AVERAGES);
        
        /****************************************************
         *
         * Setup code
         *
         ****************************************************/
        void setup() {
        
          pinMode(LED_PIN, OUTPUT);
          digitalWrite(LED_PIN, LOW);
        
          Serial.begin(115200);
          Serial.print(F("Sensebender Micro FW "));
          Serial.print(RELEASE);
          Serial.flush();
        
          // First check if we should boot into test mode
        
          pinMode(TEST_PIN,INPUT_PULLUP);
          //digitalWrite(TEST_PIN, HIGH); // Enable pullup
          if (!digitalRead(TEST_PIN)) testMode();
        
          pinMode(OTA_ENABLE, INPUT);
          digitalWrite(OTA_ENABLE, HIGH);
          if (!digitalRead(OTA_ENABLE)) {
            ota_enabled = true;
          }
        
          // Make sure that ATSHA204 is not floating
          pinMode(ATSHA204_PIN, INPUT);
          digitalWrite(ATSHA204_PIN, HIGH);
        
          digitalWrite(TEST_PIN,LOW);
          digitalWrite(OTA_ENABLE, LOW); // remove pullup, save some power.
        
          // Setup the button
          pinMode(BUTTON_PIN, INPUT_PULLUP);
        
          digitalWrite(LED_PIN, HIGH);
        
        #ifdef NODE_ADDRESS
          gw.begin(NULL, NODE_ADDRESS, false);
        #else
          gw.begin(NULL,AUTO,false);
        #endif
        
          humiditySensor.begin();
        
          digitalWrite(LED_PIN, LOW);
        
          Serial.flush();
          Serial.println(F(" - Online!"));
          gw.sendSketchInfo("Sensebender Micro Bell", RELEASE);
        
          gw.present(CHILD_ID_TEMP,S_TEMP);
          gw.present(CHILD_ID_HUM,S_HUM);
        
        #ifdef BATT_SENSOR
          gw.present(BATT_SENSOR, S_MULTIMETER);
        #endif
        
          // Register binary input sensor to sensor_node (they will be created as child devices)
          // You can use S_DOOR, S_MOTION or S_LIGHT here depending on your usage.
          // If S_LIGHT is used, remember to update variable type you send in. See "msg" above.
          gw.present(CHILD_ID_BUTTON, S_DOOR);
        
          isMetric = gw.getConfig().isMetric;
          Serial.print(F("isMetric: ")); Serial.println(isMetric);
          raHum.clear();
          sendTempHumidityMeasurements(false);
          sendBattLevel(false);
          if (ota_enabled) Serial.println("OTA FW update enabled");
        
        }
        
        
        /***********************************************
         *
         *  Main loop function
         *
         ***********************************************/
        void loop() {
        
          measureCount ++;
          sendBattery ++;
          bool forceTransmit = false;
          transmission_occured = false;
          if ((measureCount == 5) && highfreq)
          {
            if (!ota_enabled) clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power.
            highfreq = false;
          }
        
          if (measureCount > FORCE_TRANSMIT_INTERVAL) { // force a transmission
            forceTransmit = true;
            measureCount = 0;
          }
        
          gw.process();
        
          sendTempHumidityMeasurements(forceTransmit);
          if (sendBattery > 60)
          {
             sendBattLevel(forceTransmit); // Not needed to send battery info that often
             sendBattery = 0;
          }
        
          if (ota_enabled & transmission_occured) {
              gw.wait(OTA_WAIT_PERIOD);
          }
        
          // Short delay to allow buttons to properly settle
          gw.sleep(5);
        
          int buttonValue = digitalRead(BUTTON_PIN);
        
          if (buttonValue != oldValue) {
             // Send in the new buttonValue
             gw.send(msg.set(buttonValue==HIGH ? 0 : 1));
             oldValue = buttonValue;
          }
        
          // Sleep until something happens with the sensor
          gw.sleep(BUTTON_PIN-2, CHANGE, MEASURE_INTERVAL);
        }
        
        
        /*********************************************
         *
         * Sends temperature and humidity from Si7021 sensor
         *
         * Parameters
         * - force : Forces transmission of a value (even if it's the same as previous measurement)
         *
         *********************************************/
        void sendTempHumidityMeasurements(bool force)
        {
          bool tx = force;
        
          si7021_env data = humiditySensor.getHumidityAndTemperature();
        
          raHum.addValue(data.humidityPercent);
        
          float diffTemp = abs(lastTemperature - (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths)/100.0);
          float diffHum = abs(lastHumidity - raHum.getAverage());
        
          Serial.print(F("TempDiff :"));Serial.println(diffTemp);
          Serial.print(F("HumDiff  :"));Serial.println(diffHum);
        
          if (isnan(diffHum)) tx = true;
          if (diffTemp > TEMP_TRANSMIT_THRESHOLD) tx = true;
          if (diffHum > HUMI_TRANSMIT_THRESHOLD) tx = true;
        
          if (tx) {
            measureCount = 0;
            float temperature = (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths) / 100.0;
        
            int humidity = data.humidityPercent;
            Serial.print("T: ");Serial.println(temperature);
            Serial.print("H: ");Serial.println(humidity);
        
            gw.send(msgTemp.set(temperature,1));
            gw.send(msgHum.set(humidity));
            lastTemperature = temperature;
            lastHumidity = humidity;
            transmission_occured = true;
          }
        }
        
        /********************************************
         *
         * Sends battery information (battery percentage)
         *
         * Parameters
         * - force : Forces transmission of a value
         *
         *******************************************/
        void sendBattLevel(bool force)
        {
          if (force) lastBattery = -1;
          long vcc = readVcc();
          if (vcc != lastBattery) {
            lastBattery = vcc;
          float siVolt = vcc / 1000.0;
        #ifdef BATT_SENSOR
            gw.send(msgBatt.set(siVolt, 2));
        #endif
        
            // Calculate percentage
            vcc = min(vcc, 3200L); // vcc max is 3200
            vcc = vcc  - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
        
            long percent = vcc / 13.0;
            gw.sendBatteryLevel(percent);
            transmission_occured = true;
          }
        }
        
        /*******************************************
         *
         * Internal battery ADC measuring
         *
         *******************************************/
        long readVcc() {
          // Read 1.1V reference against AVcc
          // set the reference to Vcc and the measurement to the internal 1.1V reference
          #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
            ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
          #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
            ADMUX = _BV(MUX5) | _BV(MUX0);
          #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
            ADcdMUX = _BV(MUX3) | _BV(MUX2);
          #else
            ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
          #endif
        
          delay(2); // Wait for Vref to settle
          ADCSRA |= _BV(ADSC); // Start conversion
          while (bit_is_set(ADCSRA,ADSC)); // measuring
        
          uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
          uint8_t high = ADCH; // unlocks both
        
          long result = (high<<8) | low;
        
          result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
          return result; // Vcc in millivolts
        
        }
        
        /****************************************************
         *
         * Verify all peripherals, and signal via the LED if any problems.
         *
         ****************************************************/
        void testMode()
        {
          uint8_t rx_buffer[SHA204_RSP_SIZE_MAX];
          uint8_t ret_code;
          byte tests = 0;
        
          digitalWrite(LED_PIN, HIGH); // Turn on LED.
          Serial.println(F(" - TestMode"));
          Serial.println(F("Testing peripherals!"));
          Serial.flush();
          Serial.print(F("-> SI7021 : "));
          Serial.flush();
        
          if (humiditySensor.begin())
          {
            Serial.println(F("ok!"));
            tests ++;
          }
          else
          {
            Serial.println(F("failed!"));
          }
          Serial.flush();
        
          Serial.print(F("-> Flash : "));
          Serial.flush();
          if (flash.initialize())
          {
            Serial.println(F("ok!"));
            tests ++;
          }
          else
          {
            Serial.println(F("failed!"));
          }
          Serial.flush();
        
        
          Serial.print(F("-> SHA204 : "));
          ret_code = sha204.sha204c_wakeup(rx_buffer);
          Serial.flush();
          if (ret_code != SHA204_SUCCESS)
          {
            Serial.print(F("Failed to wake device. Response: ")); Serial.println(ret_code, HEX);
          }
          Serial.flush();
          if (ret_code == SHA204_SUCCESS)
          {
            ret_code = sha204.getSerialNumber(rx_buffer);
            if (ret_code != SHA204_SUCCESS)
            {
              Serial.print(F("Failed to obtain device serial number. Response: ")); Serial.println(ret_code, HEX);
            }
            else
            {
              Serial.print(F("Ok (serial : "));
              for (int i=0; i<9; i++)
              {
                if (rx_buffer[i] < 0x10)
                {
                  Serial.print('0'); // Because Serial.print does not 0-pad HEX
                }
                Serial.print(rx_buffer[i], HEX);
              }
              Serial.println(")");
              tests ++;
            }
        
          }
          Serial.flush();
        
          Serial.println(F("Test finished"));
        
          if (tests == 3)
          {
            Serial.println(F("Selftest ok!"));
            while (1) // Blink OK pattern!
            {
              digitalWrite(LED_PIN, HIGH);
              delay(200);
              digitalWrite(LED_PIN, LOW);
              delay(200);
            }
          }
          else
          {
            Serial.println(F("----> Selftest failed!"));
            while (1) // Blink FAILED pattern! Rappidly blinking..
            {
            }
          }
        }
        
        
        Pierre PP Offline
        Pierre PP Offline
        Pierre P
        wrote on last edited by
        #4

        @martinhjelmare there is a bug (for code bender and arduinoUI). It doesn't like siVolt. '"siVolt' was not declared in this scope"
        your code:

        /********************************************
         *
         * Sends battery information (battery percentage)
         *
         * Parameters
         * - force : Forces transmission of a value
         *
         *******************************************/
        void sendBattLevel(bool force)
        {
          if (force) lastBattery = -1;
          long vcc = readVcc();
          if (vcc != lastBattery) {
            lastBattery = vcc;
          siVolt = vcc / 1000;
        #ifdef BATT_SENSOR
            gw.send(msgBatt.set(siVolt));
        #endif
        
            // Calculate percentage
            vcc = min(vcc, 3000L); // vcc max is 3000
            vcc = vcc  - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
        
            long percent = vcc / 11.0;
            gw.sendBatteryLevel(percent);
            transmission_occured = true;
          }
        }
        
        /*******************************************
        

        old code

        /********************************************
         *
         * Sends battery information (battery percentage)
         *
         * Parameters
         * - force : Forces transmission of a value
         *
         *******************************************/
        void sendBattLevel(bool force)
        {
          if (force) lastBattery = -1;
          long vcc = readVcc();
          if (vcc != lastBattery) {
            lastBattery = vcc;
        
        #ifdef BATT_SENSOR
            gw.send(msgBatt.set(vcc));
        #endif
        
            // Calculate percentage
        
            vcc = vcc - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
            
            long percent = vcc / 14.0;
            gw.sendBatteryLevel(percent);
          }
        }
        

        How did you compil ?

        No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

        tbowmoT 1 Reply Last reply
        0
        • Pierre PP Pierre P

          @martinhjelmare there is a bug (for code bender and arduinoUI). It doesn't like siVolt. '"siVolt' was not declared in this scope"
          your code:

          /********************************************
           *
           * Sends battery information (battery percentage)
           *
           * Parameters
           * - force : Forces transmission of a value
           *
           *******************************************/
          void sendBattLevel(bool force)
          {
            if (force) lastBattery = -1;
            long vcc = readVcc();
            if (vcc != lastBattery) {
              lastBattery = vcc;
            siVolt = vcc / 1000;
          #ifdef BATT_SENSOR
              gw.send(msgBatt.set(siVolt));
          #endif
          
              // Calculate percentage
              vcc = min(vcc, 3000L); // vcc max is 3000
              vcc = vcc  - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
          
              long percent = vcc / 11.0;
              gw.sendBatteryLevel(percent);
              transmission_occured = true;
            }
          }
          
          /*******************************************
          

          old code

          /********************************************
           *
           * Sends battery information (battery percentage)
           *
           * Parameters
           * - force : Forces transmission of a value
           *
           *******************************************/
          void sendBattLevel(bool force)
          {
            if (force) lastBattery = -1;
            long vcc = readVcc();
            if (vcc != lastBattery) {
              lastBattery = vcc;
          
          #ifdef BATT_SENSOR
              gw.send(msgBatt.set(vcc));
          #endif
          
              // Calculate percentage
          
              vcc = vcc - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
              
              long percent = vcc / 14.0;
              gw.sendBatteryLevel(percent);
            }
          }
          

          How did you compil ?

          tbowmoT Offline
          tbowmoT Offline
          tbowmo
          Admin
          wrote on last edited by
          #5

          @Pierre-P

          You just need to declare siVolt as a float type

          float siVolt = vcc/100;
          #ifdef.... 
          
          
          Pierre PP 1 Reply Last reply
          0
          • tbowmoT tbowmo

            @Pierre-P

            You just need to declare siVolt as a float type

            float siVolt = vcc/100;
            #ifdef.... 
            
            
            Pierre PP Offline
            Pierre PP Offline
            Pierre P
            wrote on last edited by
            #6

            @tbowmo "call of overloaded 'set(float&)' is ambiguous"
            I don't know what it mean.
            And i don't know why the very first sketch is working for you and not for me ! :sweat_smile:

            /********************************************
             *
             * Sends battery information (battery percentage)
             *
             * Parameters
             * - force : Forces transmission of a value
             *
             *******************************************/
            void sendBattLevel(bool force)
            {
              if (force) lastBattery = -1;
              long vcc = readVcc();
              if (vcc != lastBattery) {
                lastBattery = vcc;
                float siVolt = vcc / 1000;
            #ifdef BATT_SENSOR
                gw.send(msgBatt.set(siVolt));
            #endif
            
                // Calculate percentage
                vcc = min(vcc, 3000L); // vcc max is 3000
                vcc = vcc  - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
            
                long percent = vcc / 11.0;
                gw.sendBatteryLevel(percent);
                transmission_occured = true;
              }
            }
            
            /*******************************************f```

            No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

            martinhjelmareM 1 Reply Last reply
            0
            • Pierre PP Pierre P

              @tbowmo "call of overloaded 'set(float&)' is ambiguous"
              I don't know what it mean.
              And i don't know why the very first sketch is working for you and not for me ! :sweat_smile:

              /********************************************
               *
               * Sends battery information (battery percentage)
               *
               * Parameters
               * - force : Forces transmission of a value
               *
               *******************************************/
              void sendBattLevel(bool force)
              {
                if (force) lastBattery = -1;
                long vcc = readVcc();
                if (vcc != lastBattery) {
                  lastBattery = vcc;
                  float siVolt = vcc / 1000;
              #ifdef BATT_SENSOR
                  gw.send(msgBatt.set(siVolt));
              #endif
              
                  // Calculate percentage
                  vcc = min(vcc, 3000L); // vcc max is 3000
                  vcc = vcc  - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
              
                  long percent = vcc / 11.0;
                  gw.sendBatteryLevel(percent);
                  transmission_occured = true;
                }
              }
              
              /*******************************************f```
              martinhjelmareM Offline
              martinhjelmareM Offline
              martinhjelmare
              Plugin Developer
              wrote on last edited by
              #7

              @Pierre-P

              Sorry that was my addition and I haven't actually tested the siVolt thing yet. Everything else works though. But I don't see why it shouldn't work if you declare it properly first.

              1 Reply Last reply
              0
              • Pierre PP Offline
                Pierre PP Offline
                Pierre P
                wrote on last edited by Pierre P
                #8

                BATT_SENSOR si declared.
                ... I think msgBatt is not.
                Does it should be here ?

                // Sensor messages
                MyMessage msgHum(CHILD_ID_HUM, V_HUM);
                MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
                

                Wait not it's just under:

                #ifdef BATT_SENSOR
                MyMessage msgBatt(BATT_SENSOR, V_VOLTAGE);
                #endif
                

                No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

                martinhjelmareM 1 Reply Last reply
                0
                • Pierre PP Pierre P

                  BATT_SENSOR si declared.
                  ... I think msgBatt is not.
                  Does it should be here ?

                  // Sensor messages
                  MyMessage msgHum(CHILD_ID_HUM, V_HUM);
                  MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
                  

                  Wait not it's just under:

                  #ifdef BATT_SENSOR
                  MyMessage msgBatt(BATT_SENSOR, V_VOLTAGE);
                  #endif
                  
                  martinhjelmareM Offline
                  martinhjelmareM Offline
                  martinhjelmare
                  Plugin Developer
                  wrote on last edited by martinhjelmare
                  #9

                  @Pierre-P

                  It's declared three lines below, inside the ifdefine.

                  Try declaring siVolt outside the if block in the battery function.

                  Edit: Scrap the last suggestion.

                  1 Reply Last reply
                  0
                  • Pierre PP Offline
                    Pierre PP Offline
                    Pierre P
                    wrote on last edited by
                    #10

                    If I undefine: //#define BATT_SENSOR 199
                    it's working.
                    But your code still not 100% so we have to find why.
                    But... but, i think i'm making a mistake: yes i plan to use 3volts power. But, i don't want it as a sensor ! I wan't it as a battery level like the very first SensebenderMicro sketch. So... I have to undefine BATT_SENSOR ? And i will not have it set to 3Vcc=100% ?
                    0_1453547060579_jeedom-004.png

                    No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

                    martinhjelmareM iotcrazyI 2 Replies Last reply
                    0
                    • Pierre PP Pierre P

                      If I undefine: //#define BATT_SENSOR 199
                      it's working.
                      But your code still not 100% so we have to find why.
                      But... but, i think i'm making a mistake: yes i plan to use 3volts power. But, i don't want it as a sensor ! I wan't it as a battery level like the very first SensebenderMicro sketch. So... I have to undefine BATT_SENSOR ? And i will not have it set to 3Vcc=100% ?
                      0_1453547060579_jeedom-004.png

                      martinhjelmareM Offline
                      martinhjelmareM Offline
                      martinhjelmare
                      Plugin Developer
                      wrote on last edited by
                      #11

                      @Pierre-P

                      Might you need to specify decimals if sending float as message. If you want to try, add a second argument with an integer number for decimals.
                      https://github.com/mysensors/Arduino/blob/1.5.3/libraries/MySensors/MyMessage.cpp#L212

                      1 Reply Last reply
                      0
                      • Pierre PP Offline
                        Pierre PP Offline
                        Pierre P
                        wrote on last edited by
                        #12

                        Sorry i'm lost. I'm not as good for now.
                        (you may already see that)

                        No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

                        martinhjelmareM 1 Reply Last reply
                        0
                        • Pierre PP Pierre P

                          Sorry i'm lost. I'm not as good for now.
                          (you may already see that)

                          martinhjelmareM Offline
                          martinhjelmareM Offline
                          martinhjelmare
                          Plugin Developer
                          wrote on last edited by martinhjelmare
                          #13

                          @Pierre-P

                          void sendBattLevel(bool force)
                          {
                            if (force) lastBattery = -1;
                            long vcc = readVcc();
                            if (vcc != lastBattery) {
                              lastBattery = vcc;
                              float siVolt = vcc / 1000;
                          #ifdef BATT_SENSOR
                              gw.send(msgBatt.set(siVolt, 2));
                          #endif
                          
                              // Calculate percentage
                              vcc = min(vcc, 3000L); // vcc max is 3000
                              vcc = vcc  - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
                          
                              long percent = vcc / 11.0;
                              gw.sendBatteryLevel(percent);
                              transmission_occured = true;
                            }
                          }
                          
                          1 Reply Last reply
                          0
                          • Pierre PP Offline
                            Pierre PP Offline
                            Pierre P
                            wrote on last edited by
                            #14

                            oh...:no_mouth:
                            Just need to say use "2" decimals in the message and it's ok...

                            The compilation work !
                            I'll try this afternoon the difference between #define BATT_SENSOR 199 and //#define BATT_SENSOR 199

                            Thanks for your help !

                            No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

                            1 Reply Last reply
                            0
                            • Pierre PP Offline
                              Pierre PP Offline
                              Pierre P
                              wrote on last edited by
                              #15

                              0_1453549809864_jeedom-005.png
                              Voltage is not good (it's a new 3Vcc button cell) and batterie pourcentage is at 76%

                              The battery voltage is not just minus 0.3V...

                              No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

                              1 Reply Last reply
                              0
                              • tbowmoT Offline
                                tbowmoT Offline
                                tbowmo
                                Admin
                                wrote on last edited by
                                #16

                                @Pierre-P

                                The measurement method is not accurate at all. It relies on an internal reference that can vary in value between boards (I can't remember the accuracy of it at the moment)

                                If you don't want the battery voltage, then uncomment the #define for BATT_SENSOR in the top of the sketch, and move the float siVolt = vcc/1000; to be within the #ifdef BATT_SENSOR like:

                                #ifdef BATT_SENSOR
                                    float siVolt = vcc / 1000;
                                    gw.send(msgBatt.set(siVolt, 2));
                                #endif
                                
                                

                                Now it should compile, and send battery percentage as the standard sensebender sketch.

                                1 Reply Last reply
                                0
                                • Pierre PP Offline
                                  Pierre PP Offline
                                  Pierre P
                                  wrote on last edited by
                                  #17

                                  I personaly think that it's quite good. When powered by FTDI, it found 3.00V.
                                  And I have only add the "//" to BATT_SENSOR and it work good.
                                  (you inverted the thing in the message just above).

                                  Thanks again for you help.
                                  Now i work very good and very fast. I just have to check for adding an antenna to the controller.

                                  No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

                                  1 Reply Last reply
                                  0
                                  • tbowmoT Offline
                                    tbowmoT Offline
                                    tbowmo
                                    Admin
                                    wrote on last edited by
                                    #18

                                    @Pierre-P

                                    The FTDI probably supplies the board with 3.3V and not 3V..

                                    1 Reply Last reply
                                    0
                                    • alexsh1A Offline
                                      alexsh1A Offline
                                      alexsh1
                                      wrote on last edited by
                                      #19

                                      @Pierre-P How do you find the battery life please? I am planning to fit Sensebender with nrf24l01+ SMD and CR2032, but I wonder how long the battery is going to survive? Appreciate if depends on your sketch, but given one is conservative (i.e. no need to send temp/hum every 30-60 sec, but probably every 5-10mins or so), what's your estimate please?

                                      1 Reply Last reply
                                      0
                                      • Pierre PP Offline
                                        Pierre PP Offline
                                        Pierre P
                                        wrote on last edited by
                                        #20

                                        I can't tell you for the moment, I haven't check the real voltage of the CR2032 at the beginning. I'll try to make two mesure between 30 days.
                                        But my sketch is 1800000ms or 30min sleeping (if no-one press the button). Because it's a redundant information, my Jeedom controler have a meteo plugin who's working good. (i'll use it for the mini-night-temperature to have a message if there is glass on my car's windows).

                                        No quote, no forum notification (else, the mail box ring every minutes !). Thanks, and have a very good MySensors day !

                                        1 Reply Last reply
                                        0
                                        • Pierre PP Pierre P

                                          If I undefine: //#define BATT_SENSOR 199
                                          it's working.
                                          But your code still not 100% so we have to find why.
                                          But... but, i think i'm making a mistake: yes i plan to use 3volts power. But, i don't want it as a sensor ! I wan't it as a battery level like the very first SensebenderMicro sketch. So... I have to undefine BATT_SENSOR ? And i will not have it set to 3Vcc=100% ?
                                          0_1453547060579_jeedom-004.png

                                          iotcrazyI Offline
                                          iotcrazyI Offline
                                          iotcrazy
                                          wrote on last edited by
                                          #21

                                          @Pierre-P you controller image looks great . What controller is it ?

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


                                          21

                                          Online

                                          11.7k

                                          Users

                                          11.2k

                                          Topics

                                          113.1k

                                          Posts


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

                                          • Don't have an account? Register

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