fw: Implement battery voltage readout

This commit is contained in:
Markus Koch 2020-07-30 17:11:48 +02:00
parent 475c9cdd4a
commit 9e9e2ff5c4
4 changed files with 41 additions and 2 deletions

View File

@ -3,7 +3,7 @@ CFLAGS=-g -Wall -Wno-multichar -Wno-overflow -mcall-prologues -mmcu=$(MCU) -O2 -
LDFLAGS=-Wl,-gc-sections -Wl,-relax LDFLAGS=-Wl,-gc-sections -Wl,-relax
CC=avr-gcc CC=avr-gcc
TARGET=main 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 all: $(TARGET).hex

25
firmware/batmon.c Normal file
View File

@ -0,0 +1,25 @@
#include <avr/io.h>
#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;
}

12
firmware/batmon.h Normal file
View File

@ -0,0 +1,12 @@
#ifndef BATMON_H
#define BATMON_H
#include <avr/io.h>
#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

View File

@ -5,6 +5,7 @@
#include "oled-display/lcd.h" #include "oled-display/lcd.h"
#include "input.h" #include "input.h"
#include "systick.h" #include "systick.h"
#include "batmon.h"
#define PORT_SPI(t) t##B #define PORT_SPI(t) t##B
#define PIN_SPI_CS (1 << 2) #define PIN_SPI_CS (1 << 2)
@ -33,7 +34,7 @@ uint8_t spi_proc()
if (SPSR & (1 << SPIF)) { if (SPSR & (1 << SPIF)) {
switch (y) { switch (y) {
case Y_MAX - 1: case Y_MAX - 1:
spdr_next = 55; // TODO: Vbat spdr_next = batmon_get_voltage();
break; break;
} }
SPDR = spdr_next; SPDR = spdr_next;
@ -86,6 +87,7 @@ int main()
spi_init(); spi_init();
systick_init(); systick_init();
input_init(); input_init();
batmon_init();
_delay_ms(10); _delay_ms(10);