GameCounter/Source/src/main.c

119 lines
2.8 KiB
C

#include <stdint.h>
#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>
#include <ssd1306xled.h>
#include "shared.h"
#include "screen/counter.h"
#define VccTreshold 3000
// Forward declarations
uint8_t hasPower();
void waitForInput();
void handleCurrentScreen();
uint16_t readVCC();
int main()
{
while (1)
{
if (hasPower())
handleCurrentScreen();
}
return 0;
}
void waitForInput()
{
// TODO go to sleep until a button is pressed
_delay_ms(1000);
}
void handleCurrentScreen()
{
handleCounterScreen();
}
uint8_t isOn = 0;
uint8_t hasPower()
{
vcc = readVCC();
// Turn display off below 3v. It holds up surprisingly well, but at around
// 1.5v it does corrupt the screen and requires reinitialization when the
// voltage is turned back up.
//
// ...although by then the battery would be damaged, but still, turning off at
// 3v means we're close enough to the recommended minimum of 2.7v for LiPo
// batteries to be safe.
//
// TODO go into a sleep cycle until the battery is recharged
if ((vcc > VccTreshold) != (isOn != 0))
{
isOn = !isOn;
if (isOn)
{
// Delay is required on power-on for the SSD1306 to initialize,
// to be sure we're simply delaying every time it's reinitialized
_delay_ms(40);
ssd1306_init();
}
ssd1306_clear();
}
return isOn;
}
// Source: http://21stdigitalhome.blogspot.nl/2014/10/trinket-attiny85-internal-temperature.html
//
// I've tried many versions and none seemed to work with my ATTiny85-20SU's.
// For example:
// https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
// https://github.com/cano64/ArduinoSystemStatus/blob/master/SystemStatus.cpp
// http://www.avrfreaks.net/forum/attiny-adc-using-internal-ref-measure-vcc-problem
//
// The key for me was in: ADMUX = 0x0c | _BV(REFS2);
uint16_t readVCC() {
ADCSRA |= _BV(ADEN);
// Read 1.1V reference against AVcc
// set the reference to Vcc and the measurement to the internal 1.1V reference
/*
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0);
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#endif
*/
ADMUX = 0x0c | _BV(REFS2);
_delay_ms(100);
ADCSRA |= _BV(ADSC);
while (bit_is_set(ADCSRA,ADSC));
uint16_t result = ADC;
ADCSRA &= ~(_BV(ADEN));
return result == 0 ? 0 : 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
}