]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/battery.c
battery.c: priority of operations
[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      100    // kOhm
7
8 volatile unsigned char battery_100mv = 0;
9
10 void init_battery()
11 {
12         battery_100mv = 0;
13 }
14
15 void battery_adc(uint16_t adcval)
16 {
17         /*
18          * This is tricky: we need to maintain precision, so we first
19          * multiply adcval by as big number as possible to fit uint16_t,
20          * then divide to get the final value,
21          * and finally type-cast it to unsigned char.
22          * We don't do running average, as the required precision
23          * is coarse (0.1 V).
24          */
25         battery_100mv = (unsigned char)
26                 ((uint16_t)(adcval * (11                   // 1.1V
27                 * (RESISTOR_HI+RESISTOR_LO)/RESISTOR_LO    // resistor ratio
28                 / 4)) >> 8);                               // divide by 1024
29 }
30