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:
- Could anyone explain me why does it crash?
- How to prevent it?
- Would reflashing bootloader and setting oscillator to 8Mhz help with this problem?
while
line may be the endless loop