Last active
January 23, 2022 05:58
-
-
Save matty0005/219007dcdb1b235b2e250bbc705b14a3 to your computer and use it in GitHub Desktop.
Attiny 85 Low voltage cutoff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <avr/io.h> | |
#include <util/delay.h> | |
#define MOSFET 4 | |
#define LED 1 | |
/* Returns the voltage of a battery in mV */ | |
uint16_t measure_voltage() { | |
ADCSRA |= (1 << ADSC); //Start conversion | |
while ((ADCSRA & (1 << ADSC)) != 0) | |
; | |
uint16_t value = ADCL | (ADCH << 8); // Read value | |
// Value from 0 - 1024 -> 0 - 25.2v, 0.025v/digit -> 25,200 max value, -> 25/digit | |
return value * 25; | |
} | |
int main(void) { | |
//Configure Mosfet to output and turn on | |
DDRB |= (1 << LED)| (1 << MOSFET); | |
PORTB |= (1 << MOSFET); | |
// Configure ADC | |
ADMUX = (1 << REFS1) | (1 << REFS2) | (1 << 1) | (1); // 2.56v Vref | |
ADCSRA |= (1 << ADEN); | |
// Measure voltage at start up to estimate battery size | |
uint16_t batt_ref = measure_voltage(); | |
uint8_t cell_count = batt_ref / 3400; // Estimate cell >= 3.4v | |
uint16_t min_voltage = cell_count * 3200; //Cutoff voltage | |
uint16_t meas; | |
while (meas = measure_voltage(), meas >= min_voltage) { | |
for (uint8_t i = 0; i < cell_count; i++) { | |
PORTB |= (1 << LED); | |
_delay_ms(150); | |
PORTB &= ~(1 << LED); | |
_delay_ms(100); | |
} | |
_delay_ms(2000); | |
} | |
// turn off mosfet, adc and sleep | |
PORTB &= ~(1 << MOSFET); | |
ADCSRA &= ~(1 << ADEN); | |
MCUCR |= (1 << SE) | (1 << SM1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment