Given: arduino nano (atmega328P) with nrf24l01. What am I trying to do: Measure battery drain. What am I doing for that. So I made a small research of how could I measure the battery voltage without using any additional pins (already printed the board and suddenly realized it would be good to also measure the battery drain). And found samples with almost always similar code:

long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;

It works okey when I have batteries charged but once it get to 3.7 volts writing to ADMUX seems to be crashing the whole program and restarts chip. Everything else is working fine before this operation though.

Several questions:

  1. Could anyone explain me why does it crash?
  2. How to prevent it?
  3. Would reflashing bootloader and setting oscillator to 8Mhz help with this problem?
  • add debugging code... the program may not be crashing ... it may be getting into an endless loop ... the while line may be the endless loop
    – jsotola
    Nov 15, 2022 at 17:45
  • 1
    I'm pretty sure it is crashing. Because it restarts and sends data again with nrf24l01. I checked it by sending counter which I increment each loop. And when it is crashing it is always 0. So it is crashing. Nov 15, 2022 at 21:45
  • could be the power supply browning out when the NRF24L01 activates its radio
    – jsotola
    Nov 15, 2022 at 22:09
  • Not really sure how can it be possible. With a slightly higher power everything works alright. Also if I connect temp sensor everything works alright. It is failing exactly on writing to ADMUX. Nov 15, 2022 at 22:34
  • 1
    How did you figure out it was failing exactly on writing to ADMUX?
    – Fahad
    Nov 16, 2022 at 19:46


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.