Thanks Ralph. I've used your circuit form video #123 to control power-up/power-down and it works perfectly. My arduino powers up (activated by a tilt-switch), sends a message via an NRF24 radio module, then powers down. Now I've added the voltage reading to the transmitted message and can generate a low-battery alert at the receiving end. All working wonderfully well (so far). Massive respect and appreciation!
Wow, you added that new feature very quickly, Dirk! I'm very glad you got things all working so well, sounds fab. I've added the battery warning to the Benny cupboard alarm sketch too, works very well. Thanks for posting, great to hear from you.
@@RalphBacon The 'secret volt-meter' code snippet you pointed me to last week made it a snap. I've decided to go with Ni-Mh AAs for my power source because it's what I had on hand. The power-up/transmit cycle is so quick that the shelf-life of the batteries may be the main factor in how long the batteries will last. I find peace of mind in the knowledge that somewhere across the Atlantic, the "Best Cat Ever' lives without fear of being locked away in the linen closet. :)
Not yet he doesn't (and it's us that are fearful not him, he couldn't care less until he wants to leave that closet!). I'm waiting for the PCBs, on their way to me now. Then he will be safe. We hope. Update video, no doubt, some time in the future.
Thanks for another very useful tutorial, Ralph! I really love that you make these types of down-to-earth Arduino videos that us common makers/students can learn from and apply it directly in our projects. Please keep up the great work!
Hey there Ralph, I can't thank you enough for this video. You cleared up so many uncertainties with this one. You even managed to clear up for me why precision is lost when using floats (it may be obvious to many, but I'm new to this). A huge "Thank You" !!!!!!!!!
I'm glad you liked the video George! Nothing is obvious until you know it, then it is _blindingly_ obvious! It's called knowledge and experience, which is what I hope my channel imparts! Thanks for posting.
Commercially you either wouldn't use the internal reference at all, if you need that accuracy without calibration, or you write your program in a way that you get into some kind of calibration mode (e. g. by holding a certain pin low), in which you apply an exactly known voltage to the ADC and the AVR can deduce from that what the internal reference voltage is and store the calibration value in EEPROM. No need to measure anything externally. Be aware that the internal reference draws power whenever it is on. You might want to disable it when it's not needed. Throw away the first conversion after activating the internal reference. The issue with floats isn't precision. It's the number significant digits that counts, doesn't matter if it's int or floats. The issue is that they are pure software on an atmega (as is pretty much everything that's not an 8-bit integer; even those 16-bit ints are "software"), which means everything you do with them is awfully slow. Same with divisions (for integers). It's a software iteration. If you divide by a fixed value (known at compile time), you are much better off multiplying (the AVR has hardware for that) by a factor and then divide by a power of two (because that's a bit shift, which is fast). For example a fixed divide by 10 could be done as a multiply by 102 and divide by 1024. Much faster, same result (as long as the x100 value still fits into the datatype, which in this case it easily does since it's long aka. 32bit int). Floats should be reserved for the last step like an output on screen, not for calculating. There's really no point in dealing with floats inside the AVR. Start thinking in mV for example and your need for floats is gone. Just using a single float btw. also adds quite substantially to the hex-file size, because the library for it has to be included. Which means that the battery voltage library that returns the float will add a lot more to the sketch size than the few lines it contains. Adding the 0.5 in the float version isn't correct. It is using floats. A "float" has 6 to 7 digits of precision, the ADC value barely 4. Floats conserve significant digits (that's the point of them compared to integers.), there is no truncation in this case. The long line for ADMUX is also just an 8 bit value (as are all registers in an atmega).
If your (commercial) brief was to use the INTERNAL voltage reference, because it saves 0.01c on the total price (yes, that's how commercial thinking goes) you would _have_ to devise a way of storing the chip's actual AREF value in EEPROM as part of the (pre-) assembly process. It can be done by, boy, would it slow the process down. It probably would cost more than any saving so maybe the accurate EXTERNAL reference would be the way to go after all! Yes, your thinking on floats is very sound. I might recompile the sketch and see what actual difference the float usage makes in program size. If it is significant then it would be well worth avoiding if at all possible. OK: With just an INT - Sketch uses 1600 bytes (5%) of program storage space With just a float - Sketch uses 2442 bytes (7%) of program storage space Wow! *842* bytes just for a single float. I'd call that significant. The difference between squeezing a program in or not. Good that you reminded us all that things don't come for free in the computing world.
Thanks, Gene, and this might be on a breadboard but I've included it into the previous project (Benny's cupboard Alarm) already and it works like a dream. Thanks for posting, good to hear from you.
Hi Ralph. I really appreciate your detailed explanations. I have a project where I monitor a Nano's vin input voltage across a resistor network and into an analogue port. Small bit of code to monitor when analogue input drops below a set point that relates to low battery voltage. Code then turns off the FET holding the battery power on to vin. Yes, this was using your excellent deep sleep process from a couple of months ago. I'm learning so much from your videos. Long may they continue. All the best.
It's amazing what you guys (including you, Paul) are doing with all these video ideas! And I'm very happy that it's getting your projects off the ground. Hey, maybe I could use that a byline for my channel. Heh heh! Seriously, it's great. Thanks so much for posting, nice to hear from you.
I have used a voltage reference ic on the aref pin, a 2.048V or 4.096V can be used, you just specify to use it. The internal reference can vary a bit in its stability, if you don’t care about accuracy too much then the internal is fine.
Yes, you can. The AREF is only used in reference to the analog pins. A higher voltage than AREF will get you the full 1023. Just make sure it's not higher than 5v, otherwise you need a resistor voltage divider on the analog pin you're connecting it to.
Another great, interesting and useful video. I always thought one of the reasons people complained about floats in microcontrollers was do to them being relatively slow at floating point math. Even with fixed point math, you'll end up with rounding but I guess it is more predictable as you determine the number of decimal places based on your multiplier. Your videos always leave me with something to think about. As for testing the bandgap ref, I imagine that with a bit of time you could set up a rig to power the atmel MCU, test AREF at several voltages and write those values to EEPROM in a way that some generic firmware could later retrieve. Still somewhat labor intensive as you have to swap out the chips for each test, but I'm sure someone much smarter than me in such matters could minimize the annoyance with a 'robot' of some sort.
The float question I've "answered" in a previous comment from Peter Camilleri. As for the production run, I've been thinking long and hard about this and have the solution. You can get bare chips with code preloaded from the manufacturer, if your run is long enough. The chips with preloaded code are then put through a simple jig that reads the AREF (eg via another, pre-calibrated Arduino) and that is entered (automatically) via the RX (serial) pin to be stored in EEPROM. Then the final sketch is loaded and sent off to the build process. Sounds more complicated than it would be in Real Life. Let's face it, this must be a common requirement for all sorts of things so I guess they have cracked that nut long ago!
good stuff Ralph , you can now read the ATMega328P internal temperature sensor and go around in circles chasing the ref voltage then the temperature calibration then back to the ref..... ;-)
Heh heh! Thankfully, for _this_ project the temperature calibration is 'good enough' and I'll accept the tiny deviation in cold / hot weather. But, for a more serious application, it could be problematic.
Been going through some of your earlier videos and lots of good info to be found--so thank you! Also, great info on the 'shipping-insurance' and tariff-protection' caveats---which I think are worthwhile as I've had bad experiences on China-eBay orders in the past. Believe it or not, never used Bangood or AliExpress. Just Amazon and Tayda Electronics! Thanks for all you do and really enjoy 'rummaging' around in your great repository Ralph... 😊
Glad you like them! It's definitely worth checking out the two "big" Chinese warehouses. Banggood doesn't really sell many components as such, but does sell modules and part completed items that we can build on. AliExpress sells right down to the individual component level (albeit in lots of 10+), great for stocking up on ICs, resistors, capacitors etc.
Yes, the spec sheet mentions this but in my tests it made no difference (maybe because I was not actually doing an _anlogRead_ I was doing it via the registers).
Thank you. Connect directly to an analogue pin, ONLY with max 5 volts. Anything more needs a voltage divider to bring the voltage down to with the totllerences of Arduino. Again, thank you
Re: Customs tariff. I ordered some custom boards from a Chinese supplier, total incl. shipping was about £40. Got an e-mail from the carrier saying I had to pay an extra £20 or the boards wouldn't clear customs! (I payed, because I could pass the cost on to my customer.) Often wonder if I was had.
Oh wow! I don't think you were "had", but if the order is over about £15 then customs (and perhaps tax) must be paid, hence I keep my orders low. I had DHL say I had to pay some tax (quite small) before they would pick it up from a PCB manufacturer. I had no option but to pay the few pounds, I guess I was just over the limit. AFter Brexit it will only get worse, I suspect.
Regarding the BangGood shipping insurance problem and orders not received. If the payment was via a PayPal account or Credit Card using PayPal, it may be possible to open a dispute via PayPal regarding a refund. If you paid direct via credit card and the value is over £100, you may be able to claim the money back with a section 75 claim.
Yes, indeed, Chris, PayPal might assist; I'm not sure what the rules are with PayPal for getting your money back (I've got it back not once but twice from rogue sellers, not Banggood). And your credit card is always a good bet if you're ordering over £100 of goods. Good info, thanks for posting.
@@RalphBacon I'd be careful with the term goods regarding section 75. I'm fairly sure that section 75 covers an individual item costing between £100 and £30000, not a selection of goods that total over £100.
Ralph S Bacon, Chris G is correct; Section 75 only applies for a single item that costs more than £100, and not for a combination of items totalling more than £100. However, card issuers should apply a chargeback (i.e. refund you) for disputes on lower-value goods. I have never had a chargeback declined. Chargeback rules are not law, but are in issuers’ T&Cs as part of the credit card industry ‘code’. On the whole, if you are based in the UK, ‘transit insurance’ is a money-making scheme for the retailer. Also, Section 75 does apply to orders from overseas that are being delivered to the UK. I have fact-checked using a couple of sources, including ‘Which’. Thank you for your videos.
I am trying to find the right words to honor your great work -well we come to expect that from you :) Good comments at the end about the Banggood shipping insurance. The resolution and stability is certainly good enough for a battery indicator. I wonder if you might make a part 2 to show how to get the best resolution and stability and an Arduino?
Did I mention that I stand on the shoulders of giants, Flemming? It's true. Many others have given us (me) the information that gets me going. It's the nature of open software, and it's great that we all benefit. But thank you, it's most appreciated. Regarding a Part 2, others have requested a battery monitor when the VCC is not the voltage we're monitoring (eg via a buck boost) so I will endeavour to include it in that. Thanks for posting, good to hear from you.
Hi Ralph, I measured with my Current Ranger that you need "turn of" the "ADMUX" after use or the MCU will consume more power during deep sleep. It could be only the way my code is designed but by turning of (ADMUX =~) I lower the power consumption by 60uA.
Man I’ve been fighting with a project very very similar to this.. starting with the voltage display I can’t get a cell to read correctly, close as I e gotten it to read is 4.53 and should read a cell that is at 3.28 , using voltage divider , caps and other components.... after I get it displaying the correct voltage then I can move on to the other cool stuff I have planned.. I’m going crazy with it!!!
There have been several requests to read any old battery voltage so I've added it to my list of things. Stay tuned and calm, Heny! And increase your dose of Valium. (Or, if you have spare, send them to me, boy do I need them).
Thanks for another interesting video. You mention that the chip will run at lower voltages but with reduced clock speed. Could you do a quick video of how to set the clock speed or point to an existing video if you have already done one. All I know is that it involves setting some internal registers. Thanks for taking the time to produce these instructive pieces.
The stock 328p, with no crystal, comes fused for internal RC 8mhz/div8 -- 1mhz, so you can run at minimal voltage there. You can fuse it to run slower @128khz ... and even on a watch crystal. Be careful not to brick yourself, if you do not have a HVPP handy! forum.arduino.cc/index.php?topic=353982.0
Possibly, Gary, possibly. It could equally be that the PSU is not so/more accurate than my multimeter. Or just the measurement on AREF was not done as well as I could have done it. In this case, it's no biggie. For other projects I'd investigate a bit further.
hi Ralph, great content, something new and original each chapter 👌. I should consider buying that freezer spray you showed at 20:20 to remove a stubborn wart from my finger but its quite expensive 😃😂👀(>40GBP)
OMG, what is this, a medical forum now?!!!? I must say I do not condone the use of freezer spray on anything other than electronic components. On your own head be it if you use it for something else... Will it really remove a wart? Let me know if it works and I might have a go. I bought it here: cpc.farnell.com/pro-power-chemicals/ppc239/freezer-spray-hfo-400ml/dp/SA03495
@@RalphBacon , Undefined Lastname thanks for your time my friends, here I feel free to talk about all of my concerns and thoughts, cutting under my skin with a heated knife without any anesthesia sounds like a horror movie to me 😃. The story was that: at work while patrolling (I work as a guard at a few lobbies) I used to kick the parapets with my knuckles just to strengthen my bones. Unfortunately these 1" pipes are dirty and full with skin deseases, and later if you don't wash your hands with soap these microbes "drill" into your skin and later you find yourself asking an electronic online forum for solutions 😂🤣🤦♂️. BTW, here is an electronic USB device for this, I wonder what effect this needle has on the bulge 😜😁. www.aliexpress.com/item/32854287745.html?spm=a2g0o.productlist.0.0.57544480KSjYEK&algo_pvid=3b018f55-088d-4fc4-8342-fb12e2c4048d&algo_expid=3b018f55-088d-4fc4-8342-fb12e2c4048d-10&btsid=61a0cbcd-44e0-4a5e-92ac-cd02632f9c33&ws_ab_test=searchweb0_0,searchweb201602_8,searchweb201603_52
Good info about I always thought that if you used aref everything scaled to it so anything over ~1.1v would just read 1023. I guess I need to look at it again. I'm moving to esp32 mostly. I found a cheap one with lipo support and a small RGB LCD I think will be my new go-to. A bit more money but wifi, blue tooth, lipo support and a display for $6 is cheap enough to just throw at a priject.
It should be noted that these cheap boards with a LiPo connector tend to have lossy voltage regulators and power LED's which draw so much current it makes them badly suited for battery powered usage. Usually also the USB to serial converter chip draws in current even when not in use. In fact the same applies to pretty much all dev boards you can get with or without a battery connector/charging circuit. To get them to a reasonable sleep mode current consumption (microamp range) you'll need to desolder the wasteful components (or alternatively cut traces leading to them.
Ristomatti Airo this particular one pulls about. 0.3-0.4 ma in sleep mode with the display turned off as shown in a video here on RUclips. Good enough for me to run maybe a day two in a pack I have. It’s a TTGO T-display.
Nice! I didn't know they've started to focus on that. And surely if a day or two fits the needs of your project then even better. I'm usually thinking about wireless sensor nodes of which I'd hope to get several months of battery life for them to not become a nuisance. :)
You could consider powering the display (and other peripherals) from a GPIO pin of the µC (possibly via a suitable transistor if the power is > 20mA). That way, the device wakes up, powers up the devices and does its stuff. Whilst asleep the peripherals consume zero power. That's the way I do it in my recent Benny PIR project. In sleep mode (Arduino ATMega328P) it's 0.2µA in sleep mode, 10µA including the PIR (which has to be on all the time, so it can wake up the µC).
Hi Ralph, well if I was going to just measure the battery voltage and just wanted to flag a low battery voltage I might use the internal voltage reference. but if the voltage was from critical source then I would use an external voltage reference with a very tight temperature characteristics, along with high stability resistors used in any protentional dividers etc. there also might be some opamp circuits to level shift the signal to give the best accuracy. With a 10bit ADC you get 0.001072421875V/bit or with a bit of rounding 1.1mV / bit with the internal 1.1V ref. I wonder what the chip uses to drop the supply voltage down to less than 1.1V internally, think I might have to go and read the datasheet some time soon. great video as always as it gets the grey cell's under my grey hair working as I run down to being a house husband. :)
Yes, I did mention that if you needed more accurate (eg for a multimeter) you would need a better reference voltage, but for this type of simple project it works (very) well. They don't actually 'drop' the voltage, there is an industry standard circuit known as a Brokaw bandgap reference voltage circuit, invented by David Hilbiber, Bob Widlar, Paul Brokaw and others in 1964. Glad you like the video and it got your grey cells a good workout!
@@RalphBacon Hi Ralph, It took a while but I’ve got it straight in the old grey cells now. Two constants and one unknown. Constant #1 1.095V True BandGap voltage (TBGV) measured externally with higher accuracy Constant #2 1024 number of bits in ADC (2^10) Unknown #3 Supply voltage and hence ADC reference voltage. Step one; Set mux to bandgap, and ADC reference to AVcc (which should be at supply voltage) Step two; read ADC. This will give the bandgap voltage as a number of bits, where each bit has a value based on the supply voltage / number of ADC bits. Step three; divide TBGV by ADC reading to give the Voltage per bit, by dividing the true bandgap voltage by this number gives us the true voltage of each bit. Step four; multiply the true voltage of each bit by number of bits this will give us the ADC Reference voltage and hence supply voltage. QED (quod erat demonstrandum (which was to be demonstrated)) Thanks again for getting me thinking, thought I’d write it down in case any others wanted to know the process behind the numbers.
Hi Ralph, Very clear and useful video - as always. I haven't looked at the code (yet) but what would be useful is the action the circuit takes when the voltage drops below a user-settable threshold - switch a relay, power Mosfet, shut down a device etc. The circuit also lends itself for use as a stand-alone module for all other battery-powered projects. Of particular interest for me is with the UPS-powered Raspberry Pi as in your previous videos (and the auto powerup module using an ATTiny)
The action you take on a low battery is just a simple if statement Dave. if (batteryValue < requiredValue) { do something here } I'll show you how I've implemented this in my Benny airing cupboard project from last week. Basically, as it comes out of Deep Sleep it checks the battery and beeps very quickly a few times if it's too low. works like a dream. Keep tuned.
The answer to how you would handle the device-to-device variance in commercial products of the analog reference voltage is that you would measure it. Instead of manually measuring Vref, and encoding that value into the sketch, you measure it in-circuit and use that value in the calculations. The only consequence in doing this is whether there is a channel on the ADC attached to Vref or whether you have to use an ADC channel externally to measure pin 21. I don't know if the ADC loads the source significantly during conversion which, if it does, would justify use of that decoupling capacitor.
So you would have to have a sketch to load the EEPROM with the corrected value first as part of the manufacture (eg bootloader/sketch load). Yes, that could work.
lol at banggood, UK law applies if your buying in the UK and the responsibility to supply is with them, gets lost in post its legally their loss, contact you bank/card company, you will get your money back. well i have in the past and i'm no one special so.....
The key phrase is _if you're buying in the UK_ which I presume Banggood would not be considered a UK-based company. Or did you mean the purchaser being in the UK? Mostly I use PayPal for overseas purchases, will they also protect me?
@@RalphBacon the point of sale dictates the law, so if i am sat at home in the uk on my pc, then uk law should apply, and for me in the past has been enough, ..but... that being said, the law hasnt fully caught up with ''not in person international sales'' as it could be argued that the point of sale is their server in HK etc or as you say, if you have paid with paypal, is it then the US, and as paypal paid them with your funds, did you ''make the sale'' or did paypal.... as to your question, paypal have never let me down re protection. also if your paypal is linked to credit card, and paypal do let you down, then you may have a 2nd chance with the CC company, banks no way near as much as a cc company so its worth having a cc just for the use of paypal...
This is HUGELY helpful for me as most of my projects now are LiIon powered, and I've been struggling with external voltage regulators and whatnot in order to read voltages from around 4 volts to 2.5~3. Will this code work on the ATTiny range, like ATTiny85?
It _can_ work on the Tiny85 but AREF uses PB0 pin so you might run of pins very quickly. More info in the datasheet and in this forum answer: electronics.stackexchange.com/questions/60237/attiny-default-aref (Look at the second post) I've not tried it although one day I will find time to do that!
Yup, just need the ADC multiplexer to be configured slightly differently - ADMUX = _BV(MUX3) | _BV(MUX2); instead of how it's configured for the ATmega328 - nothing else needs to change. In fact, if you have a look at this function snippet, it configures the registers different for several of the different microcontroller types... unfortunately that particular code writer didn't see fit to make it so the calibrated voltage was passed into the function so that a more accurate reading could be calculated. github.com/sweebee/Arduino-home-automation/blob/master/libraries/readVcc/readVcc.h
Hey Ralph, Many Thanks for wonderful guideline. But unable to compile on IDE even using your Zip folder as Library. Showing BatteryVoltageReader.h: No such file or directory .Kindly
Hi Ralph, Thanks for the awesome video... If you remember a while ago I was struggling getting the voltage of a lithium cell using an analog pin to report the voltage. I haven't found a way to do this accurately, as the reported voltage varies wildly. My circuit is a lithium cell with a boost converter to boost the current up to 5V, though I do take a wire directly from the battery to the analog pin. I've tried resistive dividers, capacitors and other ways to try and get it to report a correct value. I think it'd make a great video if you can help and try something out? Thanks :)
A similar method would work for you too but does require a simple voltage divider on the analog pin. Because you don't care about VCC (which would stay pretty constant thanks to the buck boost) you want to measure the (lower) battery voltage against the internal AREF voltage. I'll add this to my list, Jessica, stay tuned!
Hi Ralph, very nice video, you mentioned that you have got new PIR sensors (now consuming 10microAmps) could you please share the link, thank you kindly!
Sure, here's the link, just remember I can't guarantee what you will get sent, and these look identical to the ones I was using in my Home Alone project but use less current. Bizarre. www.banggood.com/5Pcs-Mini-IR-Infrared-Pyroelectric-PIR-Body-Motion-Human-Sensor-Detector-Module-p-1020426.html?p=FQ040729393382015118&
Thanks Ralph Another interesting video. I wonder if those bypass caps are needed when the power source is a (no noise/ripple) battery? Also a question is "Aref" and input or an output or both? Regards Greg
Yes you _do_ need the caps in all cases, Greg, to prevent noise entering/leaving the chip, thus improving stability. At least, according to the Data Sheet which is the equivalent of the manufacturer's Bible on the subject. And they have to be right next to the chip too, as you will see on a future PCB of mine. AREF is neither INPUT nor OUTPUT. Certainly, it reads the voltage present if you are using EXTERNAL as the reference, but if using INTERNAL you should not be connecting anything else to the pin; although you could switch between INTERNAL and EXTERNAL references if you used a resistor into the AREF (once again, the Data Sheet explains all). But you don't set it as either INPUT nor OUTPUT. Great question, thanks for posting.
That would explain, Nicholas, why the first time I did it (without the BlueTac) it continued to work but it caused me some worry that I _might_ have damaged the chip with all that liquid sloshing about. Good to know then, CO2 it is!
Hi Ralph, you make a good point about chips behaving differently as I have a 3289-AU (QFP) running my sketch that simply has two switches, one puts it to deep sleep and one wakes it up and lights a LED and it is using a "poundland" AA battery, Zinc Chloride (1.5V) quite happily and has been for days, haven't got the deep sleep numbers yet (still waiting for parts ) but 1.5V is ok by me! Im lighting the LED from a CR2032 driven by the the 328p via a transistor (2N2222A)...again tiny currents I'm definitely into "low and slow" at the moment but my alternative "Nano" arrived today so gonna see what that can do..I wonder what MiniCore will make of it?
I'm wondering how you can possibly run an ATMega328P on 1.5V, Andy? The minimum, official voltage is 1.8V and whilst I have mine running OK at 1.6V it will stop at anything lower - and refuses to restart until I up the voltage to beyond 1.6V. What magic hast thou in they wizard's cape?
@@RalphBacon no idea! it is the QFP version but I had to measure it to believe it I will take a photo see if you can work it out! I swear it's a kodak AA from the pound shop ( 10 of them!) I'll show you the sketch as well
Great video - I don't do a lot of analog, but I can see that this is really neat. Any idea if there is something like this for the STM32 - I don't even see an AREF pin on it - have not looked at the chip pinout - just the blue pill board layout.
@@ristomatti Thanks - I will have to try that out. I have a blue pill board that I use to drive SK6812 LED strings with about 200 leds. I use an external 5V supply to drive the LEDs, but if I forget to plug it in, it pulls the power off the processor board causing the voltage on the board to drop almost a volt. I would like to detect this and turn off the leds if the external voltage is not applied.
@@RalphBacon The power is not connected to the STM32 directly. The blue pill is a daughter board on a board I built that is normally driven by the same 5V 15A supply that drives the LEDs. We inject power every 50 LEDs, but the first 50 get there power from the board. Sometime, when I am just doing software development, I will plug in a 50 led string and just power it off the USB. This actually works fine. But, if the unit was installed in a pinball machine, it might be trying to drive 250 led, and I know that will not work (ask me how I know!). But, if I could sense the voltage, I could turn on the LEDs one at a time at startup and if the voltage started dropping, I could start flashing some kind of error signal - maybe 10 leds flashing red or something like that to indicate that something is wrong.
hi Ralph, thanks for helping everybody learning good staff. one question.... in case of a battery powered project with an Arduino Pro mini 3.3v, the battery is attached to the RAW pin, not to VCC.... (battery full if 4.2 V in case of a Lipo). this will compare the RAW voltage to the internal 1.1V? Marco
If you're supplying the voltage into the RAW pin, that is then being converted to +3.3V by the onboard voltage regulator (a MIC5205 or similar). This means you *cannot* monitor your battery voltage using this method at all, because VCC (the reference) will _always_ report the full 3v3. What you need to do is monitor the actual battery voltage directly as you indicate (the RAW voltage) but not like this. Luckily for you, my video in two weeks covers this topic completely so keep tuned.
Ralph S Bacon hi Ralph, Yes that’s my point.... so in your example how do you power up your arduino with 3 volts? What I mean, in VCC pin you should plug in or 5V or 3.3V (in my case of pro mini). If you use a battery you should plug it into RAW, isn’t it? At the moment I use a trimmer 10K for getting out a 1.1 V from the slider when my lipo is fully charge at 4.2 Volts, the slider gets into A0. So when battery drops to 3.7 I lid a Led to remind me to charge. So I still don’t understand why check the VCC Vs internal reference while the VCC should be fix and regulated. Unless... is the arduino uno able to work with VCC 3.7-3.6?
Let's clarify our terminology and what we are talking about here. The Arduino (actually let's be specific here, it's a bare ATMEGA328P chip) will run from 1.8v to 5.5v when powered directly into the VCC pins (two of them) on the chip. That's the way most battery-powered projects are powered up. You will have to run off the 8MHz internal oscillator once you drop below about 4v as you cannot run at 16MHz at such a low voltage. If you are using an Arduino UNO _board_ with a Vin pin, your 6v - 12v power goes through an inefficient voltage regulator to give 5v. You would not put a LIPO through that pin, the Arduino will run directly from the +5v pin from 4.2v all the way down to the 3.0 LIPO cut-off voltage (albeit not necessarily at 16MHz as mentioned above). A LIPO has a fully-charged voltage of 4.2 that quickly drops to its nominal 3.7v where it very slowly drifts down to 3.4 before falling off a cliff edge down to 3.0 when the battery protection circuitry will kick in at 3.0v. The 328P chip provides a nominal 1.1v reference (which you can measure at the AREF pin) and it will use this to measure VCC. If you want to be precise you need to measure the actual voltage presented at AREF and plug that value into the formula I showed. If your battery is going through a DC-DC step up (boost) module to get 5v out of a 3.4v LIPO then you need to measure the battery directly, which is exactly the topic of my video in two weeks' time. Make more sense now? Watch the next but on video!
Does the Tariff Insurance cover quite what you expecting?! When I read it, firstly it doesn't seem to cover service charges like the £8 ish (+vat?) Royal Mail add to handle the payment and secondly, does it cover vat? Between £15 and £100 pounds isn't there technically only vat charged on the package and not import duty? And since vat isn't a tariff is it covered? So I can't see it being worthwhile except on particularly large orders
Ha! I knew somebody would query this, as my suspicions were aroused too. I think we can safely assume that the answer to your question is "probably not". If the import duty was £10 they should/would cover that. But that plus a handling charge of £8 plus VAT on the lot would easily make a hole in your pocket. As you say, probably worth doing on larger orders only. It's the one thing that stopped me buying more (expensive) stuff from China.Well, that and the lack of any kind of guarantee, of course. Most of the tools I have in my workshop have been UK-sourced. I want some kind of guarantee on these sort of items. And no unexpected C&E bill. DHL demanded a relatively small amount of $4 from me for the latest PCBWay shipment, before they would even pick it up. It must have just snuck into the higher value category. I dread to think what the $40 PCB batch I'm next about to order will do to my pocket! Caveat emptor!
Couldn't you just use a voltage divider across vcc and ground fed in to an analog port and compared to the internal 1.1 reference? Given the fact that that isn't temperature stable and that you don't really care if the battery is completely or very nearly completely flat before you change it, surely this is good enough. Or is it that the voltage divider idea consumes current, which defeats the object of this particular exercise, which is to run for as long as you can? By the way, I got annoyed with Banggood when an empty envelope arrived that was supposed to contain two LEDs. Banggood refused to accept responsibility without me getting written confirmation from the post office of the weight of the package as it travelled through the system, presumably to identify where in the world the two Leds disappeared. As if the weight would be measurably different with and without the leds. Two leds to them - 1p. Cost or arguing for days, who knows. Certainly more than 1p. Stupid.
Funnily enough, Jessica has requested a method to read what is effectively an _external_ voltage (the input to a buck boost) so I've added this to my list, Andy, and we can explore the options in a future video!
You're using the sketch with the library, then, John? BVR (which stands for Battery Voltage Reader, in my sketch) relies on the library being available. Copy the library files (.cpp and .h) from my GitHub into a folder called BatteryVoltageReader in your 'libraries' folder which is inside your Arduino sketches folder (sounds a bit convoluted but really isn't). If you are still stuck and can't move on, let me know I'll give you a screenshot.
@@RalphBacon Thanks Ralph I do understand that I did get your other version without library first time. I will try the lib. version as well. Thanks for the great videos and your speedy response john.
Hi Ralph. Having trouble with the battery monitoring. The sketch works fine it's my hardware seems to be the problem I have a diymore 18650 battery shield much like the one in your video, using this to power arduino uno. I then connect the Txd line from the arduino to the Rxd line on my usb to serial connector to monitor the voltage. I get nothing but when I ground the gnd line from the usb/serial it works ?. but I get a fairly constant 4.99 volts. I think I may be monitoring the usb port voltage. I am not sure what is going on, as I said complete newbie just following the pictures without fully understanding. Sorry for the long note if you can shed any light on this that would be great but I understand you may not have time. Regards John
your videos always turn my head gears. do you how use atmega 328 p without bootloader but code can still be uploaded by using the arduino maybe using it as isp.
Get an usbasp clone (2€ on ebay) or program another Arduino as ISP programmer, connect those to the ISP pins of the AVR you want to program and then just selected the programmer in the Arduino IDE.
@@superdau sorry i am still confused so if have a atmeage329p without bootloader so i can just program it by using arduino as an isp right? select programmer in gui as arduino isp. program arduino as isp with the built in sketch. connect wire of spi communication open code in GUI and upload it "upload using programmer"
@@inferno6012 I haven't used the Arduino IDE in ages (using atom/VSC with platformIO). But yes, I remember there is a Arduino-ISP sketch in the examples. You write that to an Arduino board (which has a boot loader) the "normal" way. You then connect it to another Arduino (or even almost bare AVR chip) using the ISP pins. Somewhere there's a list how the ISP pins of the two Arduinos have to be connected. And yes you then select the "ArduinoISP" as programmer and upload using "Upload using programmer". It's nothing special, there are enough explanatons of this available on the internet, if you need to know more.
Hey Ralph, could you please make a video on how to measure current and voltage used by an Arduino UNO setup? Please do a review on the GY-INA219 High Precision I2C Digital Current Sensor Module. I am looking for a way to accurately measure power consumption in my Arduino robot. Thanks again for your help!
@@RalphBacon im 50 plus i've always love electronics from a kid. only just been getting into the uno things wow. what an amazing bit of kit. i remember trying to make various thing over the passed using just 74 and 4000 logic gates and end up with loads of chips and wires running all over the place. then this thing pop up in my radar half the things i made over the pass could have just been programmed into this things i know thats there propose in the first place but when you see it in action it just blows my mind lol.. is there any books that you would recommend at all?
Seriously though, integers are far worse. 1.0/3.0 may be 0.333333 with floats but 1/3 is 0 with integers! I think the real reason floats take so much shade is because floating point libraries for 8 bit micros are both both bulky and very slow. Embedded programmers take great pride in NOT needing to use them.
"floating point libraries for 8 bit micros" Floating points are bad for more reasons than that. A properly programmed algorithm using integers will keep the full precision possible with the processor. With floats the rounding quickly becomes an issue for anything other than trivial calculations. Floats are very rarely the right choice in an embedded program.
@Peter If you were doing calculations (or holding values) like that 1/3, you would first multiply the value by 10, 100, 1000... whatever accuracy you need. Then 1/3 becomes 1000/3 which is 333 (integer) and you do all the maths on that figure with other numbers that are also 1000 times bigger. As a *final* step, divide by 1000 into a float (if you wish) to get the final value. Which is what we do in this sketch - hold the "float" of AREF as a value 1000 times bigger to get the required accuracy. I hope this makes sense! Regarding floating point libraries being big (and possibly slow) that is totally correct. But if you _need_ a float as the end result then you will need that library for the final step.
@@RalphBacon My point here is that the rounding has not gone away. Yes you can scale all your calculations but there is still loss of accuracy. 1000/3 is not 333 it's 333.3333... And now we add the risk of integer overflow with insane results when it occurs. If memory serves, the European Space Agency found this out the hard (and costly, and dangerous) way when the flight control software of an Ariane 5 rocket failed with an integer overflow. Floats balance dynamic range while keeping maximum accuracy. They are just resource hogs which is a strong reason to avoid them if you can. An alternative is to implement a rational data type, which I have done on numerous occasions, but that is beyond the scope of this discussion.
Agreed, rounding never goes away, it just gets pushed to the point where it is acceptable (and predictable). Rational data types have been around (and supported) for years, even in C++, but something tells me the Arduino flavour doesn't do this (I may be wrong, I never checked). Not as good as a rational (a non-rounding type) but we can also use long longs (64-bits) so multiplying up should not be a problem even there, and rounding becomes far less of an issue. And no float library in sight! There's an interesting article here: softsolder.com/2017/05/26/arduino-vs-significant-figures-useful-64-bit-fixed-point/
Hi Ralph, thanks for the great video. How can I find out what other Atmel chips can do this measurement? In particular I'm very interested to see if the ATTiny841 can also do this. Thanks again.
I haven't had any experience of the Tiny841 (nor its smaller brother the Tiny441) and having looked at the spec sheet I'm wondering, Graham, what it is about that chip that appeals so much (compared to, say, the Mega328P)?
The ATTiny 841 is low power, can be programmed in the Arduino IDE (with the appropriate library), has hardware I2C, and 2 x hardware serial, which is of particular interest for me as I want to daisy chain several together. It appears to be a bit of an ATTiny85 on steroids (which I believe only does software serial and I2C) After watching your video I did a bit of further research and found the following document which seems to describe the VCC measurement technique: ww1.microchip.com/downloads/en/AppNotes/00002447A.pdf At the end of the doc it lists all the Atmel chips that can do this measurement, and the ATTiny841 can do it. Happy days. just need to understand the registers..... :)
Another great video Ralph :) You (and others) might also be interested in the work of rlogiacco, as he has put together two very nice libraries about battery sensing... github.com/rlogiacco/VoltageReference does the bandgap voltage reading, and has the added benefits of passing in a calibration voltage when starting the library, or even having it read back from EEPROM if you've saved it there. There is then the BatterySense project, centered around making it easier to make a voltage-based decision about whether the battery is flat or not... in a percentage form. I haven't used them myself, but instead did something similar to Nick's function. I am working on a RF sensor project, and when I commission each node I shove the 1V1 value into EEPROM so the code can read it back without having to put different code on each node. I'll probably incorporate the VoltageReference library instead in future as it's less code to maintain ;)
I was using about 300°C, Jeff, but it was with my little Antex C18W - these days I use 350°C using my lovely ATTEN ST-100W and it works a _lot_ better!
No, not at all. I'm not saying you should dawdle but as long as you have enough flux on the pins, apply the iron, let the solder melt and get sucked into the pin and move on to the next pin. Each pin probably has less than 1 second of heat applied. Let it cool for a few seconds before correcting any bridges or solder wicking the bridges away. Seems to work for me (admittedly, much to my surprise). Practice using the SMD practice boards from Banggood which contain some SMD chips and taught me how NOT to do it!
I have some _real_ Ultrafire AA batteries though, good ones they are too, although poor choice of name, agreed. The charger does say not to use unattended. Hmm...
Ralph S Bacon While we’re correcting spelling and grammar then @ 8:10, line 7 “Force interal” correct “Force internal”. Obviously it doesn’t matter in commenting but it will expressions. Yes I’m another pedantic German that can’t let a typo pass without comment.
@MUDGEL the _interal_ is something quite different and advanced, actually. Far too advanced for this channel. I would say thanks for posting, but in this case... heh heh. But I'm off to see my non-pedantic Mutti and family in Stuttgart next week so I'll give you a wave. MfG bis demnaechst!
Ralph S Bacon Very poor German here. Emigrated to Australia aged 5 so didn’t ever have any formal schooling in the German language. We spoke a dialect when at home but I only once saw it in a written form in a local cookbook. I’m from Idar-Oberstein in Germany, en.wikipedia.org/wiki/Idar-Oberstein I understand “bis demnaechst” - till the next time or catch ya later mate..but what is “MfG”?
MfG stands for mit freundlichen Gruessen, in other words, Best Regards or something similar. My daughter and her partner are visiting 'straya at this very moment, somewhere in the vicinity of Brisbane. She's having a great time. And has no trouble understanding the locals either. All those hours watching _Home & Away_ and _Neighbours_ have really paid off, ha ha!
Thanks Ralph. I've used your circuit form video #123 to control power-up/power-down and it works perfectly. My arduino powers up (activated by a tilt-switch), sends a message via an NRF24 radio module, then powers down. Now I've added the voltage reading to the transmitted message and can generate a low-battery alert at the receiving end. All working wonderfully well (so far).
Massive respect and appreciation!
Wow, you added that new feature very quickly, Dirk! I'm very glad you got things all working so well, sounds fab. I've added the battery warning to the Benny cupboard alarm sketch too, works very well. Thanks for posting, great to hear from you.
@@RalphBacon The 'secret volt-meter' code snippet you pointed me to last week made it a snap. I've decided to go with Ni-Mh AAs for my power source because it's what I had on hand. The power-up/transmit cycle is so quick that the shelf-life of the batteries may be the main factor in how long the batteries will last.
I find peace of mind in the knowledge that somewhere across the Atlantic, the "Best Cat Ever' lives without fear of being locked away in the linen closet. :)
Not yet he doesn't (and it's us that are fearful not him, he couldn't care less until he wants to leave that closet!). I'm waiting for the PCBs, on their way to me now. Then he will be safe. We hope. Update video, no doubt, some time in the future.
Thanks for another very useful tutorial, Ralph! I really love that you make these types of down-to-earth Arduino videos that us common makers/students can learn from and apply it directly in our projects. Please keep up the great work!
Kind words, indeed, Shakell, thanks for that and for posting!
Hey there Ralph, I can't thank you enough for this video. You cleared up so many uncertainties with this one. You even managed to clear up for me why precision is lost when using floats (it may be obvious to many, but I'm new to this). A huge "Thank You" !!!!!!!!!
I'm glad you liked the video George! Nothing is obvious until you know it, then it is _blindingly_ obvious! It's called knowledge and experience, which is what I hope my channel imparts! Thanks for posting.
MY HEARTY THANKS FOR YOUR VIDEO!!! INFO FROM YOUR VIDEO HAS FINALLY STOPPED ME
BEATING MY SKULL... AGAIN THANKS !!!
Glad I could help!
Commercially you either wouldn't use the internal reference at all, if you need that accuracy without calibration, or you write your program in a way that you get into some kind of calibration mode (e. g. by holding a certain pin low), in which you apply an exactly known voltage to the ADC and the AVR can deduce from that what the internal reference voltage is and store the calibration value in EEPROM. No need to measure anything externally.
Be aware that the internal reference draws power whenever it is on. You might want to disable it when it's not needed. Throw away the first conversion after activating the internal reference.
The issue with floats isn't precision. It's the number significant digits that counts, doesn't matter if it's int or floats. The issue is that they are pure software on an atmega (as is pretty much everything that's not an 8-bit integer; even those 16-bit ints are "software"), which means everything you do with them is awfully slow.
Same with divisions (for integers). It's a software iteration. If you divide by a fixed value (known at compile time), you are much better off multiplying (the AVR has hardware for that) by a factor and then divide by a power of two (because that's a bit shift, which is fast). For example a fixed divide by 10 could be done as a multiply by 102 and divide by 1024. Much faster, same result (as long as the x100 value still fits into the datatype, which in this case it easily does since it's long aka. 32bit int).
Floats should be reserved for the last step like an output on screen, not for calculating. There's really no point in dealing with floats inside the AVR. Start thinking in mV for example and your need for floats is gone.
Just using a single float btw. also adds quite substantially to the hex-file size, because the library for it has to be included. Which means that the battery voltage library that returns the float will add a lot more to the sketch size than the few lines it contains. Adding the 0.5 in the float version isn't correct. It is using floats. A "float" has 6 to 7 digits of precision, the ADC value barely 4. Floats conserve significant digits (that's the point of them compared to integers.), there is no truncation in this case.
The long line for ADMUX is also just an 8 bit value (as are all registers in an atmega).
If your (commercial) brief was to use the INTERNAL voltage reference, because it saves 0.01c on the total price (yes, that's how commercial thinking goes) you would _have_ to devise a way of storing the chip's actual AREF value in EEPROM as part of the (pre-) assembly process. It can be done by, boy, would it slow the process down. It probably would cost more than any saving so maybe the accurate EXTERNAL reference would be the way to go after all!
Yes, your thinking on floats is very sound. I might recompile the sketch and see what actual difference the float usage makes in program size. If it is significant then it would be well worth avoiding if at all possible.
OK: With just an INT - Sketch uses 1600 bytes (5%) of program storage space
With just a float - Sketch uses 2442 bytes (7%) of program storage space
Wow! *842* bytes just for a single float. I'd call that significant. The difference between squeezing a program in or not. Good that you reminded us all that things don't come for free in the computing world.
I really appreciate how you break this down for some of us simple minded folks..lol...it makes battery projects more feasible..
Thanks, Gene, and this might be on a breadboard but I've included it into the previous project (Benny's cupboard Alarm) already and it works like a dream. Thanks for posting, good to hear from you.
Hi Ralph. I really appreciate your detailed explanations. I have a project where I monitor a Nano's vin input voltage across a resistor network and into an analogue port. Small bit of code to monitor when analogue input drops below a set point that relates to low battery voltage. Code then turns off the FET holding the battery power on to vin. Yes, this was using your excellent deep sleep process from a couple of months ago. I'm learning so much from your videos. Long may they continue. All the best.
It's amazing what you guys (including you, Paul) are doing with all these video ideas! And I'm very happy that it's getting your projects off the ground. Hey, maybe I could use that a byline for my channel. Heh heh! Seriously, it's great. Thanks so much for posting, nice to hear from you.
I have used a voltage reference ic on the aref pin, a 2.048V or 4.096V can be used, you just specify to use it. The internal reference can vary a bit in its stability, if you don’t care about accuracy too much then the internal is fine.
Can you still use, say, a 2.048v reference, and power the chip with a higher voltage like 3 volts? I've often wondered about during my experiments.
Yes, you can. The AREF is only used in reference to the analog pins. A higher voltage than AREF will get you the full 1023. Just make sure it's not higher than 5v, otherwise you need a resistor voltage divider on the analog pin you're connecting it to.
Another great, interesting and useful video. I always thought one of the reasons people complained about floats in microcontrollers was do to them being relatively slow at floating point math. Even with fixed point math, you'll end up with rounding but I guess it is more predictable as you determine the number of decimal places based on your multiplier. Your videos always leave me with something to think about.
As for testing the bandgap ref, I imagine that with a bit of time you could set up a rig to power the atmel MCU, test AREF at several voltages and write those values to EEPROM in a way that some generic firmware could later retrieve. Still somewhat labor intensive as you have to swap out the chips for each test, but I'm sure someone much smarter than me in such matters could minimize the annoyance with a 'robot' of some sort.
The float question I've "answered" in a previous comment from Peter Camilleri. As for the production run, I've been thinking long and hard about this and have the solution.
You can get bare chips with code preloaded from the manufacturer, if your run is long enough. The chips with preloaded code are then put through a simple jig that reads the AREF (eg via another, pre-calibrated Arduino) and that is entered (automatically) via the RX (serial) pin to be stored in EEPROM. Then the final sketch is loaded and sent off to the build process. Sounds more complicated than it would be in Real Life. Let's face it, this must be a common requirement for all sorts of things so I guess they have cracked that nut long ago!
good stuff Ralph , you can now read the ATMega328P internal temperature sensor and go around in circles chasing the ref voltage then the temperature calibration then back to the ref..... ;-)
Heh heh! Thankfully, for _this_ project the temperature calibration is 'good enough' and I'll accept the tiny deviation in cold / hot weather. But, for a more serious application, it could be problematic.
U r really a true teacher. Give clues to get the answer. Really appreciate it.
It's my pleasure, thanks Kamal.
Been going through some of your earlier videos and lots of good info to be found--so thank you!
Also, great info on the 'shipping-insurance' and tariff-protection' caveats---which I think are worthwhile as I've had bad experiences on China-eBay orders in the past. Believe it or not, never used Bangood or AliExpress. Just Amazon and Tayda Electronics!
Thanks for all you do and really enjoy 'rummaging' around in your great repository Ralph... 😊
Glad you like them!
It's definitely worth checking out the two "big" Chinese warehouses. Banggood doesn't really sell many components as such, but does sell modules and part completed items that we can build on. AliExpress sells right down to the individual component level (albeit in lots of 10+), great for stocking up on ICs, resistors, capacitors etc.
I have also found that if you do 2 analogRead one after the other you get a more stable measurement.
Yes, the spec sheet mentions this but in my tests it made no difference (maybe because I was not actually doing an _anlogRead_ I was doing it via the registers).
The operation of (0
That's good to know, I will try this out! Thanks for posting,
Great video again Ralph. And it answers my comment from the earlier video. Thanks!
So it's a win-win for you Bruce! Glad you liked it. More on this topic in a future video.
Thank you. Connect directly to an analogue pin, ONLY with max 5 volts. Anything more needs a voltage divider to bring the voltage down to with the totllerences of Arduino. Again, thank you
Yes, absolutely. You might get away with 5.5v at a pinch but I wouldn't push your (my) luck!
Re: Customs tariff. I ordered some custom boards from a Chinese supplier, total incl. shipping was about £40. Got an e-mail from the carrier saying I had to pay an extra £20 or the boards wouldn't clear customs! (I payed, because I could pass the cost on to my customer.) Often wonder if I was had.
Oh wow! I don't think you were "had", but if the order is over about £15 then customs (and perhaps tax) must be paid, hence I keep my orders low. I had DHL say I had to pay some tax (quite small) before they would pick it up from a PCB manufacturer. I had no option but to pay the few pounds, I guess I was just over the limit. AFter Brexit it will only get worse, I suspect.
@@RalphBacon Bluddy Brexit! What wally came up with that idea? (rhetorical).
I read just yesterday that the £15 minimum order level is going to be lost once we Brexit. I blame Cameron and his silly 50% vote.
Regarding the BangGood shipping insurance problem and orders not received. If the payment was via a PayPal account or Credit Card using PayPal, it may be possible to open a dispute via PayPal regarding a refund. If you paid direct via credit card and the value is over £100, you may be able to claim the money back with a section 75 claim.
Yes, indeed, Chris, PayPal might assist; I'm not sure what the rules are with PayPal for getting your money back (I've got it back not once but twice from rogue sellers, not Banggood). And your credit card is always a good bet if you're ordering over £100 of goods. Good info, thanks for posting.
@@RalphBacon I'd be careful with the term goods regarding section 75. I'm fairly sure that section 75 covers an individual item costing between £100 and £30000, not a selection of goods that total over £100.
Ralph S Bacon, Chris G is correct; Section 75 only applies for a single item that costs more than £100, and not for a combination of items totalling more than £100. However, card issuers should apply a chargeback (i.e. refund you) for disputes on lower-value goods. I have never had a chargeback declined. Chargeback rules are not law, but are in issuers’ T&Cs as part of the credit card industry ‘code’. On the whole, if you are based in the UK, ‘transit insurance’ is a money-making scheme for the retailer. Also, Section 75 does apply to orders from overseas that are being delivered to the UK. I have fact-checked using a couple of sources, including ‘Which’. Thank you for your videos.
I am trying to find the right words to honor your great work -well we come to expect that from you :)
Good comments at the end about the Banggood shipping insurance.
The resolution and stability is certainly good enough for a battery indicator.
I wonder if you might make a part 2 to show how to get the best resolution and stability and an Arduino?
Did I mention that I stand on the shoulders of giants, Flemming? It's true. Many others have given us (me) the information that gets me going. It's the nature of open software, and it's great that we all benefit. But thank you, it's most appreciated.
Regarding a Part 2, others have requested a battery monitor when the VCC is not the voltage we're monitoring (eg via a buck boost) so I will endeavour to include it in that. Thanks for posting, good to hear from you.
I'm loving anything to do with battery stuff, another great explanation...cheers!
Your joy is reward enough for me, Andy. Well, no, it's not actually, but the thought is there!
Hi Ralph, I measured with my Current Ranger that you need "turn of" the "ADMUX" after use or the MCU will consume more power during deep sleep. It could be only the way my code is designed but by turning of (ADMUX =~) I lower the power consumption by 60uA.
Thanks for the info! A bare ATMega328P on my breadboard consumes just 0.2µA, as per the datasheet.
Man I’ve been fighting with a project very very similar to this.. starting with the voltage display I can’t get a cell to read correctly, close as I e gotten it to read is 4.53 and should read a cell that is at 3.28 , using voltage divider , caps and other components.... after I get it displaying the correct voltage then I can move on to the other cool stuff I have planned.. I’m going crazy with it!!!
There have been several requests to read any old battery voltage so I've added it to my list of things. Stay tuned and calm, Heny! And increase your dose of Valium. (Or, if you have spare, send them to me, boy do I need them).
Ralph S Bacon hehehee
Thanks for another interesting video. You mention that the chip will run at lower voltages but with reduced clock speed. Could you do a quick video of how to set the clock speed or point to an existing video if you have already done one. All I know is that it involves setting some internal registers. Thanks for taking the time to produce these instructive pieces.
The stock 328p, with no crystal, comes fused for internal RC 8mhz/div8 -- 1mhz, so you can run at minimal voltage there.
You can fuse it to run slower @128khz ... and even on a watch crystal. Be careful not to brick yourself, if you do not have a HVPP handy!
forum.arduino.cc/index.php?topic=353982.0
I'll be showing a very simple way of doing this, possibly in my next video, no additional hardware required!
Is the 10mV disparity between the power supply display and your measured voltage accounted for by a voltage drop on the supply wires?
Possibly, Gary, possibly. It could equally be that the PSU is not so/more accurate than my multimeter. Or just the measurement on AREF was not done as well as I could have done it. In this case, it's no biggie. For other projects I'd investigate a bit further.
Is usefull, because 0.01-0.03v of error is not too much.
Yes, it's not a great deviance, it will be fine I'm sure, Daniel.
Fantastic walkthrough as always 👍
Thanks for sharing 👍😀
Glad you liked it Asger, nice to hear from you.
hi Ralph, great content, something new and original each chapter 👌.
I should consider buying that freezer spray you showed at 20:20 to remove a stubborn wart from my finger but its quite expensive 😃😂👀(>40GBP)
@Undefined Lastname I thought it has liquid Nitrogen inside to reach such lower temperatures..
OMG, what is this, a medical forum now?!!!? I must say I do not condone the use of freezer spray on anything other than electronic components. On your own head be it if you use it for something else... Will it really remove a wart? Let me know if it works and I might have a go. I bought it here:
cpc.farnell.com/pro-power-chemicals/ppc239/freezer-spray-hfo-400ml/dp/SA03495
@@RalphBacon , Undefined Lastname
thanks for your time my friends, here I feel free to talk about all of my concerns and thoughts, cutting under my skin with a heated knife without any anesthesia sounds like a horror movie to me 😃.
The story was that: at work while patrolling (I work as a guard at a few lobbies) I used to kick the parapets with my knuckles just to strengthen my bones.
Unfortunately these 1" pipes are dirty and full with skin deseases, and later if you don't wash your hands with soap these microbes "drill" into your skin and later you find yourself asking an electronic online forum for solutions 😂🤣🤦♂️.
BTW, here is an electronic USB device for this, I wonder what effect this needle has on the bulge 😜😁.
www.aliexpress.com/item/32854287745.html?spm=a2g0o.productlist.0.0.57544480KSjYEK&algo_pvid=3b018f55-088d-4fc4-8342-fb12e2c4048d&algo_expid=3b018f55-088d-4fc4-8342-fb12e2c4048d-10&btsid=61a0cbcd-44e0-4a5e-92ac-cd02632f9c33&ws_ab_test=searchweb0_0,searchweb201602_8,searchweb201603_52
Looks and sounds like an instrument of torture, quite frankly.
Cheers Ralph, excellent stuff very useful couple of lines of code.....
I'm happy you found it useful, Tony! Nice to hear from you.
Good info about I always thought that if you used aref everything scaled to it so anything over ~1.1v would just read 1023. I guess I need to look at it again. I'm moving to esp32 mostly. I found a cheap one with lipo support and a small RGB LCD I think will be my new go-to. A bit more money but wifi, blue tooth, lipo support and a display for $6 is cheap enough to just throw at a priject.
It should be noted that these cheap boards with a LiPo connector tend to have lossy voltage regulators and power LED's which draw so much current it makes them badly suited for battery powered usage. Usually also the USB to serial converter chip draws in current even when not in use. In fact the same applies to pretty much all dev boards you can get with or without a battery connector/charging circuit.
To get them to a reasonable sleep mode current consumption (microamp range) you'll need to desolder the wasteful components (or alternatively cut traces leading to them.
Ristomatti Airo this particular one pulls about. 0.3-0.4 ma in sleep mode with the display turned off as shown in a video here on RUclips. Good enough for me to run maybe a day two in a pack I have. It’s a TTGO T-display.
Nice! I didn't know they've started to focus on that. And surely if a day or two fits the needs of your project then even better. I'm usually thinking about wireless sensor nodes of which I'd hope to get several months of battery life for them to not become a nuisance. :)
You could consider powering the display (and other peripherals) from a GPIO pin of the µC (possibly via a suitable transistor if the power is > 20mA). That way, the device wakes up, powers up the devices and does its stuff. Whilst asleep the peripherals consume zero power. That's the way I do it in my recent Benny PIR project. In sleep mode (Arduino ATMega328P) it's 0.2µA in sleep mode, 10µA including the PIR (which has to be on all the time, so it can wake up the µC).
Hi Ralph, well if I was going to just measure the battery voltage and just wanted to flag a low battery voltage I might use the internal voltage reference. but if the voltage was from critical source then I would use an external voltage reference with a very tight temperature characteristics, along with high stability resistors used in any protentional dividers etc. there also might be some opamp circuits to level shift the signal to give the best accuracy.
With a 10bit ADC you get 0.001072421875V/bit or with a bit of rounding 1.1mV / bit with the internal 1.1V ref.
I wonder what the chip uses to drop the supply voltage down to less than 1.1V internally, think I might have to go and read the datasheet some time soon.
great video as always as it gets the grey cell's under my grey hair working as I run down to being a house husband. :)
Yes, I did mention that if you needed more accurate (eg for a multimeter) you would need a better reference voltage, but for this type of simple project it works (very) well. They don't actually 'drop' the voltage, there is an industry standard circuit known as a Brokaw bandgap reference voltage circuit, invented by David Hilbiber, Bob Widlar, Paul Brokaw and others in 1964.
Glad you like the video and it got your grey cells a good workout!
@@RalphBacon Hi Ralph,
It took a while but I’ve got it straight in the old grey cells now.
Two constants and one unknown.
Constant #1 1.095V True BandGap voltage (TBGV) measured externally with higher accuracy
Constant #2 1024 number of bits in ADC (2^10)
Unknown #3 Supply voltage and hence ADC reference voltage.
Step one; Set mux to bandgap, and ADC reference to AVcc (which should be at supply voltage)
Step two; read ADC. This will give the bandgap voltage as a number of bits, where each bit has a value based on the supply voltage / number of ADC bits.
Step three; divide TBGV by ADC reading to give the Voltage per bit, by dividing the true bandgap voltage by this number gives us the true voltage of each bit.
Step four; multiply the true voltage of each bit by number of bits this will give us the ADC Reference voltage and hence supply voltage.
QED (quod erat demonstrandum (which was to be demonstrated))
Thanks again for getting me thinking, thought I’d write it down in case any others wanted to know the process behind the numbers.
Hi Ralph, Very clear and useful video - as always. I haven't looked at the code (yet) but what would be useful is the action the circuit takes when the voltage drops below a user-settable threshold - switch a relay, power Mosfet, shut down a device etc. The circuit also lends itself for use as a stand-alone module for all other battery-powered projects. Of particular interest for me is with the UPS-powered Raspberry Pi as in your previous videos (and the auto powerup module using an ATTiny)
The action you take on a low battery is just a simple if statement Dave.
if (batteryValue < requiredValue) {
do something here
}
I'll show you how I've implemented this in my Benny airing cupboard project from last week. Basically, as it comes out of Deep Sleep it checks the battery and beeps very quickly a few times if it's too low. works like a dream. Keep tuned.
The answer to how you would handle the device-to-device variance in commercial products of the analog reference voltage is that you would measure it. Instead of manually measuring Vref, and encoding that value into the sketch, you measure it in-circuit and use that value in the calculations.
The only consequence in doing this is whether there is a channel on the ADC attached to Vref or whether you have to use an ADC channel externally to measure pin 21. I don't know if the ADC loads the source significantly during conversion which, if it does, would justify use of that decoupling capacitor.
So you would have to have a sketch to load the EEPROM with the corrected value first as part of the manufacture (eg bootloader/sketch load). Yes, that could work.
lol at banggood, UK law applies if your buying in the UK and the responsibility to supply is with them, gets lost in post its legally their loss, contact you bank/card company, you will get your money back. well i have in the past and i'm no one special so.....
The key phrase is _if you're buying in the UK_ which I presume Banggood would not be considered a UK-based company. Or did you mean the purchaser being in the UK? Mostly I use PayPal for overseas purchases, will they also protect me?
@@RalphBacon the point of sale dictates the law, so if i am sat at home in the uk on my pc, then uk law should apply, and for me in the past has been enough, ..but... that being said, the law hasnt fully caught up with ''not in person international sales'' as it could be argued that the point of sale is their server in HK etc or as you say, if you have paid with paypal, is it then the US, and as paypal paid them with your funds, did you ''make the sale'' or did paypal.... as to your question, paypal have never let me down re protection. also if your paypal is linked to credit card, and paypal do let you down, then you may have a 2nd chance with the CC company, banks no way near as much as a cc company so its worth having a cc just for the use of paypal...
Will this technique work the same for other microcontrollers like ATTiny85 or ATTiny84?
You haven't got many pins on a Tiny85 but in principle it should work. Only one way to find out, Gary!
This is HUGELY helpful for me as most of my projects now are LiIon powered, and I've been struggling with external voltage regulators and whatnot in order to read voltages from around 4 volts to 2.5~3.
Will this code work on the ATTiny range, like ATTiny85?
It _can_ work on the Tiny85 but AREF uses PB0 pin so you might run of pins very quickly. More info in the datasheet and in this forum answer: electronics.stackexchange.com/questions/60237/attiny-default-aref
(Look at the second post)
I've not tried it although one day I will find time to do that!
Yup, just need the ADC multiplexer to be configured slightly differently - ADMUX = _BV(MUX3) | _BV(MUX2); instead of how it's configured for the ATmega328 - nothing else needs to change. In fact, if you have a look at this function snippet, it configures the registers different for several of the different microcontroller types... unfortunately that particular code writer didn't see fit to make it so the calibrated voltage was passed into the function so that a more accurate reading could be calculated. github.com/sweebee/Arduino-home-automation/blob/master/libraries/readVcc/readVcc.h
Hey Ralph, Many Thanks for wonderful guideline. But unable to compile on IDE even using your Zip folder as Library. Showing
BatteryVoltageReader.h: No such file or directory
.Kindly
Ensure you have placed that "missing" file (from the zip) into the same folder as your sketch, so the Arduino IDE can find it.
Hi Ralph,
Thanks for the awesome video...
If you remember a while ago I was struggling getting the voltage of a lithium cell using an analog pin to report the voltage. I haven't found a way to do this accurately, as the reported voltage varies wildly.
My circuit is a lithium cell with a boost converter to boost the current up to 5V, though I do take a wire directly from the battery to the analog pin.
I've tried resistive dividers, capacitors and other ways to try and get it to report a correct value. I think it'd make a great video if you can help and try something out? Thanks :)
A similar method would work for you too but does require a simple voltage divider on the analog pin. Because you don't care about VCC (which would stay pretty constant thanks to the buck boost) you want to measure the (lower) battery voltage against the internal AREF voltage. I'll add this to my list, Jessica, stay tuned!
Hi Ralph, very nice video, you mentioned that you have got new PIR sensors (now consuming 10microAmps) could you please share the link, thank you kindly!
Javier Palla Lorden I got mine here. rover.ebay.com/rover/0/0/0?mpre=https%3A%2F%2Fwww.ebay.com.au%2Fulk%2Fitm%2F264254233842
Sure, here's the link, just remember I can't guarantee what you will get sent, and these look identical to the ones I was using in my Home Alone project but use less current. Bizarre.
www.banggood.com/5Pcs-Mini-IR-Infrared-Pyroelectric-PIR-Body-Motion-Human-Sensor-Detector-Module-p-1020426.html?p=FQ040729393382015118&
Thanks Ralph Another interesting video. I wonder if those bypass caps are needed when the power source is a (no noise/ripple) battery? Also a question is "Aref" and input or an output or both? Regards Greg
Yes you _do_ need the caps in all cases, Greg, to prevent noise entering/leaving the chip, thus improving stability. At least, according to the Data Sheet which is the equivalent of the manufacturer's Bible on the subject. And they have to be right next to the chip too, as you will see on a future PCB of mine.
AREF is neither INPUT nor OUTPUT. Certainly, it reads the voltage present if you are using EXTERNAL as the reference, but if using INTERNAL you should not be connecting anything else to the pin; although you could switch between INTERNAL and EXTERNAL references if you used a resistor into the AREF (once again, the Data Sheet explains all). But you don't set it as either INPUT nor OUTPUT. Great question, thanks for posting.
The freezer spray will just be Carbon Dioxide, so nothing to worry about.
That would explain, Nicholas, why the first time I did it (without the BlueTac) it continued to work but it caused me some worry that I _might_ have damaged the chip with all that liquid sloshing about. Good to know then, CO2 it is!
or if from the poundshop its maybe just butane, I kid ye not, they did sell that for a while! a can of air with a butane propellent
@3m49s: Does that mean that we've been looking at a backwards Ralph all this time?
It just means, like my teachers always said, Ralph is a bit sdrawkcab.
Hi Ralph, you make a good point about chips behaving differently as I have a 3289-AU (QFP) running my sketch that simply has two switches, one puts it to deep sleep and one wakes it up and lights a LED and it is using a "poundland" AA battery, Zinc Chloride (1.5V) quite happily and has been for days, haven't got the deep sleep numbers yet (still waiting for parts ) but 1.5V is ok by me! Im lighting the LED from a CR2032 driven by the the 328p via a transistor (2N2222A)...again tiny currents I'm definitely into "low and slow" at the moment but my alternative "Nano" arrived today so gonna see what that can do..I wonder what MiniCore will make of it?
I'm wondering how you can possibly run an ATMega328P on 1.5V, Andy? The minimum, official voltage is 1.8V and whilst I have mine running OK at 1.6V it will stop at anything lower - and refuses to restart until I up the voltage to beyond 1.6V. What magic hast thou in they wizard's cape?
@@RalphBacon no idea! it is the QFP version but I had to measure it to believe it I will take a photo see if you can work it out! I swear it's a kodak AA from the pound shop ( 10 of them!) I'll show you the sketch as well
The laws of physics you have altered, my young Padawan. Strong with you the Force is.
@@RalphBacon Hahaha!...cheers!
Can I redar mow then one input at the same time
Not really sure what you are asking here! Would you like to rephrase the question, please?
Great video - I don't do a lot of analog, but I can see that this is really neat. Any idea if there is something like this for the STM32 - I don't even see an AREF pin on it - have not looked at the chip pinout - just the blue pill board layout.
Based on a quick web search this might be what you're looking for github.com/stm32duino/wiki/wiki/API
Look good, Ristomatti, I shall have to try that out too! Thanks for sharing.
@@ristomatti Thanks - I will have to try that out. I have a blue pill board that I use to drive SK6812 LED strings with about 200 leds. I use an external 5V supply to drive the LEDs, but if I forget to plug it in, it pulls the power off the processor board causing the voltage on the board to drop almost a volt. I would like to detect this and turn off the leds if the external voltage is not applied.
Your power for the LEDs should not be connected to your Arduino, Edward, just the grounds needs to be joined.
@@RalphBacon The power is not connected to the STM32 directly. The blue pill is a daughter board on a board I built that is normally driven by the same 5V 15A supply that drives the LEDs. We inject power every 50 LEDs, but the first 50 get there power from the board. Sometime, when I am just doing software development, I will plug in a 50 led string and just power it off the USB. This actually works fine. But, if the unit was installed in a pinball machine, it might be trying to drive 250 led, and I know that will not work (ask me how I know!). But, if I could sense the voltage, I could turn on the LEDs one at a time at startup and if the voltage started dropping, I could start flashing some kind of error signal - maybe 10 leds flashing red or something like that to indicate that something is wrong.
hi Ralph, thanks for helping everybody learning good staff.
one question.... in case of a battery powered project with an Arduino Pro mini 3.3v, the battery is attached to the RAW pin, not to VCC.... (battery full if 4.2 V in case of a Lipo).
this will compare the RAW voltage to the internal 1.1V?
Marco
If you're supplying the voltage into the RAW pin, that is then being converted to +3.3V by the onboard voltage regulator (a MIC5205 or similar). This means you *cannot* monitor your battery voltage using this method at all, because VCC (the reference) will _always_ report the full 3v3.
What you need to do is monitor the actual battery voltage directly as you indicate (the RAW voltage) but not like this. Luckily for you, my video in two weeks covers this topic completely so keep tuned.
Ralph S Bacon hi Ralph,
Yes that’s my point.... so in your example how do you power up your arduino with 3 volts?
What I mean, in VCC pin you should plug in or 5V or 3.3V (in my case of pro mini).
If you use a battery you should plug it into RAW, isn’t it?
At the moment I use a trimmer 10K for getting out a 1.1 V from the slider when my lipo is fully charge at 4.2 Volts, the slider gets into A0. So when battery drops to 3.7 I lid a Led to remind me to charge.
So I still don’t understand why check the VCC Vs internal reference while the VCC should be fix and regulated. Unless... is the arduino uno able to work with VCC 3.7-3.6?
Let's clarify our terminology and what we are talking about here.
The Arduino (actually let's be specific here, it's a bare ATMEGA328P chip) will run from 1.8v to 5.5v when powered directly into the VCC pins (two of them) on the chip. That's the way most battery-powered projects are powered up. You will have to run off the 8MHz internal oscillator once you drop below about 4v as you cannot run at 16MHz at such a low voltage.
If you are using an Arduino UNO _board_ with a Vin pin, your 6v - 12v power goes through an inefficient voltage regulator to give 5v. You would not put a LIPO through that pin, the Arduino will run directly from the +5v pin from 4.2v all the way down to the 3.0 LIPO cut-off voltage (albeit not necessarily at 16MHz as mentioned above).
A LIPO has a fully-charged voltage of 4.2 that quickly drops to its nominal 3.7v where it very slowly drifts down to 3.4 before falling off a cliff edge down to 3.0 when the battery protection circuitry will kick in at 3.0v.
The 328P chip provides a nominal 1.1v reference (which you can measure at the AREF pin) and it will use this to measure VCC. If you want to be precise you need to measure the actual voltage presented at AREF and plug that value into the formula I showed.
If your battery is going through a DC-DC step up (boost) module to get 5v out of a 3.4v LIPO then you need to measure the battery directly, which is exactly the topic of my video in two weeks' time.
Make more sense now? Watch the next but on video!
Ralph S Bacon Thanks Ralph, all clear. I use a pro mini 3.3v so that’s why I have to plug the lipo on the raw pin... thanks again for you help!
👍
Does the Tariff Insurance cover quite what you expecting?! When I read it, firstly it doesn't seem to cover service charges like the £8 ish (+vat?) Royal Mail add to handle the payment and secondly, does it cover vat? Between £15 and £100 pounds isn't there technically only vat charged on the package and not import duty? And since vat isn't a tariff is it covered? So I can't see it being worthwhile except on particularly large orders
Ha! I knew somebody would query this, as my suspicions were aroused too. I think we can safely assume that the answer to your question is "probably not". If the import duty was £10 they should/would cover that. But that plus a handling charge of £8 plus VAT on the lot would easily make a hole in your pocket. As you say, probably worth doing on larger orders only. It's the one thing that stopped me buying more (expensive) stuff from China.Well, that and the lack of any kind of guarantee, of course.
Most of the tools I have in my workshop have been UK-sourced. I want some kind of guarantee on these sort of items. And no unexpected C&E bill. DHL demanded a relatively small amount of $4 from me for the latest PCBWay shipment, before they would even pick it up. It must have just snuck into the higher value category. I dread to think what the $40 PCB batch I'm next about to order will do to my pocket!
Caveat emptor!
Indeed. I have seen this answered by banggood. They will only cover the duty (or presumably vat). They will not cover the handling charge.
Couldn't you just use a voltage divider across vcc and ground fed in to an analog port and compared to the internal 1.1 reference? Given the fact that that isn't temperature stable and that you don't really care if the battery is completely or very nearly completely flat before you change it, surely this is good enough. Or is it that the voltage divider idea consumes current, which defeats the object of this particular exercise, which is to run for as long as you can? By the way, I got annoyed with Banggood when an empty envelope arrived that was supposed to contain two LEDs. Banggood refused to accept responsibility without me getting written confirmation from the post office of the weight of the package as it travelled through the system, presumably to identify where in the world the two Leds disappeared. As if the weight would be measurably different with and without the leds. Two leds to them - 1p. Cost or arguing for days, who knows. Certainly more than 1p. Stupid.
Funnily enough, Jessica has requested a method to read what is effectively an _external_ voltage (the input to a buck boost) so I've added this to my list, Andy, and we can explore the options in a future video!
getting 'BVR' not declared in this scope error message when compiling.
newbie any help please and thanks.
You're using the sketch with the library, then, John?
BVR (which stands for Battery Voltage Reader, in my sketch) relies on the library being available.
Copy the library files (.cpp and .h) from my GitHub into a folder called BatteryVoltageReader in your 'libraries' folder which is inside your Arduino sketches folder (sounds a bit convoluted but really isn't). If you are still stuck and can't move on, let me know I'll give you a screenshot.
@@RalphBacon Thanks Ralph I do understand that I did get your other version without library first time.
I will try the lib. version as well.
Thanks for the great videos and your speedy response
john.
Hi Ralph.
Having trouble with the battery monitoring.
The sketch works fine it's my hardware seems to be the problem
I have a diymore 18650 battery shield much like the one in your video, using this to power arduino uno.
I then connect the Txd line from the arduino to the Rxd line on my usb to serial connector to monitor the voltage.
I get nothing but when I ground the gnd line from the usb/serial it works ?. but I get a fairly constant 4.99 volts. I think I may be monitoring the usb port voltage. I am not sure what
is going on, as I said complete newbie just following the pictures without fully understanding.
Sorry for the long note if you can shed any light on this that would be great but I understand you may not have time.
Regards John
Ralph, I may have resolved my problem by connecting my battery directly to vin.
Regards John
your videos always turn my head gears.
do you how use atmega 328 p without bootloader but code can still be uploaded by using the arduino maybe using it as isp.
Get an usbasp clone (2€ on ebay) or program another Arduino as ISP programmer, connect those to the ISP pins of the AVR you want to program and then just selected the programmer in the Arduino IDE.
@@superdau sorry i am still confused
so if have a atmeage329p without bootloader so i can just program it by using arduino as an isp right?
select programmer in gui as arduino isp. program arduino as isp with the built in sketch.
connect wire of spi communication
open code in GUI and upload it "upload using programmer"
@@inferno6012
I haven't used the Arduino IDE in ages (using atom/VSC with platformIO). But yes, I remember there is a Arduino-ISP sketch in the examples. You write that to an Arduino board (which has a boot loader) the "normal" way. You then connect it to another Arduino (or even almost bare AVR chip) using the ISP pins. Somewhere there's a list how the ISP pins of the two Arduinos have to be connected. And yes you then select the "ArduinoISP" as programmer and upload using "Upload using programmer".
It's nothing special, there are enough explanatons of this available on the internet, if you need to know more.
@@superdau ok thanks
I'll be doing a video on all this very soon, keep tuned!
Hey Ralph, could you please make a video on how to measure current and voltage used by an Arduino UNO setup? Please do a review on the GY-INA219 High Precision I2C Digital Current Sensor Module. I am looking for a way to accurately measure power consumption in my Arduino robot. Thanks again for your help!
I've already done this! Look at my recent Intelligent Phone Charger video which uses the INA219, works like a dream.
cool nice video thank you :)
Thanks for watching!
@@RalphBacon im 50 plus i've always love electronics from a kid. only just been getting into the uno things wow. what an amazing bit of kit. i remember trying to make various thing over the passed using just 74 and 4000 logic gates and end up with loads of chips and wires running all over the place. then this thing pop up in my radar half the things i made over the pass could have just been programmed into this things i know thats there propose in the first place but when you see it in action it just blows my mind lol.. is there any books that you would recommend at all?
Seriously though, integers are far worse. 1.0/3.0 may be 0.333333 with floats but 1/3 is 0 with integers! I think the real reason floats take so much shade is because floating point libraries for 8 bit micros are both both bulky and very slow. Embedded programmers take great pride in NOT needing to use them.
"floating point libraries for 8 bit micros"
Floating points are bad for more reasons than that.
A properly programmed algorithm using integers will keep the full precision possible with the processor. With floats the rounding quickly becomes an issue for anything other than trivial calculations.
Floats are very rarely the right choice in an embedded program.
@Peter If you were doing calculations (or holding values) like that 1/3, you would first multiply the value by 10, 100, 1000... whatever accuracy you need. Then 1/3 becomes 1000/3 which is 333 (integer) and you do all the maths on that figure with other numbers that are also 1000 times bigger. As a *final* step, divide by 1000 into a float (if you wish) to get the final value. Which is what we do in this sketch - hold the "float" of AREF as a value 1000 times bigger to get the required accuracy. I hope this makes sense! Regarding floating point libraries being big (and possibly slow) that is totally correct. But if you _need_ a float as the end result then you will need that library for the final step.
@@RalphBacon My point here is that the rounding has not gone away. Yes you can scale all your calculations but there is still loss of accuracy. 1000/3 is not 333 it's 333.3333... And now we add the risk of integer overflow with insane results when it occurs. If memory serves, the European Space Agency found this out the hard (and costly, and dangerous) way when the flight control software of an Ariane 5 rocket failed with an integer overflow. Floats balance dynamic range while keeping maximum accuracy. They are just resource hogs which is a strong reason to avoid them if you can. An alternative is to implement a rational data type, which I have done on numerous occasions, but that is beyond the scope of this discussion.
Agreed, rounding never goes away, it just gets pushed to the point where it is acceptable (and predictable). Rational data types have been around (and supported) for years, even in C++, but something tells me the Arduino flavour doesn't do this (I may be wrong, I never checked).
Not as good as a rational (a non-rounding type) but we can also use long longs (64-bits) so multiplying up should not be a problem even there, and rounding becomes far less of an issue. And no float library in sight! There's an interesting article here: softsolder.com/2017/05/26/arduino-vs-significant-figures-useful-64-bit-fixed-point/
Hi Ralph, thanks for the great video. How can I find out what other Atmel chips can do this measurement? In particular I'm very interested to see if the ATTiny841 can also do this. Thanks again.
I haven't had any experience of the Tiny841 (nor its smaller brother the Tiny441) and having looked at the spec sheet I'm wondering, Graham, what it is about that chip that appeals so much (compared to, say, the Mega328P)?
The ATTiny 841 is low power, can be programmed in the Arduino IDE (with the appropriate library), has hardware I2C, and 2 x hardware serial, which is of particular interest for me as I want to daisy chain several together. It appears to be a bit of an ATTiny85 on steroids (which I believe only does software serial and I2C)
After watching your video I did a bit of further research and found the following document which seems to describe the VCC measurement technique:
ww1.microchip.com/downloads/en/AppNotes/00002447A.pdf
At the end of the doc it lists all the Atmel chips that can do this measurement, and the ATTiny841 can do it. Happy days. just need to understand the registers..... :)
centiVolts FTW
Yay! thanks for sharing!
Another great video Ralph :) You (and others) might also be interested in the work of rlogiacco, as he has put together two very nice libraries about battery sensing... github.com/rlogiacco/VoltageReference does the bandgap voltage reading, and has the added benefits of passing in a calibration voltage when starting the library, or even having it read back from EEPROM if you've saved it there. There is then the BatterySense project, centered around making it easier to make a voltage-based decision about whether the battery is flat or not... in a percentage form. I haven't used them myself, but instead did something similar to Nick's function. I am working on a RF sensor project, and when I commission each node I shove the 1V1 value into EEPROM so the code can read it back without having to put different code on each node. I'll probably incorporate the VoltageReference library instead in future as it's less code to maintain ;)
Ooh, I must read that, Peter, it seems a very common requirement, thanks for the pointer!
Ralph, when you drag soldered your atmega328 what temp did you use on your soldering iron?
I was using about 300°C, Jeff, but it was with my little Antex C18W - these days I use 350°C using my lovely ATTEN ST-100W and it works a _lot_ better!
Ralph S Bacon no problems with burning up the processors?
No, not at all. I'm not saying you should dawdle but as long as you have enough flux on the pins, apply the iron, let the solder melt and get sucked into the pin and move on to the next pin. Each pin probably has less than 1 second of heat applied. Let it cool for a few seconds before correcting any bridges or solder wicking the bridges away. Seems to work for me (admittedly, much to my surprise). Practice using the SMD practice boards from Banggood which contain some SMD chips and taught me how NOT to do it!
Probably one of the worst names for a LiPo battery ever aha
I can only imagine their marketing budget was quite small!
ULTRAFIRE .....what a scam :)
Hang on there, Graham, it says 10,000mAH on that battery, are you telling me that not true, either? 🤣
@@RalphBacon The model number is "10,000mAH". What's wrong with that?
You've got to admire the magnitude of the minerals on a man who willingly buys Lithium batteries with that brand name.
I have some _real_ Ultrafire AA batteries though, good ones they are too, although poor choice of name, agreed. The charger does say not to use unattended. Hmm...
@2m11s: Should be MHz, not Mhz. :-)
True, Heinrich would be very upset as such disrespect. I shall endeavour to be more respectful in future videos.
Ralph S Bacon While we’re correcting spelling and grammar then @ 8:10, line 7 “Force interal” correct “Force internal”. Obviously it doesn’t matter in commenting but it will expressions. Yes I’m another pedantic German that can’t let a typo pass without comment.
@MUDGEL the _interal_ is something quite different and advanced, actually. Far too advanced for this channel. I would say thanks for posting, but in this case... heh heh. But I'm off to see my non-pedantic Mutti and family in Stuttgart next week so I'll give you a wave. MfG bis demnaechst!
Ralph S Bacon Very poor German here. Emigrated to Australia aged 5 so didn’t ever have any formal schooling in the German language. We spoke a dialect when at home but I only once saw it in a written form in a local cookbook. I’m from Idar-Oberstein in Germany, en.wikipedia.org/wiki/Idar-Oberstein I understand “bis demnaechst” - till the next time or catch ya later mate..but what is “MfG”?
MfG stands for mit freundlichen Gruessen, in other words, Best Regards or something similar. My daughter and her partner are visiting 'straya at this very moment, somewhere in the vicinity of Brisbane. She's having a great time. And has no trouble understanding the locals either. All those hours watching _Home & Away_ and _Neighbours_ have really paid off, ha ha!
Who is Nick?
Nick Gammon, no relation, guru of all things Arduino, from Australia.
Not to confused with Nearly Headless Nick, it's Nick "The Arduino God" Gammon! 😂😂😂