summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSadeep Madurange <16175248+smadurange@users.noreply.github.com>2025-08-17 12:30:27 +0800
committerGitHub <noreply@github.com>2025-08-17 12:30:27 +0800
commitd7edbdf11b419f152d627405fe9a368e6c1e81dd (patch)
treefe373a5ddb7c29da5a7c05ddec261426d01d4d77
parentf421d44c1898cdf1c7a8c1eab2414738b2543fad (diff)
parent56abe66f1b1aa6e172b9aec916b87c60c08a94fe (diff)
downloadfpm-door-lock-d7edbdf11b419f152d627405fe9a368e6c1e81dd.tar.gz
Monitor battery level using the ADC
-rw-r--r--main.c50
1 files changed, 46 insertions, 4 deletions
diff --git a/main.c b/main.c
index beeb87a..9efbffa 100644
--- a/main.c
+++ b/main.c
@@ -1,4 +1,5 @@
#include <stdint.h>
+#include <stdlib.h>
#include <avr/wdt.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
@@ -7,6 +8,8 @@
#include "fpm.h"
#include "uart.h"
+#define BATMIN 5100
+
#define SERVO_PIN PB1
#define SERVO_DDR DDRB
@@ -19,6 +22,7 @@
#define LED_DDR DDRB
#define LED_PORT PORTB
+#define PWR_BATCHK PB2
#define PWR_SERVO PB3
#define PWR_FPM PB4
#define PWR_DDR DDRB
@@ -100,19 +104,57 @@ static inline void flash_led(void)
}
}
+static inline void pwron_batchk(void)
+{
+ PWR_PORT &= ~(1 << PWR_BATCHK);
+}
+
+static inline void pwroff_batchk(void)
+{
+ PWR_PORT |= (1 << PWR_BATCHK);
+}
+
+static void check_bat(void)
+{
+ uint16_t vbg, vcc;
+
+ pwron_batchk();
+
+ ADMUX |= (1 << REFS1) | (1 << REFS0);
+ ADCSRA |= (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1); /* clk: 50-200 kHz */
+
+ _delay_us(500); /* https://www.sciencetronics.com/greenphotons/?p=1521 */
+
+ ADCSRA |= (1 << ADSC);
+ while (ADCSRA & (1 << ADSC))
+ ;
+
+ ADCSRA &= ~(1 << ADEN);
+ vbg = (1100UL * ADC) / 1024;
+ ADCSRA &= ~(1 << ADEN);
+
+ pwroff_batchk();
+
+ vcc = (vbg * 66) / 10; /* 56k/10k divider */
+ if (vcc < BATMIN)
+ flash_led();
+}
+
int main(void)
{
uint16_t id;
- /* disable watchdog timer */
+ /* disable wdt */
cli();
wdt_reset();
MCUSR &= ~(1 << WDRF);
WDTCSR |= (1 << WDCE) | (1 << WDE);
WDTCSR = 0x00;
+ PWR_DDR |= (1 << PWR_BATCHK) | (1 << PWR_FPM) | (1 << PWR_SERVO);
+ pwroff_batchk();
+
uart_init();
- PWR_DDR |= (1 << PWR_FPM) | (1 << PWR_SERVO);
pwron_fpm();
fpm_init();
@@ -144,9 +186,9 @@ int main(void)
PCMSK2 |= ((1 << FRONT_LOCK_INT) | (1 << ENROLL_INT) |
(1 << BACK_LOCK_INT) | (1 << BACK_UNLOCK_INT));
- flash_led();
-
for (;;) {
+ check_bat();
+
switch(cmd) {
case LOCK_FRONT:
lock();