Measuring battery voltage, which way is best?



  • I remember seeing the below code for reading battery levels of arduino without the need for external components.

    long readVcc() {
      // Read 1.1V reference against AVcc
      // set the reference to Vcc and the measurement to the internal 1.1V reference
      #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
        ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
        ADMUX = _BV(MUX5) | _BV(MUX0);
      #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
        ADMUX = _BV(MUX3) | _BV(MUX2);
      #else
        ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      #endif  
    
      delay(2); // Wait for Vref to settle
      ADCSRA |= _BV(ADSC); // Start conversion
      while (bit_is_set(ADCSRA,ADSC)); // measuring
    
      uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH  
      uint8_t high = ADCH; // unlocks both
    
      result = (high<<8) | low;
    
      result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
      return result; // Vcc in millivolts
    }
    

    It would appear to be good as it reduces space needed, reduces the Bom, and saves constant current flow through a voltage divider.

    The build page here seems to still prefer the analog read method and I am just wondering why the internal option has not been adopted and what difference we could expect between options?


  • Mod

    @skywatch I think the "internal" method can only be used when the Arduino is powered directly from battery. If the Arduino is powered through a step-up, and ldo or something similar, a different method (like the one on the build page) must be used.



  • Wise words as always @mfalkvidd !

    Thank you for clearing that up for me. I wasn't sure as both compiled and I would have tested but instead had to go to my Mothers (91 years old and needs a lot of maintenance). That and the 6cm of snow had finally melted! 😉

    I will be running straight from battery so no issues there (either CR2032 or 2x AAA) and have got the code to this for the battery monitoring.....

    readVcc;
    
      //send battery level to controller...
      vSend = float(result) / 1000.0;
      send(msgVSend.set(vSend, 2));
      wait(5000);
    
      //calc and send batt percent to controller...
      int sensorValue = vSend / 0.003363075;
      batteryPcnt = sensorValue / 10;
      if (oldBatteryPcnt != batteryPcnt) {
        sendBatteryLevel(batteryPcnt);
        oldBatteryPcnt = batteryPcnt;
      }
    

    If you have time can you see any errors or issues in the way I have it? Hopefully I will test tomorrow, so no pressure! 🙂 Heeeeee.....


  • Mod

    @skywatch both methods will compile regardless of how the Arduino gets its power.

    The difference is that if you have a step-up or ldo, the "internal" method will measure the output of the step-up/ldo, regardless of what the battery voltage is.



  • @mfalkvidd Great! 😉

    All understood now. I will make some programming cables up today and maybe get time to test it all out!


  • Mod

    @skywatch I have added the "internal" measurement method to https://www.mysensors.org/build/battery#measuring-and-reporting-battery-level and created a new example sketch that uses the internal method, based on the code you provided above. The battery page did not cover the internal method before.

    I'll need to update the reference to the example sketch when the pull request has been vetted and merged. https://github.com/mysensors/MySensors/pull/1470



  • Unless it gets integrated into the MySensors library itself, it may be easier for some people to use a little library for that purpose? Because it "hides" all the technical stuff, setting and reading the registers. I have been using Yveaux's Arduino_VCC library in the past, which works great. Anyway - it's always good to have options.


  • Mod

    @BearWithBeard yes, Yveaux’s library is great. But having to install a separate library, and the correct version if the library ever breaks backwards compatibility, is something we know beginners often struggle with.



  • @mfalkvidd Thanks for adding it to the battery section, I am sure it will help people looking for a simple way of doing this. The link isn't working for me though...

    As it is I have modified my code so that the brown out voltage is 0% and initial voltage is 100% - seemed logical to get the best granularity in the readings. I sould be testing it out in the next few days and if OK I'll send that to you to add in as well if you like.


  • Mod

    @skywatch could you expand on ”isn’t working”?

    This is what it looks like for me:
    D98CA384-FDF3-4F13-AAA5-F53EB805599E.png



  • @mfalkvidd I expected the link to take me to the git page when clicked on, maybe it wasn't meant to do that?

    OK, it's not a hyperlink afterall - but the text for the page is truncated at then end - here is what I see.....

    Battlink.jpg



  • The URL is in an inline code HTML element and the CSS rule #article code {white-space: nowrap;} prevents long lines from breaking the layout, causing the (visual) truncation depending on the window size. Double-clicking or marking the whole line with the cursor gives you the full link, but you can't simply click on it to open the URL. A hyperlink would wrap (and be clickable).

    mysensors-code-link-wrap.png

    I assume this is only a temporary solution. It might be better though to replace it with a hyperlink tag or better, embed it like the external measurement example in the section below it (once it's added to the examples repo).

    @mfalkvidd Okay, understood. Managing external libraries in ArduinoIDE projects can be cumbersome and confusing. Just brainstorming here - two ways of clarifying that external libraries are required in a provided example sketch:

    • After including an external library, add a conditional #error preprocessor directive that checks if the library-specific header guard is defined. This doesn't address backwards compatibility issues though:
    #include <Vcc.h>
    #ifndef VCC_H
    #error You need to install Arduino_VCC version 1.x (URL)
    #error How to install libraries in ArduinoIDE: (URL)
    #endif
    
    • Provide a "Notice" box or something like that above the embedded sketch on the website: (quickly hacked together):
      mysensors-external-lib-note.png

  • Mod

    @BearWithBeard said in Measuring battery voltage, which way is best?:

    This doesn't address backwards compatibility issues though

    Nor forward compatibility, as "#pragma once" is much more common these days than using an include guard



  • Hello all, may be I did not get the point of this thread, but a very similar code to measure the AVR CPU voltage is already part of the MySensors library: MyHwAVR.cpp#L289

    I use it in some of my PIR sensors and it works fine. Simply call hwCPUVoltage() to get it.
    This is from my code:

    void sendBatteryLevel()
    {
      // This calls the internal voltage measurement
      uint16_t voltage = hwCPUVoltage(); 
    
      // Li AAA Cell Voltage range: discharged - full 2.6V - 3.0V
      uint16_t batteryPcnt = map(voltage, 2600, 3000, 0, 100);
      batteryPcnt = constrain(batteryPcnt, 0, 100);
    
      // This MySensors function sends the "internal battery info" to the gateway
      sendBatteryLevel(batteryPcnt);
    }
    
    

    BR Immo



  • @virtualmkr Thanks - I did not know that - it is really helpful! 🙂

    The original purpose was that the 'build' section on 'battery power' was missing anything about the 'internal voltmeter' and only mentioned the external components method.



  • @skywatch Thank you for clarifying. And nice that you like my implementation 🙂

    I also find it very good and helpful for beginners to show the internal battery measurement method on the "Battery Power" page from MySensors. When I started with MySensors I followed the instructions for measuring via analog pin and 2 resistors. The more simple internal measurement I discovered way much later.

    BTW there are some more built in functions, e.g. for the current CPU frequency and the current free heap size. With the MYSController you can query these values from the individual nodes:

    2021-02-19 21_40_28-MYSController 1.0.0beta (build 3316).png

    You need only to add the #define for this functionality in your Node sketch:

    // Enable support for I_DEBUG messages.
    #define MY_SPECIAL_DEBUG
    


  • @virtualmkr Thanks - this is really useful stuff which is 'hidden away' and should really be seen by all coming to mysensors for the first time. I hope @mfalkvidd will find a way to get this into the battery section.

    I modified your implementation a little to better suit my needs, as follows....

    void sendBatteryLevel()
    {
      // This calls the internal voltage measurement and converts to Volts.
       wait(250);                                        //Allow power lines to settle.
       float voltage = hwCPUVoltage()/1000; 
       wdt_reset();
       batteryPcnt = map(voltage, brown_out_voltage, BattMax, 0, 100);
      //batteryPcnt = constrain(batteryPcnt, 0, 100);
    
      // This MySensors function sends the "internal battery info" to the gateway
      if(batteryPcnt != oldBatteryPcnt){
      sendBatteryLevel(batteryPcnt);
      oldBatteryPcnt = batteryPcnt;
      }
    }
    

    I wanted it all in volts and not mV and also not send unless there is a change in % level to further reduce battery usage. For some reason the 'constrain' function gives a warning in minicore so I leave it out for now.

    The image you posted shows frequency as "cHz". I am not familiar with that term, do you know what it is?



  • @skywatch Thank you for the minicore tip. I was not aware of this project.
    Implementation of constrain() in minicore differs from constrain() implementation in the original Arduino core.
    So maybe it is a minicore issue. Or may be your batteryPcnt type is float?
    Neverless one should prevent battery percentage below 0% or above 100% because it makes no much sense.

    "cHz" is actually strange but it means 0.1 x MHz, so for my ESP8266 I get 1600 x 0.1 MHz = 160 MHz:

    2021-02-20 12_32_10-MYSController 1.0.0beta (build 3316).png

    This way the frequency value fits well into uint16_t type.



  • @virtualmkr Thanks for the information, very interesting.

    My batteryPcnt is an int. The voltage is defined as a float but as I understand it any math between a float and an int will always result in an int, expecially if the variable it is being stored in is an int.

    cHz! Well I learn something new, so that is good! 😉

    As for minicore, it does get a mention in the bootloader page on this site and I like it as it is easy to use and I don't need to keep going to the command line or avrdudess all the time, it all works within arduino ide. As a big plus it was upgraded to version 2.1.0 today and the constrain issue has been fixed!


  • Mod

    My pull request has now been merged to the MySensors development branch. I have updated the battery page to show the example sketch for internal measurement. Note that the internal measurement method does not work on all supported mcus (not esp8266 for example) but I don't think it matter much since the battery page recommends a Pro Mini which works.

    Special thanks to @hek for tracking down a tricky display problem with the sketch inclusion, and to @Yveaux, @user2684 and @tekka for feedback on the pull request.



  • @mfalkvidd Good News! 🙂

    But I am curious where the "+ 0.5" vomes from in this line.....

    int batteryPcnt = batteryMillivolts / FULL_BATTERY / 1000.0 * 100 + 0.5;
    

    ???



  • @skywatch Rounding up to the nearest int ?


  • Mod

    @skywatch as @zboblamont said, it makes sure we have ”proper” rounding. In C, floating point numbers are always rounded down Ehrn converted to an integer. So 42.8 becomes 42. By adding 0.5, we get the rounding expected by most humans in most cases.

    To read about different rounding methods, see https://en.wikipedia.org/wiki/Rounding#Rounding_to_the_nearest_integer

    My personal favorite is called ”banker’s rounding” but I did not use it in this sketch.



  • @zboblamont & @mfalkvidd - Thank you for that. It never occured to me that rounding might need some help. But now it makes logical sense.

    @mfalkvidd I guess if you used 'bankers rounding' you would always end up with 0.


Log in to reply
 

Suggested Topics

  • 4
  • 3
  • 9
  • 274
  • 933
  • 2

0
Online

11.2k
Users

11.1k
Topics

112.5k
Posts