5 #define BATTERY_ADC_SHIFT 2
6 #define RESISTOR_HI 1500 // kOhm
7 #define RESISTOR_LO 100 // kOhm
9 * The internal 1.1V reference has tolerance from 1.0 to 1.2V
10 * (datasheet, section 19.6). We have to measure the actual value
13 #define AREF_1100MV 1060 // mV
15 static volatile uint16_t battery_adcval;
16 static unsigned char initial_readings = 0;
24 unsigned char battery_100mv()
27 * This is tricky: we need to maintain precision, so we first
28 * multiply adcval by as big number as possible to fit uint16_t,
29 * then divide to get the final value,
30 * and finally type-cast it to unsigned char.
31 * We don't do running average, as the required precision
34 return (unsigned char)
36 (battery_adcval >> BATTERY_ADC_SHIFT)
38 * (RESISTOR_HI+RESISTOR_LO)/RESISTOR_LO // resistor ratio
39 / 4)) >> 8); // divide by 1024
42 void battery_adc(uint16_t adcval)
44 if (initial_readings) {
46 battery_adcval = adcval << BATTERY_ADC_SHIFT;
47 } else if (battery_adcval == 0) {
48 battery_adcval = adcval << BATTERY_ADC_SHIFT;
49 } else { // running average
50 battery_adcval += (adcval
51 - (battery_adcval >> BATTERY_ADC_SHIFT));
54 log_byte(battery_100mv());
59 unsigned char battery_gauge()
61 unsigned char b8 = battery_100mv();
80 if (rv == 1 && !initial_readings)
81 set_error(ERR_BATTERY);