Files
JustAnotherClock/src/clock.c

168 lines
2.4 KiB
C

#include <stdint.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "clock.h"
volatile clock_t clock;
volatile opTime_t opTime;
volatile uint8_t useLocalClock = 1;
volatile uint8_t nextSecond = 0;
volatile uint8_t nextMinute = 0;
volatile uint8_t tack = 0;
volatile uint8_t step = 0;
void clockInit() {
clock.hour = 0;
clock.minute = 0;
clock.second = 0;
opTime.hour = 0;
opTime.minute = 0;
opTime.second = 0;
// seconds
TCCR2 = 0b00000101;
ASSR |= (1 << AS2);
TIMSK |= (1 << TOIE2) | (1 << TICIE1);
// heartbeat
TCCR0 = (1 << CS02) | (1 << CS00);
TIMSK |= (1 << TOIE0);
}
ISR(TIMER2_OVF_vect) {
clock.second++;
if (useLocalClock == 1) {
if (clock.second >= 60) {
clock.minute++;
}
if (clock.minute >= 60) {
clock.minute = 0;
clock.hour++;
}
if (clock.hour >= 24) {
clock.hour = 0;
}
}
if (clock.second >= 60) {
clock.second = 0;
}
opTime.second++;
nextSecond = 1;
if (opTime.second >= 60) {
opTime.second = 0;
opTime.minute++;
nextMinute = 1;
}
if (opTime.minute >= 60) {
opTime.minute = 0;
opTime.hour++;
}
if (opTime.hour >= 24) {
opTime.hour = 0;
}
}
ISR(TIMER0_OVF_vect) {
static uint8_t subDivTack = 0;
subDivTack++;
if (subDivTack >= SUB_DIV_LED) {
subDivTack = 0;
tack = 1;
}
static uint8_t subDivStepper = 0;
subDivStepper++;
if (subDivStepper >= SUB_DIV_STEPPER) {
subDivStepper = 0;
step = 1;
}
}
opTime_t clockGetOpTime() {
return opTime;
}
void clockSetUseLocalClock(uint8_t x) {
useLocalClock = x;
}
void clockSetClock(uint8_t year, uint8_t month, uint8_t day, uint8_t weekday, uint8_t hour, uint8_t minute) {
cli();
clock.year = year;
clock.month = month;
clock.day = day;
clock.weekday = weekday;
clock.hour = hour;
clock.minute = minute;
sei();
}
void clockClearSecond() {
cli();
clock.second = 0;
sei();
}
clock_t clockGetClock() {
cli();
clock_t c = clock;
sei();
return c;
}
uint8_t clockNextSecond() {
if (nextSecond != 0) {
nextSecond = 0;
return 1;
} else {
return 0;
}
}
uint8_t clockNextMinute() {
if (nextMinute != 0) {
nextMinute = 0;
return 1;
} else {
return 0;
}
}
uint8_t clockNextStep() {
if (step != 0) {
step = 0;
return 1;
} else {
return 0;
}
}
uint8_t clockNextBlink() {
if (tack != 0) {
tack = 0;
return 1;
} else {
return 0;
}
}