]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/battery.c
battery voltage sensor
[bike-lights.git] / firmware / battery.c
1 #include <avr/io.h>
2
3 #include "lights.h"
4
5 #define RESISTOR_HI     1500    // kOhm
6 #define RESISTOR_LO      150    // kOhm
7
8 volatile unsigned char battery_100mv;
9
10 void battery_adc(uint16_t adcval)
11 {
12         /*
13          * This is tricky: we need to maintain precision, so we first
14          * multiply adcval by as big number as possible to fit uint16_t,
15          * then divide to get the final value,
16          * and finally type-cast it to unsigned char.
17          * We don't do running average, as the required precision
18          * is coarse (0.1 V).
19          */
20         battery_100mv = (unsigned char)
21                 ((adcval * 11                              // 1.1V
22                 * (RESISTOR_HI+RESISTOR_LO)/RESISTOR_LO    // resistor ratio
23                 / 4) >> 8);                                // divide by 1024
24 }
25