]> www.fi.muni.cz Git - bike-lights.git/blobdiff - firmware/battery.c
battery voltage sensor
[bike-lights.git] / firmware / battery.c
diff --git a/firmware/battery.c b/firmware/battery.c
new file mode 100644 (file)
index 0000000..472c1c4
--- /dev/null
@@ -0,0 +1,25 @@
+#include <avr/io.h>
+
+#include "lights.h"
+
+#define RESISTOR_HI    1500    // kOhm
+#define RESISTOR_LO     150    // kOhm
+
+volatile unsigned char battery_100mv;
+
+void battery_adc(uint16_t adcval)
+{
+       /*
+        * This is tricky: we need to maintain precision, so we first
+        * multiply adcval by as big number as possible to fit uint16_t,
+        * then divide to get the final value,
+        * and finally type-cast it to unsigned char.
+        * We don't do running average, as the required precision
+        * is coarse (0.1 V).
+        */
+       battery_100mv = (unsigned char)
+               ((adcval * 11                              // 1.1V
+               * (RESISTOR_HI+RESISTOR_LO)/RESISTOR_LO    // resistor ratio
+               / 4) >> 8);                                // divide by 1024
+}
+