diff --git a/firmware/Makefile b/firmware/Makefile index efa55c1..b716d96 100644 --- a/firmware/Makefile +++ b/firmware/Makefile @@ -3,7 +3,7 @@ CFLAGS=-g -Wall -Wno-multichar -Wno-overflow -mcall-prologues -mmcu=$(MCU) -O2 - LDFLAGS=-Wl,-gc-sections -Wl,-relax CC=avr-gcc TARGET=main -OBJECT_FILES=main.o input.o systick.o oled-display/font.o oled-display/i2c.o oled-display/lcd.o +OBJECT_FILES=main.o batmon.o input.o systick.o oled-display/font.o oled-display/i2c.o oled-display/lcd.o all: $(TARGET).hex diff --git a/firmware/batmon.c b/firmware/batmon.c new file mode 100644 index 0000000..7f9be9f --- /dev/null +++ b/firmware/batmon.c @@ -0,0 +1,25 @@ +#include +#include "batmon.h" + +void batmon_init() +{ + ADCSRA = (1 << ADPS2) | (1 << ADPS1); // 125 kHz ADC clock + ADMUX = ADC_CHANNEL | (1 << REFS0) | (1 << REFS1) | (1 << ADLAR); // Internal 1.2V bandgap, left adj. + ADCSRB = 0; // Manual start +#if ADC_CHANNEL < 7 + DIDR0 = (1 << ADC_CHANNEL); // Disconnect digital channel +#endif + + // Enable voltage divider + PORT_ADCC(DDR) |= PIN_ADCC; + PORT_ADCC(PORT) &= ~PIN_ADCC; + + // Enable ADC + ADCSRA |= (1 << ADEN); +} + +inline uint8_t batmon_get_voltage() +{ + ADCSRA |= (1 << ADSC); // TODO: Check whether this increases the power consumption of the chip by much + return ADCH; +} diff --git a/firmware/batmon.h b/firmware/batmon.h new file mode 100644 index 0000000..9ee5c92 --- /dev/null +++ b/firmware/batmon.h @@ -0,0 +1,12 @@ +#ifndef BATMON_H +#define BATMON_H +#include + +#define ADC_CHANNEL 0 +#define PORT_ADCC(t) t##D +#define PIN_ADCC (1 << 1) + +void batmon_init(); +uint8_t batmon_get_voltage(); + +#endif // BATMON_H diff --git a/firmware/main.c b/firmware/main.c index 18f8fde..25a0f0b 100644 --- a/firmware/main.c +++ b/firmware/main.c @@ -5,6 +5,7 @@ #include "oled-display/lcd.h" #include "input.h" #include "systick.h" +#include "batmon.h" #define PORT_SPI(t) t##B #define PIN_SPI_CS (1 << 2) @@ -33,7 +34,7 @@ uint8_t spi_proc() if (SPSR & (1 << SPIF)) { switch (y) { case Y_MAX - 1: - spdr_next = 55; // TODO: Vbat + spdr_next = batmon_get_voltage(); break; } SPDR = spdr_next; @@ -86,6 +87,7 @@ int main() spi_init(); systick_init(); input_init(); + batmon_init(); _delay_ms(10);