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. Development
  3. Arduino mini pro 3.3 battery optimization code

Arduino mini pro 3.3 battery optimization code

Scheduled Pinned Locked Moved Development
23 Posts 6 Posters 2.9k Views 5 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.
  • T Tommas

    Dear All!

    I would like to use the Arduino Mini Pro 3.3 8Mhz (aTMega328) with 2xAA battery. I have read that it useful to put it in powerdown/sleep mode.
    Could you help me what code/sketch should I use. I copied to here my beta sketch(It works, but it doesnt have the powerdown function)
    If someone has any other suggestion related to the code, please write it!

    /**
     * The MySensors Arduino library handles the wireless radio link and protocol
     * between your home built sensors/actuators and HA controller of choice.
     * The sensors forms a self healing radio network with optional repeaters. Each
     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
     * network topology allowing messages to be routed to nodes.
     *
     * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
     * Copyright (C) 2013-2015 Sensnology AB
     * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
     *
     * Documentation: http://www.mysensors.org
     * Support Forum: http://forum.mysensors.org
     *
     * This program is free software; you can redistribute it and/or
     * modify it under the terms of the GNU General Public License
     * version 2 as published by the Free Software Foundation.
     *
     *******************************
     *
     * REVISION HISTORY
     * Version 1.0: Henrik EKblad
     * Version 1.1 - 2016-07-20: Converted to MySensors v2.0 and added various improvements - Torben Woltjen (mozzbozz)
     * 
     * DESCRIPTION
     * This sketch provides an example of how to implement a humidity/temperature
     * sensor using a DHT11/DHT-22.
     *  
     * For more information, please visit:
     * http://www.mysensors.org/build/humidity
     * 
     */
    #define MY_NODE_ID 6
    // Enable debug prints
    #define MY_DEBUG
    
    // Enable and select radio type attached 
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    //#define MY_RS485
    /* Sketch with Si7021 and battery monitoring.
    by m26872, 20151109 
    */
    #include <MySensors.h>  
    #include <Wire.h>
    #include <SI7021.h>
    #include <SPI.h>
    #include <RunningAverage.h>
    #include <BH1750.h> //BH1750
    
    #define DEBUG
    
    #ifdef DEBUG
    #define DEBUG_SERIAL(x) Serial.begin(x)
    #define DEBUG_PRINT(x) Serial.print(x)
    #define DEBUG_PRINTLN(x) Serial.println(x)
    #else
    #define DEBUG_SERIAL(x)
    #define DEBUG_PRINT(x) 
    #define DEBUG_PRINTLN(x) 
    #endif
    #define MOTION_DIGITAL_INPUT_SENSOR 3 //MOTION
    
    #define NODE_ID 6             // <<<<<<<<<<<<<<<<<<<<<<<<<<<   Enter Node_ID
    #define CHILD_ID_TEMP 0
    #define CHILD_ID_HUM 1
    #define CHILD_ID_LIGHT 2 //BH1750
    #define CHILD_ID_MOTION 3 /*MOTION*/
    //BATTERY
    int BATTERY_SENSE_PIN = A0;  // select the input pin for the battery sense point
    
    uint32_t SLEEP_TIME = 900000;  // sleep time between reads (seconds * 1000 milliseconds)
    int oldBatteryPcnt = 0;
    
    
    //#define SLEEP_TIME 15000 // 15s for DEBUG
    #define SLEEP_TIME 10000   // 5 min
    //#define FORCE_TRANSMIT_CYCLE 36  // 5min*12=1/hour, 5min*36=1/3hour 
    #define FORCE_TRANSMIT_CYCLE 1  // 5min*12=1/hour, 5min*36=1/3hour 
    //#define BATTERY_REPORT_CYCLE 2880   // Once per 5min   =>   12*24*7 = 2016 (one report/week)
    //#define VMIN 1900
    //#define VMAX 3300
    #define HUMI_TRANSMIT_THRESHOLD 3.0  // THRESHOLD tells how much the value should have changed since last time it was transmitted.
    #define TEMP_TRANSMIT_THRESHOLD 0.5
    #define AVERAGES 2
    
    //int batteryReportCounter = BATTERY_REPORT_CYCLE - 1;  // to make it report the first time.
    int measureCount = 0;
    float lastTemperature = -100;
    int lastHumidity = -100;
    
    uint16_t lastlux; //BH1750
    
    RunningAverage raHum(AVERAGES);
    SI7021 humiditySensor;
    BH1750 lightSensor;
    
    //MySensor gw;
    MyMessage msgTemp(CHILD_ID_TEMP,V_TEMP); // Initialize temperature message
    MyMessage msgHum(CHILD_ID_HUM,V_HUM);
    MyMessage msgLight(CHILD_ID_LIGHT, V_LIGHT_LEVEL); //BH1750
    MyMessage msgMotion(CHILD_ID_MOTION, V_TRIPPED); //MOTION
    
    void presentation(){
    
    sendSketchInfo("Node 6, Temp,Hum,Light,Motion", "1.1"); 
      present(CHILD_ID_TEMP, S_TEMP);   // Present sensor to controller
      present(CHILD_ID_HUM, S_HUM);
      present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); //BH1750
      present(CHILD_ID_MOTION, S_MOTION); /*MOTION*/
    
    //BATTERY
    sendSketchInfo("Battery Meter", "1.0");
    }
    
    
    void setup() {
    
      //BATTERY
        // use the 1.1 V internal reference
    #if defined(__AVR_ATmega2560__)
        analogReference(INTERNAL1V1);
    #else
        analogReference(INTERNAL);
    #endif
    
    //BATTERY
      
      DEBUG_SERIAL(115200);    
      DEBUG_PRINTLN("Serial started");
      
      //DEBUG_PRINT("Voltage: ");
      //DEBUG_PRINT(readVcc()); 
      //DEBUG_PRINTLN(" mV");
    /*
      delay(500);
      DEBUG_PRINT("Internal temp: ");
      DEBUG_PRINT(GetInternalTemp()); // Probably not calibrated. Just to print something.
      DEBUG_PRINTLN(" *C");
    */  
      delay(500); // Allow time for radio if power useed as reset
      //begin(NULL,NODE_ID);
      
      //DEBUG_PRINT("Node and "); DEBUG_PRINTLN("2 children presented.");
      
      raHum.clear();
      lightSensor.begin(); //BH1750
      /* MOTION */
      pinMode(MOTION_DIGITAL_INPUT_SENSOR, INPUT);      // sets the motion sensor digital pin as input
    }
    
    void loop() {
      DEBUG_PRINTLN("Loop started"); 
      measureCount ++;
      
      bool forceTransmit = true;
      
      //if (measureCount > FORCE_TRANSMIT_CYCLE) {
      //forceTransmit = true; 
      //}
      sleep(SLEEP_TIME);
      //BATTERY
    // get the battery Voltage
        int sensorValue = analogRead(BATTERY_SENSE_PIN);
    #ifdef MY_DEBUG
        Serial.println(sensorValue);
    #endif
    
        // 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
    
        int batteryPcnt = sensorValue / 10;
    
    #ifdef MY_DEBUG
        float batteryV  = sensorValue * 0.003363075;
        Serial.print("Battery Voltage: ");
        Serial.print(batteryV);
        Serial.println(" V");
    
        Serial.print("Battery percent: ");
        Serial.print(batteryPcnt);
        Serial.println(" %");
    #endif
    
        if (oldBatteryPcnt != batteryPcnt) {
            // Power up radio after sleep
            sendBatteryLevel(batteryPcnt);
            oldBatteryPcnt = batteryPcnt;
        }
    
      //BATTERY
      sendTempHumidityMeasurements(forceTransmit);
      //BH1750   
        uint16_t lux = lightSensor.readLightLevel();// Get Lux value
        Serial.println(lux);
        DEBUG_PRINT("LUX: ");DEBUG_PRINTLN(lux);
        if (lux != lastlux) {
            send(msgLight.set(lux));
            lastlux = lux; }
      //BH1750
      /* MOTION */
      // Read digital motion value
      bool tripped = digitalRead(MOTION_DIGITAL_INPUT_SENSOR) == HIGH;
      Serial.println(tripped);
      send(msgMotion.set(tripped?"1":"0"));  // Send tripped value to gw
      
      DEBUG_PRINTLN("Loop ended");
      }
    /*********************************************
     * * 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;
      DEBUG_PRINTLN("Send TEMP and HUM started"); 
      si7021_env data = humiditySensor.getHumidityAndTemperature();
      float temperature = data.celsiusHundredths / 100.0;
      DEBUG_PRINT("T: ");DEBUG_PRINTLN(temperature);
      float diffTemp = abs(lastTemperature - temperature);
      DEBUG_PRINT(F("TempDiff :"));DEBUG_PRINTLN(diffTemp);
      //if (diffTemp > TEMP_TRANSMIT_THRESHOLD || tx) {
      send(msgTemp.set(temperature, 1));
      //lastTemperature = temperature;
      //measureCount = 0;
      DEBUG_PRINTLN("T sent!");
      //}
      
      int humidity = data.humidityPercent;
      DEBUG_PRINT("H: ");DEBUG_PRINTLN(humidity);
      raHum.addValue(humidity);
      humidity = raHum.getAverage();  // MA sample imply reasonable fast sample frequency
      float diffHum = abs(lastHumidity - humidity);  
      DEBUG_PRINT(F("HumDiff  :"));DEBUG_PRINTLN(diffHum); 
      //if (diffHum > HUMI_TRANSMIT_THRESHOLD || tx) {
      send(msgHum.set(humidity, 1));
      //lastHumidity = humidity;
      //measureCount = 0;
      DEBUG_PRINTLN("H sent!");
      //}
    
    }```
    
    Thank you in advance!!
    sundberg84S Offline
    sundberg84S Offline
    sundberg84
    Hardware Contributor
    wrote on last edited by
    #3

    @tommas - have a look at the build section: https://www.mysensors.org/build/battery

    Controller: Proxmox VM - Home Assistant
    MySensors GW: Arduino Uno - W5100 Ethernet, Gw Shield Nrf24l01+ 2,4Ghz
    MySensors GW: Arduino Uno - Gw Shield RFM69, 433mhz
    RFLink GW - Arduino Mega + RFLink Shield, 433mhz

    T 1 Reply Last reply
    0
    • sundberg84S sundberg84

      @tommas - have a look at the build section: https://www.mysensors.org/build/battery

      T Offline
      T Offline
      Tommas
      wrote on last edited by
      #4

      @sundberg84

      Oh ok. I have put this in the code, so it is OK, i think. I thought that SLEEP_TIME isnt equal to powerdown, but it seems that i misunderstood.
      I use your easypcb board Sundberg.... Is your battery measurement code better than this standard mysensors one?

      Thank You again!

      sundberg84S 1 Reply Last reply
      0
      • gohanG gohan

        @tommas said in Arduino mini pro 3.3 battery optimization code:

        sleep(SLEEP_TIME);

        That is the power down command, usually it is put at the end of loop

        T Offline
        T Offline
        Tommas
        wrote on last edited by
        #5

        @gohan

        Dear Gohan!

        Thank you! I thought that it isnt equal with this: https://www.mysensors.org/download/sensor_api_20#sleeping ....
        But perhaps I misunderstood something because you says that it is the same sleep mode...

        1 Reply Last reply
        0
        • gohanG Offline
          gohanG Offline
          gohan
          Mod
          wrote on last edited by
          #6

          SLEEP_TIME is defined as the amount of time the node will sleep, but it is the function sleep() that actually puts the node into low power mode and that usually is at the end of loop

          T 1 Reply Last reply
          0
          • T Tommas

            @sundberg84

            Oh ok. I have put this in the code, so it is OK, i think. I thought that SLEEP_TIME isnt equal to powerdown, but it seems that i misunderstood.
            I use your easypcb board Sundberg.... Is your battery measurement code better than this standard mysensors one?

            Thank You again!

            sundberg84S Offline
            sundberg84S Offline
            sundberg84
            Hardware Contributor
            wrote on last edited by sundberg84
            #7

            @tommas - "my" batterycode is due to a booster and a voltage divider. Its not possible to compare this to @Yveaux Vcc library which uses the internal vcc to measure battery level. This is not possible to use since you boost your VCC on the arduino. I think my code works great though for a voltage divider setup.

            Controller: Proxmox VM - Home Assistant
            MySensors GW: Arduino Uno - W5100 Ethernet, Gw Shield Nrf24l01+ 2,4Ghz
            MySensors GW: Arduino Uno - Gw Shield RFM69, 433mhz
            RFLink GW - Arduino Mega + RFLink Shield, 433mhz

            G 1 Reply Last reply
            0
            • T Offline
              T Offline
              Tommas
              wrote on last edited by
              #8

              Hi All!

              Im near to get it work:) .
              Someone could write an example openhab2 thing and item for Battery Voltage handling?

              Thank you!

              1 Reply Last reply
              0
              • sundberg84S sundberg84

                @tommas - "my" batterycode is due to a booster and a voltage divider. Its not possible to compare this to @Yveaux Vcc library which uses the internal vcc to measure battery level. This is not possible to use since you boost your VCC on the arduino. I think my code works great though for a voltage divider setup.

                G Offline
                G Offline
                ghiglie
                wrote on last edited by
                #9

                @sundberg84 said in Arduino mini pro 3.3 battery optimization code:

                @tommas - "my" batterycode is due to a booster and a voltage divider. Its not possible to compare this to @Yveaux Vcc library which uses the internal vcc to measure battery level. This is not possible to use since you boost your VCC on the arduino. I think my code works great though for a voltage divider setup.

                Sorry, I'm revisiting a temp/hum sensor running on battery, I lost my code so I'm back to work with this (and signing/encryption, doh!)
                I think I have something similar to yours- I'm boosting the arduino and DHT voltage to 3,3v, while the antenna is directly connected. I have a voltage divider where I get the Voltage measure. Can I borrow directly your code, you think?

                atmega328p serial killer
                HomeAssistant / gateway: ESP8266 & NRF24L01+ gateway

                sundberg84S 1 Reply Last reply
                0
                • G ghiglie

                  @sundberg84 said in Arduino mini pro 3.3 battery optimization code:

                  @tommas - "my" batterycode is due to a booster and a voltage divider. Its not possible to compare this to @Yveaux Vcc library which uses the internal vcc to measure battery level. This is not possible to use since you boost your VCC on the arduino. I think my code works great though for a voltage divider setup.

                  Sorry, I'm revisiting a temp/hum sensor running on battery, I lost my code so I'm back to work with this (and signing/encryption, doh!)
                  I think I have something similar to yours- I'm boosting the arduino and DHT voltage to 3,3v, while the antenna is directly connected. I have a voltage divider where I get the Voltage measure. Can I borrow directly your code, you think?

                  sundberg84S Offline
                  sundberg84S Offline
                  sundberg84
                  Hardware Contributor
                  wrote on last edited by
                  #10

                  @ghiglie - you can, as long as you have the same divider... (which is the standard divider found @ mysensors website.)

                  //=========================
                  // BATTERY MEASURER
                  // 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
                  

                  If not you need to recalculate,

                  Controller: Proxmox VM - Home Assistant
                  MySensors GW: Arduino Uno - W5100 Ethernet, Gw Shield Nrf24l01+ 2,4Ghz
                  MySensors GW: Arduino Uno - Gw Shield RFM69, 433mhz
                  RFLink GW - Arduino Mega + RFLink Shield, 433mhz

                  1 Reply Last reply
                  0
                  • T Tommas

                    Dear All!

                    I would like to use the Arduino Mini Pro 3.3 8Mhz (aTMega328) with 2xAA battery. I have read that it useful to put it in powerdown/sleep mode.
                    Could you help me what code/sketch should I use. I copied to here my beta sketch(It works, but it doesnt have the powerdown function)
                    If someone has any other suggestion related to the code, please write it!

                    /**
                     * The MySensors Arduino library handles the wireless radio link and protocol
                     * between your home built sensors/actuators and HA controller of choice.
                     * The sensors forms a self healing radio network with optional repeaters. Each
                     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
                     * network topology allowing messages to be routed to nodes.
                     *
                     * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
                     * Copyright (C) 2013-2015 Sensnology AB
                     * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
                     *
                     * Documentation: http://www.mysensors.org
                     * Support Forum: http://forum.mysensors.org
                     *
                     * This program is free software; you can redistribute it and/or
                     * modify it under the terms of the GNU General Public License
                     * version 2 as published by the Free Software Foundation.
                     *
                     *******************************
                     *
                     * REVISION HISTORY
                     * Version 1.0: Henrik EKblad
                     * Version 1.1 - 2016-07-20: Converted to MySensors v2.0 and added various improvements - Torben Woltjen (mozzbozz)
                     * 
                     * DESCRIPTION
                     * This sketch provides an example of how to implement a humidity/temperature
                     * sensor using a DHT11/DHT-22.
                     *  
                     * For more information, please visit:
                     * http://www.mysensors.org/build/humidity
                     * 
                     */
                    #define MY_NODE_ID 6
                    // Enable debug prints
                    #define MY_DEBUG
                    
                    // Enable and select radio type attached 
                    #define MY_RADIO_NRF24
                    //#define MY_RADIO_RFM69
                    //#define MY_RS485
                    /* Sketch with Si7021 and battery monitoring.
                    by m26872, 20151109 
                    */
                    #include <MySensors.h>  
                    #include <Wire.h>
                    #include <SI7021.h>
                    #include <SPI.h>
                    #include <RunningAverage.h>
                    #include <BH1750.h> //BH1750
                    
                    #define DEBUG
                    
                    #ifdef DEBUG
                    #define DEBUG_SERIAL(x) Serial.begin(x)
                    #define DEBUG_PRINT(x) Serial.print(x)
                    #define DEBUG_PRINTLN(x) Serial.println(x)
                    #else
                    #define DEBUG_SERIAL(x)
                    #define DEBUG_PRINT(x) 
                    #define DEBUG_PRINTLN(x) 
                    #endif
                    #define MOTION_DIGITAL_INPUT_SENSOR 3 //MOTION
                    
                    #define NODE_ID 6             // <<<<<<<<<<<<<<<<<<<<<<<<<<<   Enter Node_ID
                    #define CHILD_ID_TEMP 0
                    #define CHILD_ID_HUM 1
                    #define CHILD_ID_LIGHT 2 //BH1750
                    #define CHILD_ID_MOTION 3 /*MOTION*/
                    //BATTERY
                    int BATTERY_SENSE_PIN = A0;  // select the input pin for the battery sense point
                    
                    uint32_t SLEEP_TIME = 900000;  // sleep time between reads (seconds * 1000 milliseconds)
                    int oldBatteryPcnt = 0;
                    
                    
                    //#define SLEEP_TIME 15000 // 15s for DEBUG
                    #define SLEEP_TIME 10000   // 5 min
                    //#define FORCE_TRANSMIT_CYCLE 36  // 5min*12=1/hour, 5min*36=1/3hour 
                    #define FORCE_TRANSMIT_CYCLE 1  // 5min*12=1/hour, 5min*36=1/3hour 
                    //#define BATTERY_REPORT_CYCLE 2880   // Once per 5min   =>   12*24*7 = 2016 (one report/week)
                    //#define VMIN 1900
                    //#define VMAX 3300
                    #define HUMI_TRANSMIT_THRESHOLD 3.0  // THRESHOLD tells how much the value should have changed since last time it was transmitted.
                    #define TEMP_TRANSMIT_THRESHOLD 0.5
                    #define AVERAGES 2
                    
                    //int batteryReportCounter = BATTERY_REPORT_CYCLE - 1;  // to make it report the first time.
                    int measureCount = 0;
                    float lastTemperature = -100;
                    int lastHumidity = -100;
                    
                    uint16_t lastlux; //BH1750
                    
                    RunningAverage raHum(AVERAGES);
                    SI7021 humiditySensor;
                    BH1750 lightSensor;
                    
                    //MySensor gw;
                    MyMessage msgTemp(CHILD_ID_TEMP,V_TEMP); // Initialize temperature message
                    MyMessage msgHum(CHILD_ID_HUM,V_HUM);
                    MyMessage msgLight(CHILD_ID_LIGHT, V_LIGHT_LEVEL); //BH1750
                    MyMessage msgMotion(CHILD_ID_MOTION, V_TRIPPED); //MOTION
                    
                    void presentation(){
                    
                    sendSketchInfo("Node 6, Temp,Hum,Light,Motion", "1.1"); 
                      present(CHILD_ID_TEMP, S_TEMP);   // Present sensor to controller
                      present(CHILD_ID_HUM, S_HUM);
                      present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); //BH1750
                      present(CHILD_ID_MOTION, S_MOTION); /*MOTION*/
                    
                    //BATTERY
                    sendSketchInfo("Battery Meter", "1.0");
                    }
                    
                    
                    void setup() {
                    
                      //BATTERY
                        // use the 1.1 V internal reference
                    #if defined(__AVR_ATmega2560__)
                        analogReference(INTERNAL1V1);
                    #else
                        analogReference(INTERNAL);
                    #endif
                    
                    //BATTERY
                      
                      DEBUG_SERIAL(115200);    
                      DEBUG_PRINTLN("Serial started");
                      
                      //DEBUG_PRINT("Voltage: ");
                      //DEBUG_PRINT(readVcc()); 
                      //DEBUG_PRINTLN(" mV");
                    /*
                      delay(500);
                      DEBUG_PRINT("Internal temp: ");
                      DEBUG_PRINT(GetInternalTemp()); // Probably not calibrated. Just to print something.
                      DEBUG_PRINTLN(" *C");
                    */  
                      delay(500); // Allow time for radio if power useed as reset
                      //begin(NULL,NODE_ID);
                      
                      //DEBUG_PRINT("Node and "); DEBUG_PRINTLN("2 children presented.");
                      
                      raHum.clear();
                      lightSensor.begin(); //BH1750
                      /* MOTION */
                      pinMode(MOTION_DIGITAL_INPUT_SENSOR, INPUT);      // sets the motion sensor digital pin as input
                    }
                    
                    void loop() {
                      DEBUG_PRINTLN("Loop started"); 
                      measureCount ++;
                      
                      bool forceTransmit = true;
                      
                      //if (measureCount > FORCE_TRANSMIT_CYCLE) {
                      //forceTransmit = true; 
                      //}
                      sleep(SLEEP_TIME);
                      //BATTERY
                    // get the battery Voltage
                        int sensorValue = analogRead(BATTERY_SENSE_PIN);
                    #ifdef MY_DEBUG
                        Serial.println(sensorValue);
                    #endif
                    
                        // 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
                    
                        int batteryPcnt = sensorValue / 10;
                    
                    #ifdef MY_DEBUG
                        float batteryV  = sensorValue * 0.003363075;
                        Serial.print("Battery Voltage: ");
                        Serial.print(batteryV);
                        Serial.println(" V");
                    
                        Serial.print("Battery percent: ");
                        Serial.print(batteryPcnt);
                        Serial.println(" %");
                    #endif
                    
                        if (oldBatteryPcnt != batteryPcnt) {
                            // Power up radio after sleep
                            sendBatteryLevel(batteryPcnt);
                            oldBatteryPcnt = batteryPcnt;
                        }
                    
                      //BATTERY
                      sendTempHumidityMeasurements(forceTransmit);
                      //BH1750   
                        uint16_t lux = lightSensor.readLightLevel();// Get Lux value
                        Serial.println(lux);
                        DEBUG_PRINT("LUX: ");DEBUG_PRINTLN(lux);
                        if (lux != lastlux) {
                            send(msgLight.set(lux));
                            lastlux = lux; }
                      //BH1750
                      /* MOTION */
                      // Read digital motion value
                      bool tripped = digitalRead(MOTION_DIGITAL_INPUT_SENSOR) == HIGH;
                      Serial.println(tripped);
                      send(msgMotion.set(tripped?"1":"0"));  // Send tripped value to gw
                      
                      DEBUG_PRINTLN("Loop ended");
                      }
                    /*********************************************
                     * * 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;
                      DEBUG_PRINTLN("Send TEMP and HUM started"); 
                      si7021_env data = humiditySensor.getHumidityAndTemperature();
                      float temperature = data.celsiusHundredths / 100.0;
                      DEBUG_PRINT("T: ");DEBUG_PRINTLN(temperature);
                      float diffTemp = abs(lastTemperature - temperature);
                      DEBUG_PRINT(F("TempDiff :"));DEBUG_PRINTLN(diffTemp);
                      //if (diffTemp > TEMP_TRANSMIT_THRESHOLD || tx) {
                      send(msgTemp.set(temperature, 1));
                      //lastTemperature = temperature;
                      //measureCount = 0;
                      DEBUG_PRINTLN("T sent!");
                      //}
                      
                      int humidity = data.humidityPercent;
                      DEBUG_PRINT("H: ");DEBUG_PRINTLN(humidity);
                      raHum.addValue(humidity);
                      humidity = raHum.getAverage();  // MA sample imply reasonable fast sample frequency
                      float diffHum = abs(lastHumidity - humidity);  
                      DEBUG_PRINT(F("HumDiff  :"));DEBUG_PRINTLN(diffHum); 
                      //if (diffHum > HUMI_TRANSMIT_THRESHOLD || tx) {
                      send(msgHum.set(humidity, 1));
                      //lastHumidity = humidity;
                      //measureCount = 0;
                      DEBUG_PRINTLN("H sent!");
                      //}
                    
                    }```
                    
                    Thank you in advance!!
                    T Offline
                    T Offline
                    Tommas
                    wrote on last edited by
                    #11

                    @tommas

                    Dear All!

                    Can I use 2xAA 1.6V NiZn battery for 3.3V arduino mini pro?

                    NeverDieN gohanG 2 Replies Last reply
                    0
                    • T Tommas

                      @tommas

                      Dear All!

                      Can I use 2xAA 1.6V NiZn battery for 3.3V arduino mini pro?

                      NeverDieN Offline
                      NeverDieN Offline
                      NeverDie
                      Hero Member
                      wrote on last edited by NeverDie
                      #12

                      @tommas said in Arduino mini pro 3.3 battery optimization code:

                      @tommas

                      Dear All!

                      Can I use 2xAA 1.6V NiZn battery for 3.3V arduino mini pro?

                      Accoding to wikipedia, at 100% SOC each cell would deliver 1.85V, which is a smidge too high if running the pro mini with its voltage regulator removed. Well, actually, the pro mini would tolerate it, just maybe not the radio.

                      T 1 Reply Last reply
                      0
                      • T Tommas

                        @tommas

                        Dear All!

                        Can I use 2xAA 1.6V NiZn battery for 3.3V arduino mini pro?

                        gohanG Offline
                        gohanG Offline
                        gohan
                        Mod
                        wrote on last edited by
                        #13

                        @tommas get some LiFePo4 AA and you can use a single cell

                        T 1 Reply Last reply
                        0
                        • NeverDieN NeverDie

                          @tommas said in Arduino mini pro 3.3 battery optimization code:

                          @tommas

                          Dear All!

                          Can I use 2xAA 1.6V NiZn battery for 3.3V arduino mini pro?

                          Accoding to wikipedia, at 100% SOC each cell would deliver 1.85V, which is a smidge too high if running the pro mini with its voltage regulator removed. Well, actually, the pro mini would tolerate it, just maybe not the radio.

                          T Offline
                          T Offline
                          Tommas
                          wrote on last edited by
                          #14

                          Dear @neverdie ,
                          Ok, so I wont use these batteries.

                          1 Reply Last reply
                          0
                          • T Tommas

                            Dear All!

                            I would like to use the Arduino Mini Pro 3.3 8Mhz (aTMega328) with 2xAA battery. I have read that it useful to put it in powerdown/sleep mode.
                            Could you help me what code/sketch should I use. I copied to here my beta sketch(It works, but it doesnt have the powerdown function)
                            If someone has any other suggestion related to the code, please write it!

                            /**
                             * The MySensors Arduino library handles the wireless radio link and protocol
                             * between your home built sensors/actuators and HA controller of choice.
                             * The sensors forms a self healing radio network with optional repeaters. Each
                             * repeater and gateway builds a routing tables in EEPROM which keeps track of the
                             * network topology allowing messages to be routed to nodes.
                             *
                             * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
                             * Copyright (C) 2013-2015 Sensnology AB
                             * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
                             *
                             * Documentation: http://www.mysensors.org
                             * Support Forum: http://forum.mysensors.org
                             *
                             * This program is free software; you can redistribute it and/or
                             * modify it under the terms of the GNU General Public License
                             * version 2 as published by the Free Software Foundation.
                             *
                             *******************************
                             *
                             * REVISION HISTORY
                             * Version 1.0: Henrik EKblad
                             * Version 1.1 - 2016-07-20: Converted to MySensors v2.0 and added various improvements - Torben Woltjen (mozzbozz)
                             * 
                             * DESCRIPTION
                             * This sketch provides an example of how to implement a humidity/temperature
                             * sensor using a DHT11/DHT-22.
                             *  
                             * For more information, please visit:
                             * http://www.mysensors.org/build/humidity
                             * 
                             */
                            #define MY_NODE_ID 6
                            // Enable debug prints
                            #define MY_DEBUG
                            
                            // Enable and select radio type attached 
                            #define MY_RADIO_NRF24
                            //#define MY_RADIO_RFM69
                            //#define MY_RS485
                            /* Sketch with Si7021 and battery monitoring.
                            by m26872, 20151109 
                            */
                            #include <MySensors.h>  
                            #include <Wire.h>
                            #include <SI7021.h>
                            #include <SPI.h>
                            #include <RunningAverage.h>
                            #include <BH1750.h> //BH1750
                            
                            #define DEBUG
                            
                            #ifdef DEBUG
                            #define DEBUG_SERIAL(x) Serial.begin(x)
                            #define DEBUG_PRINT(x) Serial.print(x)
                            #define DEBUG_PRINTLN(x) Serial.println(x)
                            #else
                            #define DEBUG_SERIAL(x)
                            #define DEBUG_PRINT(x) 
                            #define DEBUG_PRINTLN(x) 
                            #endif
                            #define MOTION_DIGITAL_INPUT_SENSOR 3 //MOTION
                            
                            #define NODE_ID 6             // <<<<<<<<<<<<<<<<<<<<<<<<<<<   Enter Node_ID
                            #define CHILD_ID_TEMP 0
                            #define CHILD_ID_HUM 1
                            #define CHILD_ID_LIGHT 2 //BH1750
                            #define CHILD_ID_MOTION 3 /*MOTION*/
                            //BATTERY
                            int BATTERY_SENSE_PIN = A0;  // select the input pin for the battery sense point
                            
                            uint32_t SLEEP_TIME = 900000;  // sleep time between reads (seconds * 1000 milliseconds)
                            int oldBatteryPcnt = 0;
                            
                            
                            //#define SLEEP_TIME 15000 // 15s for DEBUG
                            #define SLEEP_TIME 10000   // 5 min
                            //#define FORCE_TRANSMIT_CYCLE 36  // 5min*12=1/hour, 5min*36=1/3hour 
                            #define FORCE_TRANSMIT_CYCLE 1  // 5min*12=1/hour, 5min*36=1/3hour 
                            //#define BATTERY_REPORT_CYCLE 2880   // Once per 5min   =>   12*24*7 = 2016 (one report/week)
                            //#define VMIN 1900
                            //#define VMAX 3300
                            #define HUMI_TRANSMIT_THRESHOLD 3.0  // THRESHOLD tells how much the value should have changed since last time it was transmitted.
                            #define TEMP_TRANSMIT_THRESHOLD 0.5
                            #define AVERAGES 2
                            
                            //int batteryReportCounter = BATTERY_REPORT_CYCLE - 1;  // to make it report the first time.
                            int measureCount = 0;
                            float lastTemperature = -100;
                            int lastHumidity = -100;
                            
                            uint16_t lastlux; //BH1750
                            
                            RunningAverage raHum(AVERAGES);
                            SI7021 humiditySensor;
                            BH1750 lightSensor;
                            
                            //MySensor gw;
                            MyMessage msgTemp(CHILD_ID_TEMP,V_TEMP); // Initialize temperature message
                            MyMessage msgHum(CHILD_ID_HUM,V_HUM);
                            MyMessage msgLight(CHILD_ID_LIGHT, V_LIGHT_LEVEL); //BH1750
                            MyMessage msgMotion(CHILD_ID_MOTION, V_TRIPPED); //MOTION
                            
                            void presentation(){
                            
                            sendSketchInfo("Node 6, Temp,Hum,Light,Motion", "1.1"); 
                              present(CHILD_ID_TEMP, S_TEMP);   // Present sensor to controller
                              present(CHILD_ID_HUM, S_HUM);
                              present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); //BH1750
                              present(CHILD_ID_MOTION, S_MOTION); /*MOTION*/
                            
                            //BATTERY
                            sendSketchInfo("Battery Meter", "1.0");
                            }
                            
                            
                            void setup() {
                            
                              //BATTERY
                                // use the 1.1 V internal reference
                            #if defined(__AVR_ATmega2560__)
                                analogReference(INTERNAL1V1);
                            #else
                                analogReference(INTERNAL);
                            #endif
                            
                            //BATTERY
                              
                              DEBUG_SERIAL(115200);    
                              DEBUG_PRINTLN("Serial started");
                              
                              //DEBUG_PRINT("Voltage: ");
                              //DEBUG_PRINT(readVcc()); 
                              //DEBUG_PRINTLN(" mV");
                            /*
                              delay(500);
                              DEBUG_PRINT("Internal temp: ");
                              DEBUG_PRINT(GetInternalTemp()); // Probably not calibrated. Just to print something.
                              DEBUG_PRINTLN(" *C");
                            */  
                              delay(500); // Allow time for radio if power useed as reset
                              //begin(NULL,NODE_ID);
                              
                              //DEBUG_PRINT("Node and "); DEBUG_PRINTLN("2 children presented.");
                              
                              raHum.clear();
                              lightSensor.begin(); //BH1750
                              /* MOTION */
                              pinMode(MOTION_DIGITAL_INPUT_SENSOR, INPUT);      // sets the motion sensor digital pin as input
                            }
                            
                            void loop() {
                              DEBUG_PRINTLN("Loop started"); 
                              measureCount ++;
                              
                              bool forceTransmit = true;
                              
                              //if (measureCount > FORCE_TRANSMIT_CYCLE) {
                              //forceTransmit = true; 
                              //}
                              sleep(SLEEP_TIME);
                              //BATTERY
                            // get the battery Voltage
                                int sensorValue = analogRead(BATTERY_SENSE_PIN);
                            #ifdef MY_DEBUG
                                Serial.println(sensorValue);
                            #endif
                            
                                // 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
                            
                                int batteryPcnt = sensorValue / 10;
                            
                            #ifdef MY_DEBUG
                                float batteryV  = sensorValue * 0.003363075;
                                Serial.print("Battery Voltage: ");
                                Serial.print(batteryV);
                                Serial.println(" V");
                            
                                Serial.print("Battery percent: ");
                                Serial.print(batteryPcnt);
                                Serial.println(" %");
                            #endif
                            
                                if (oldBatteryPcnt != batteryPcnt) {
                                    // Power up radio after sleep
                                    sendBatteryLevel(batteryPcnt);
                                    oldBatteryPcnt = batteryPcnt;
                                }
                            
                              //BATTERY
                              sendTempHumidityMeasurements(forceTransmit);
                              //BH1750   
                                uint16_t lux = lightSensor.readLightLevel();// Get Lux value
                                Serial.println(lux);
                                DEBUG_PRINT("LUX: ");DEBUG_PRINTLN(lux);
                                if (lux != lastlux) {
                                    send(msgLight.set(lux));
                                    lastlux = lux; }
                              //BH1750
                              /* MOTION */
                              // Read digital motion value
                              bool tripped = digitalRead(MOTION_DIGITAL_INPUT_SENSOR) == HIGH;
                              Serial.println(tripped);
                              send(msgMotion.set(tripped?"1":"0"));  // Send tripped value to gw
                              
                              DEBUG_PRINTLN("Loop ended");
                              }
                            /*********************************************
                             * * 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;
                              DEBUG_PRINTLN("Send TEMP and HUM started"); 
                              si7021_env data = humiditySensor.getHumidityAndTemperature();
                              float temperature = data.celsiusHundredths / 100.0;
                              DEBUG_PRINT("T: ");DEBUG_PRINTLN(temperature);
                              float diffTemp = abs(lastTemperature - temperature);
                              DEBUG_PRINT(F("TempDiff :"));DEBUG_PRINTLN(diffTemp);
                              //if (diffTemp > TEMP_TRANSMIT_THRESHOLD || tx) {
                              send(msgTemp.set(temperature, 1));
                              //lastTemperature = temperature;
                              //measureCount = 0;
                              DEBUG_PRINTLN("T sent!");
                              //}
                              
                              int humidity = data.humidityPercent;
                              DEBUG_PRINT("H: ");DEBUG_PRINTLN(humidity);
                              raHum.addValue(humidity);
                              humidity = raHum.getAverage();  // MA sample imply reasonable fast sample frequency
                              float diffHum = abs(lastHumidity - humidity);  
                              DEBUG_PRINT(F("HumDiff  :"));DEBUG_PRINTLN(diffHum); 
                              //if (diffHum > HUMI_TRANSMIT_THRESHOLD || tx) {
                              send(msgHum.set(humidity, 1));
                              //lastHumidity = humidity;
                              //measureCount = 0;
                              DEBUG_PRINTLN("H sent!");
                              //}
                            
                            }```
                            
                            Thank you in advance!!
                            T Offline
                            T Offline
                            Tommas
                            wrote on last edited by Tommas
                            #15

                            @tommas

                            I did a new code, and it seems that it is do the job.
                            My goal was, that I only send the battery voltage (percent) when:
                            At least one of sensor value transmission occured + The battery report time is elapsed.

                            What do you think about my code? IT IS NOT ONLY MY CODE and it is not clear yet Thank for @gohan , @sundberg84 and mysensors for the base.

                            /**
                             * The MySensors Arduino library handles the wireless radio link and protocol
                             * between your home built sensors/actuators and HA controller of choice.
                             * The sensors forms a self healing radio network with optional repeaters. Each
                             * repeater and gateway builds a routing tables in EEPROM which keeps track of the
                             * network topology allowing messages to be routed to nodes.
                             *
                             * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
                             * Copyright (C) 2013-2015 Sensnology AB
                             * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
                             *
                             * Documentation: http://www.mysensors.org
                             * Support Forum: http://forum.mysensors.org
                             *
                             * This program is free software; you can redistribute it and/or
                             * modify it under the terms of the GNU General Public License
                             * version 2 as published by the Free Software Foundation.
                             *
                             *******************************
                             *
                             * REVISION HISTORY
                             * Version 1.0: Henrik EKblad
                             * Version 1.1 - 2016-07-20: Converted to MySensors v2.0 and added various improvements - Torben Woltjen (mozzbozz)
                             * 
                             * DESCRIPTION
                             * This sketch provides an example of how to implement a humidity/temperature
                             * sensor using a DHT11/DHT-22.
                             *  
                             * For more information, please visit:
                             * http://www.mysensors.org/build/humidity
                             * 
                             */
                            #define MY_NODE_ID 6
                            // Enable debug prints
                            #define MY_DEBUG
                            
                            // Enable and select radio type attached 
                            #define MY_RADIO_NRF24
                            //#define MY_RADIO_RFM69
                            //#define MY_RS485
                            
                            #include <MySensors.h>  
                            #include <Wire.h>
                            #include <SI7021.h>
                            #include <SPI.h>
                            #include <RunningAverage.h>
                            #include <BH1750.h> //BH1750
                            #include <Math.h>
                            #define DEBUG
                            
                            #ifdef DEBUG
                            #define DEBUG_SERIAL(x) Serial.begin(x)
                            #define DEBUG_PRINT(x) Serial.print(x)
                            #define DEBUG_PRINTLN(x) Serial.println(x)
                            #else
                            #define DEBUG_SERIAL(x)
                            #define DEBUG_PRINT(x) 
                            #define DEBUG_PRINTLN(x) 
                            #endif
                            
                            #define NODE_ID 6             // <<<<<<<<<<<<<<<<<<<<<<<<<<<   Enter Node_ID
                            #define CHILD_ID_TEMP 0
                            #define CHILD_ID_HUM 1
                            #define CHILD_ID_LIGHT 2 //BH1750
                            #define CHILD_ID_VBAT 254
                            
                            /*BATTERY*/
                            // BATTERY MEASURER
                            // 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 2.1                                  //  Vmin (radio Min Volt)=1.9V (564v)
                            #define VMAX 3.1                                  //  Vmax = (2xAA bat)=3.0V (892v)
                            int batteryPcnt = 0;                              // Calc value for battery %
                            int battAveragePcnt;
                            int battSumPcnt = 0; 
                            int BATTERY_SENSE_PIN = A0;                       // select the input pin for the battery sense point
                            float VbatAverage=0;
                            float VbatSum=0;
                            //=========================
                            /*BATTERY*/
                            
                            //#define SLEEP_TIME 180000   // 3 min
                            //#define FORCE_TRANSMIT_CYCLE 10  // SLEEP_TIME*FORCE_TRANSMIT_CYCLE=Mindenképp küldi az értéket (Temp+HUM), különben akkor ha HUMI_TRANSMIT_THRESHOLD vagy TEMP_TRANSMIT_THRESHOLD igaz, 
                            //#define BATT_MEASURE_CYCLE 10   // SLEEP_TIME/1000*BATTERY_Measure_CYCLE=Ennyi időnként Veszünk mintát (BATTERY)
                            //#define BATT_REPORT_CYCLE 15   // SLEEP_TIME/1000*BATTERY_REPORT_CYCLE=Ennyi időnként küldi az értéket (BATTERY)
                            #define SLEEP_TIME 300000   // 15sec
                            #define FORCE_TRANSMIT_CYCLE 24  // 30sec SLEEP_TIME*FORCE_TRANSMIT_CYCLE=Mindenképp küldi az értéket (Temp+HUM), különben akkor ha HUMI_TRANSMIT_THRESHOLD vagy TEMP_TRANSMIT_THRESHOLD igaz, 
                            #define BATT_MEASURE_CYCLE 2   // Hányszor vegyünk mintát a küldés előtt
                            #define BATT_REPORT_CYCLE 60     // SLEEP_TIME/1000*BATTERY_REPORT_CYCLE*2=Ennyi időnként küldi az értéket (BATTERY)
                            #define HUMI_TRANSMIT_THRESHOLD 3.0  // THRESHOLD tells how much the value should have changed since last time it was transmitted.
                            #define TEMP_TRANSMIT_THRESHOLD 0.5
                            #define LUX_TRANSMIT_THRESHOLD 10
                            #define AVERAGES 2
                            
                            int measureCount = 0;
                            int battreportCount=-2;
                            float lastTemperature = -100;
                            int lastHumidity = -100;
                            int lastLux = 0; //BH1750
                            boolean transmission_occured = false;
                            RunningAverage raHum(AVERAGES);
                            SI7021 humiditySensor;
                            BH1750 lightSensor;
                            
                            //MySensor gw;
                            MyMessage msgTemp(CHILD_ID_TEMP,V_TEMP); // Initialize temperature message
                            MyMessage msgHum(CHILD_ID_HUM,V_HUM);
                            MyMessage msgLight(CHILD_ID_LIGHT, V_LIGHT_LEVEL); //BH1750
                            MyMessage msgVBat(CHILD_ID_VBAT, V_VOLTAGE); //BH1750
                            
                            
                            void presentation(){
                            
                            sendSketchInfo("Node 6, Temp,Hum,Light", "1.1"); 
                              present(CHILD_ID_TEMP, S_TEMP);   // Present sensor to controller
                              present(CHILD_ID_HUM, S_HUM);
                              present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); //BH1750
                              present(CHILD_ID_VBAT, S_MULTIMETER); //BH1750
                            }
                            
                            
                            void setup() {
                            
                              DEBUG_SERIAL(115200);    
                              DEBUG_PRINTLN("Serial started");
                            
                              delay(500); // Allow time for radio if power useed as reset
                              
                              raHum.clear();
                              lightSensor.begin(); //BH1750
                            
                              
                              /*BATTERY*/
                               //=========================
                              // BATTERY MEASURER
                              //Set internal ref to internal to be able to measure bat 0-1v
                              //Make sure this fits other sensors using analogRead()! 
                              //If you have a sensor reporting 0-5v you need to change analogReference() before reading that sensor.
                              
                              analogReference(INTERNAL);
                              //DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
                              //INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
                              //EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.
                              
                              //Battery inital calc
                              Serial.print("With Battery VMax (100%) = "); Serial.print(VMAX); Serial.print("volts and Vmin (0%) = "); Serial.print(VMIN); Serial.println(" volts");
                              Serial.print("Battert Percent 25%/50%/75% should be: "); Serial.print(((VMAX - VMIN) / 4) + VMIN); Serial.print("/"); Serial.print(((VMAX - VMIN) / 2) + VMIN); Serial.print("/"); Serial.println(VMAX - ((VMAX - VMIN) / 4));
                              delay(500);
                              int sensorValue = analogRead(BATTERY_SENSE_PIN);
                              delay(50);
                              float Vbat  = sensorValue * VBAT_PER_BITS;
                              int batteryPcnt = static_cast<int>(((Vbat - VMIN) / (VMAX - VMIN)) * 100.);
                              Serial.print("Current battery are measured to (please confirm!): "); Serial.print(batteryPcnt); Serial.print(" % - Or "); Serial.print(Vbat); Serial.println(" Volts");
                              //=========================
                              /*BATTERY*/
                            }
                            
                            void loop() {
                              DEBUG_PRINTLN("Loop started"); 
                              boolean forceTransmit = false;
                              transmission_occured = false;
                              battreportCount ++;
                              measureCount ++;
                              forceTransmit = false;
                              
                              if (measureCount == FORCE_TRANSMIT_CYCLE) {
                              forceTransmit = true;
                              measureCount = 0;
                              }
                              
                              sendTempHumidityMeasurements(forceTransmit);
                              sendLightMeasurements(forceTransmit);
                            
                              Serial.print("battreportCount");Serial.println(battreportCount);
                                /*BATTERY*/
                                //=========================
                                // BATTERY MEASURER
                                if(((transmission_occured) && (battreportCount>=BATT_REPORT_CYCLE)) || (battreportCount == -1)){
                                        Serial.print("----BATTERY SEND/Measure CYCLE---- ");
                                        MeasureBattery();
                                        send(msgVBat.set(VbatAverage, 3));
                                        sendBatteryLevel(battAveragePcnt);
                                        Serial.print("Battery Average (Send): "); Serial.print(battAveragePcnt); Serial.println(" %");
                                        Serial.print("Battery Average Voltage (Send): "); Serial.print(VbatAverage); Serial.println(" V");
                                        battreportCount=0; 
                                        battAveragePcnt=0;
                                        VbatAverage=0;
                                        VbatSum=0;
                                        battSumPcnt=0;
                                        measureCount=0;
                                        }
                              //=========================
                              /*BATTERY*/
                              
                              DEBUG_PRINTLN("Loop ended");
                              sleep(SLEEP_TIME);
                            }
                            /*********************************************
                             * * 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;
                              DEBUG_PRINTLN("Send TEMP and HUM started"); 
                              si7021_env data = humiditySensor.getHumidityAndTemperature();
                              float temperature = data.celsiusHundredths / 100.0;
                              DEBUG_PRINT("T: ");DEBUG_PRINTLN(temperature);
                              float diffTemp = abs(lastTemperature - temperature);
                              DEBUG_PRINT(F("TempDiff :"));DEBUG_PRINTLN(diffTemp);
                              if (diffTemp > TEMP_TRANSMIT_THRESHOLD || tx) {
                                send(msgTemp.set(temperature, 1));
                                lastTemperature = temperature;
                                DEBUG_PRINTLN("TEMP sent!");
                                transmission_occured = true;
                               
                                }
                              
                              int humidity = data.humidityPercent;
                              DEBUG_PRINT("H: ");DEBUG_PRINTLN(humidity);
                              raHum.addValue(humidity);
                              humidity = raHum.getAverage();  // MA sample imply reasonable fast sample frequency
                              float diffHum = abs(lastHumidity - humidity);  
                              DEBUG_PRINT(F("HumDiff  :"));DEBUG_PRINTLN(diffHum); 
                              if (diffHum > HUMI_TRANSMIT_THRESHOLD || tx) {
                                send(msgHum.set(humidity, 1));
                                lastHumidity = humidity;
                                DEBUG_PRINTLN("HUM sent!");
                                transmission_occured = true;
                                
                                }
                            
                            }
                            
                            //BH1750
                            void sendLightMeasurements(bool force){
                                bool tx = force;
                                int lux = lightSensor.readLightLevel();// Get Lux value
                                float diffLux = abs(lastLux - lux);
                                //Serial.println(lux);
                                DEBUG_PRINT("LUX: ");DEBUG_PRINTLN(lux);
                                DEBUG_PRINT("LuxDiff: ");DEBUG_PRINTLN(diffLux);
                                if (diffLux > LUX_TRANSMIT_THRESHOLD || tx) {
                                  send(msgLight.set(lux));
                                  lastLux = lux;
                                  DEBUG_PRINTLN("LUX sent!");
                                  transmission_occured = true;
                                  }
                            }
                            //BH1750
                            
                            /*BATTERY*/
                            //=========================
                            // BATTERY MEASURER
                            void MeasureBattery() //The battery calculations
                            {
                              
                              
                              
                             if (batteryPcnt > 100) {
                                 batteryPcnt = 100;
                                }
                                  for (int i = 1 ; i <= BATT_MEASURE_CYCLE; i++)
                                  {
                                    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("I: ");Serial.println(i);
                                    Serial.print("Battery percent: "); Serial.print(batteryPcnt); Serial.print(" %"); Serial.print("Battery Voltage: "); Serial.print(Vbat); Serial.println(" Volts");
                                    battSumPcnt += batteryPcnt;
                                    Serial.print("battSumPcnt:::");Serial.println(battSumPcnt);
                                    battAveragePcnt = battSumPcnt / i;
                                    VbatSum += Vbat;
                                    VbatAverage = VbatSum / i;
                                    Serial.print("battAveragePcnt Calculated: ");Serial.println(battAveragePcnt);
                                    
                                  }
                                }
                            //=========================
                            /*BATTERY*/
                            
                            T 1 Reply Last reply
                            0
                            • T Tommas

                              @tommas

                              I did a new code, and it seems that it is do the job.
                              My goal was, that I only send the battery voltage (percent) when:
                              At least one of sensor value transmission occured + The battery report time is elapsed.

                              What do you think about my code? IT IS NOT ONLY MY CODE and it is not clear yet Thank for @gohan , @sundberg84 and mysensors for the base.

                              /**
                               * The MySensors Arduino library handles the wireless radio link and protocol
                               * between your home built sensors/actuators and HA controller of choice.
                               * The sensors forms a self healing radio network with optional repeaters. Each
                               * repeater and gateway builds a routing tables in EEPROM which keeps track of the
                               * network topology allowing messages to be routed to nodes.
                               *
                               * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
                               * Copyright (C) 2013-2015 Sensnology AB
                               * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
                               *
                               * Documentation: http://www.mysensors.org
                               * Support Forum: http://forum.mysensors.org
                               *
                               * This program is free software; you can redistribute it and/or
                               * modify it under the terms of the GNU General Public License
                               * version 2 as published by the Free Software Foundation.
                               *
                               *******************************
                               *
                               * REVISION HISTORY
                               * Version 1.0: Henrik EKblad
                               * Version 1.1 - 2016-07-20: Converted to MySensors v2.0 and added various improvements - Torben Woltjen (mozzbozz)
                               * 
                               * DESCRIPTION
                               * This sketch provides an example of how to implement a humidity/temperature
                               * sensor using a DHT11/DHT-22.
                               *  
                               * For more information, please visit:
                               * http://www.mysensors.org/build/humidity
                               * 
                               */
                              #define MY_NODE_ID 6
                              // Enable debug prints
                              #define MY_DEBUG
                              
                              // Enable and select radio type attached 
                              #define MY_RADIO_NRF24
                              //#define MY_RADIO_RFM69
                              //#define MY_RS485
                              
                              #include <MySensors.h>  
                              #include <Wire.h>
                              #include <SI7021.h>
                              #include <SPI.h>
                              #include <RunningAverage.h>
                              #include <BH1750.h> //BH1750
                              #include <Math.h>
                              #define DEBUG
                              
                              #ifdef DEBUG
                              #define DEBUG_SERIAL(x) Serial.begin(x)
                              #define DEBUG_PRINT(x) Serial.print(x)
                              #define DEBUG_PRINTLN(x) Serial.println(x)
                              #else
                              #define DEBUG_SERIAL(x)
                              #define DEBUG_PRINT(x) 
                              #define DEBUG_PRINTLN(x) 
                              #endif
                              
                              #define NODE_ID 6             // <<<<<<<<<<<<<<<<<<<<<<<<<<<   Enter Node_ID
                              #define CHILD_ID_TEMP 0
                              #define CHILD_ID_HUM 1
                              #define CHILD_ID_LIGHT 2 //BH1750
                              #define CHILD_ID_VBAT 254
                              
                              /*BATTERY*/
                              // BATTERY MEASURER
                              // 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 2.1                                  //  Vmin (radio Min Volt)=1.9V (564v)
                              #define VMAX 3.1                                  //  Vmax = (2xAA bat)=3.0V (892v)
                              int batteryPcnt = 0;                              // Calc value for battery %
                              int battAveragePcnt;
                              int battSumPcnt = 0; 
                              int BATTERY_SENSE_PIN = A0;                       // select the input pin for the battery sense point
                              float VbatAverage=0;
                              float VbatSum=0;
                              //=========================
                              /*BATTERY*/
                              
                              //#define SLEEP_TIME 180000   // 3 min
                              //#define FORCE_TRANSMIT_CYCLE 10  // SLEEP_TIME*FORCE_TRANSMIT_CYCLE=Mindenképp küldi az értéket (Temp+HUM), különben akkor ha HUMI_TRANSMIT_THRESHOLD vagy TEMP_TRANSMIT_THRESHOLD igaz, 
                              //#define BATT_MEASURE_CYCLE 10   // SLEEP_TIME/1000*BATTERY_Measure_CYCLE=Ennyi időnként Veszünk mintát (BATTERY)
                              //#define BATT_REPORT_CYCLE 15   // SLEEP_TIME/1000*BATTERY_REPORT_CYCLE=Ennyi időnként küldi az értéket (BATTERY)
                              #define SLEEP_TIME 300000   // 15sec
                              #define FORCE_TRANSMIT_CYCLE 24  // 30sec SLEEP_TIME*FORCE_TRANSMIT_CYCLE=Mindenképp küldi az értéket (Temp+HUM), különben akkor ha HUMI_TRANSMIT_THRESHOLD vagy TEMP_TRANSMIT_THRESHOLD igaz, 
                              #define BATT_MEASURE_CYCLE 2   // Hányszor vegyünk mintát a küldés előtt
                              #define BATT_REPORT_CYCLE 60     // SLEEP_TIME/1000*BATTERY_REPORT_CYCLE*2=Ennyi időnként küldi az értéket (BATTERY)
                              #define HUMI_TRANSMIT_THRESHOLD 3.0  // THRESHOLD tells how much the value should have changed since last time it was transmitted.
                              #define TEMP_TRANSMIT_THRESHOLD 0.5
                              #define LUX_TRANSMIT_THRESHOLD 10
                              #define AVERAGES 2
                              
                              int measureCount = 0;
                              int battreportCount=-2;
                              float lastTemperature = -100;
                              int lastHumidity = -100;
                              int lastLux = 0; //BH1750
                              boolean transmission_occured = false;
                              RunningAverage raHum(AVERAGES);
                              SI7021 humiditySensor;
                              BH1750 lightSensor;
                              
                              //MySensor gw;
                              MyMessage msgTemp(CHILD_ID_TEMP,V_TEMP); // Initialize temperature message
                              MyMessage msgHum(CHILD_ID_HUM,V_HUM);
                              MyMessage msgLight(CHILD_ID_LIGHT, V_LIGHT_LEVEL); //BH1750
                              MyMessage msgVBat(CHILD_ID_VBAT, V_VOLTAGE); //BH1750
                              
                              
                              void presentation(){
                              
                              sendSketchInfo("Node 6, Temp,Hum,Light", "1.1"); 
                                present(CHILD_ID_TEMP, S_TEMP);   // Present sensor to controller
                                present(CHILD_ID_HUM, S_HUM);
                                present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); //BH1750
                                present(CHILD_ID_VBAT, S_MULTIMETER); //BH1750
                              }
                              
                              
                              void setup() {
                              
                                DEBUG_SERIAL(115200);    
                                DEBUG_PRINTLN("Serial started");
                              
                                delay(500); // Allow time for radio if power useed as reset
                                
                                raHum.clear();
                                lightSensor.begin(); //BH1750
                              
                                
                                /*BATTERY*/
                                 //=========================
                                // BATTERY MEASURER
                                //Set internal ref to internal to be able to measure bat 0-1v
                                //Make sure this fits other sensors using analogRead()! 
                                //If you have a sensor reporting 0-5v you need to change analogReference() before reading that sensor.
                                
                                analogReference(INTERNAL);
                                //DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
                                //INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
                                //EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.
                                
                                //Battery inital calc
                                Serial.print("With Battery VMax (100%) = "); Serial.print(VMAX); Serial.print("volts and Vmin (0%) = "); Serial.print(VMIN); Serial.println(" volts");
                                Serial.print("Battert Percent 25%/50%/75% should be: "); Serial.print(((VMAX - VMIN) / 4) + VMIN); Serial.print("/"); Serial.print(((VMAX - VMIN) / 2) + VMIN); Serial.print("/"); Serial.println(VMAX - ((VMAX - VMIN) / 4));
                                delay(500);
                                int sensorValue = analogRead(BATTERY_SENSE_PIN);
                                delay(50);
                                float Vbat  = sensorValue * VBAT_PER_BITS;
                                int batteryPcnt = static_cast<int>(((Vbat - VMIN) / (VMAX - VMIN)) * 100.);
                                Serial.print("Current battery are measured to (please confirm!): "); Serial.print(batteryPcnt); Serial.print(" % - Or "); Serial.print(Vbat); Serial.println(" Volts");
                                //=========================
                                /*BATTERY*/
                              }
                              
                              void loop() {
                                DEBUG_PRINTLN("Loop started"); 
                                boolean forceTransmit = false;
                                transmission_occured = false;
                                battreportCount ++;
                                measureCount ++;
                                forceTransmit = false;
                                
                                if (measureCount == FORCE_TRANSMIT_CYCLE) {
                                forceTransmit = true;
                                measureCount = 0;
                                }
                                
                                sendTempHumidityMeasurements(forceTransmit);
                                sendLightMeasurements(forceTransmit);
                              
                                Serial.print("battreportCount");Serial.println(battreportCount);
                                  /*BATTERY*/
                                  //=========================
                                  // BATTERY MEASURER
                                  if(((transmission_occured) && (battreportCount>=BATT_REPORT_CYCLE)) || (battreportCount == -1)){
                                          Serial.print("----BATTERY SEND/Measure CYCLE---- ");
                                          MeasureBattery();
                                          send(msgVBat.set(VbatAverage, 3));
                                          sendBatteryLevel(battAveragePcnt);
                                          Serial.print("Battery Average (Send): "); Serial.print(battAveragePcnt); Serial.println(" %");
                                          Serial.print("Battery Average Voltage (Send): "); Serial.print(VbatAverage); Serial.println(" V");
                                          battreportCount=0; 
                                          battAveragePcnt=0;
                                          VbatAverage=0;
                                          VbatSum=0;
                                          battSumPcnt=0;
                                          measureCount=0;
                                          }
                                //=========================
                                /*BATTERY*/
                                
                                DEBUG_PRINTLN("Loop ended");
                                sleep(SLEEP_TIME);
                              }
                              /*********************************************
                               * * 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;
                                DEBUG_PRINTLN("Send TEMP and HUM started"); 
                                si7021_env data = humiditySensor.getHumidityAndTemperature();
                                float temperature = data.celsiusHundredths / 100.0;
                                DEBUG_PRINT("T: ");DEBUG_PRINTLN(temperature);
                                float diffTemp = abs(lastTemperature - temperature);
                                DEBUG_PRINT(F("TempDiff :"));DEBUG_PRINTLN(diffTemp);
                                if (diffTemp > TEMP_TRANSMIT_THRESHOLD || tx) {
                                  send(msgTemp.set(temperature, 1));
                                  lastTemperature = temperature;
                                  DEBUG_PRINTLN("TEMP sent!");
                                  transmission_occured = true;
                                 
                                  }
                                
                                int humidity = data.humidityPercent;
                                DEBUG_PRINT("H: ");DEBUG_PRINTLN(humidity);
                                raHum.addValue(humidity);
                                humidity = raHum.getAverage();  // MA sample imply reasonable fast sample frequency
                                float diffHum = abs(lastHumidity - humidity);  
                                DEBUG_PRINT(F("HumDiff  :"));DEBUG_PRINTLN(diffHum); 
                                if (diffHum > HUMI_TRANSMIT_THRESHOLD || tx) {
                                  send(msgHum.set(humidity, 1));
                                  lastHumidity = humidity;
                                  DEBUG_PRINTLN("HUM sent!");
                                  transmission_occured = true;
                                  
                                  }
                              
                              }
                              
                              //BH1750
                              void sendLightMeasurements(bool force){
                                  bool tx = force;
                                  int lux = lightSensor.readLightLevel();// Get Lux value
                                  float diffLux = abs(lastLux - lux);
                                  //Serial.println(lux);
                                  DEBUG_PRINT("LUX: ");DEBUG_PRINTLN(lux);
                                  DEBUG_PRINT("LuxDiff: ");DEBUG_PRINTLN(diffLux);
                                  if (diffLux > LUX_TRANSMIT_THRESHOLD || tx) {
                                    send(msgLight.set(lux));
                                    lastLux = lux;
                                    DEBUG_PRINTLN("LUX sent!");
                                    transmission_occured = true;
                                    }
                              }
                              //BH1750
                              
                              /*BATTERY*/
                              //=========================
                              // BATTERY MEASURER
                              void MeasureBattery() //The battery calculations
                              {
                                
                                
                                
                               if (batteryPcnt > 100) {
                                   batteryPcnt = 100;
                                  }
                                    for (int i = 1 ; i <= BATT_MEASURE_CYCLE; i++)
                                    {
                                      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("I: ");Serial.println(i);
                                      Serial.print("Battery percent: "); Serial.print(batteryPcnt); Serial.print(" %"); Serial.print("Battery Voltage: "); Serial.print(Vbat); Serial.println(" Volts");
                                      battSumPcnt += batteryPcnt;
                                      Serial.print("battSumPcnt:::");Serial.println(battSumPcnt);
                                      battAveragePcnt = battSumPcnt / i;
                                      VbatSum += Vbat;
                                      VbatAverage = VbatSum / i;
                                      Serial.print("battAveragePcnt Calculated: ");Serial.println(battAveragePcnt);
                                      
                                    }
                                  }
                              //=========================
                              /*BATTERY*/
                              
                              T Offline
                              T Offline
                              Tommas
                              wrote on last edited by
                              #16

                              @tommas

                              Should I use any other sleep "code"? How I know that the nrf24L01 go to sleep?

                              gohanG 1 Reply Last reply
                              0
                              • gohanG gohan

                                @tommas get some LiFePo4 AA and you can use a single cell

                                T Offline
                                T Offline
                                Tommas
                                wrote on last edited by
                                #17

                                @gohan said in Arduino mini pro 3.3 battery optimization code:

                                LiFePo4 AA

                                THank You! I will try!

                                1 Reply Last reply
                                0
                                • T Tommas

                                  @tommas

                                  Should I use any other sleep "code"? How I know that the nrf24L01 go to sleep?

                                  gohanG Offline
                                  gohanG Offline
                                  gohan
                                  Mod
                                  wrote on last edited by
                                  #18

                                  @tommas said in Arduino mini pro 3.3 battery optimization code:

                                  @tommas

                                  Should I use any other sleep "code"? How I know that the nrf24L01 go to sleep?

                                  If you measure current while the node is sleeping, if it is in the range 6 to 20 uA you are good

                                  1 Reply Last reply
                                  0
                                  • gohanG gohan

                                    SLEEP_TIME is defined as the amount of time the node will sleep, but it is the function sleep() that actually puts the node into low power mode and that usually is at the end of loop

                                    T Offline
                                    T Offline
                                    Tommas
                                    wrote on last edited by
                                    #19

                                    @gohan said in Arduino mini pro 3.3 battery optimization code:

                                    loop

                                    What kind of sleep is it? There are parameters out there. ADC_OFF and some and some... Is this sleep turn off adc?

                                    1 Reply Last reply
                                    0
                                    • gohanG Offline
                                      gohanG Offline
                                      gohan
                                      Mod
                                      wrote on last edited by
                                      #20

                                      Just use the sleep () function, that's it

                                      T 1 Reply Last reply
                                      0
                                      • gohanG gohan

                                        Just use the sleep () function, that's it

                                        T Offline
                                        T Offline
                                        Tommas
                                        wrote on last edited by
                                        #21

                                        @gohan

                                        Ok! After the "loop ended " the node should go to sleep. On the console I see these lines:
                                        Loop ended
                                        62763 MCO:SLP:MS=300000,SMS=0,I1=255,M1=255,I2=255,M2=255
                                        62773 MCO:SLP:TPD

                                        What does it mean?

                                        1 Reply Last reply
                                        0
                                        • korttomaK Offline
                                          korttomaK Offline
                                          korttoma
                                          Hero Member
                                          wrote on last edited by korttoma
                                          #22

                                          @tommas said in Arduino mini pro 3.3 battery optimization code:

                                          @gohan

                                          Ok! After the "loop ended " the node should go to sleep. On the console I see these lines:
                                          Loop ended
                                          62763 MCO:SLP:MS=300000,SMS=0,I1=255,M1=255,I2=255,M2=255
                                          62773 MCO:SLP:TPD

                                          What does it mean?

                                          Log Parser is your friend ;)

                                          • Tomas
                                          T 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          12

                                          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