#include <stdint.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include "led.h"
#include "sleep_led.h"
#ifndef SLEEP_LED_TIMER
# define SLEEP_LED_TIMER 1
#endif
#if SLEEP_LED_TIMER == 1
# define TCCRxB TCCR1B
# define TIMERx_COMPA_vect TIMER1_COMPA_vect
# if defined(__AVR_ATmega32A__)
# define TIMSKx TIMSK
# else
# define TIMSKx TIMSK1
# endif
# define OCIExA OCIE1A
# define OCRxx OCR1A
#elif SLEEP_LED_TIMER == 3
# define TCCRxB TCCR3B
# define TIMERx_COMPA_vect TIMER3_COMPA_vect
# define TIMSKx TIMSK3
# define OCIExA OCIE3A
# define OCRxx OCR3A
#else
error("Invalid SLEEP_LED_TIMER config")
#endif
#define SLEEP_LED_TIMER_TOP F_CPU / (256 * 64)
void sleep_led_init(void) {
TCCRxB |= _BV(WGM12);
TCCRxB |= _BV(CS10);
uint8_t sreg = SREG;
cli();
OCRxx = SLEEP_LED_TIMER_TOP;
SREG = sreg;
}
void sleep_led_enable(void) {
TIMSKx |= _BV(OCIExA);
}
void sleep_led_disable(void) {
TIMSKx &= ~_BV(OCIExA);
}
void sleep_led_toggle(void) {
TIMSKx ^= _BV(OCIExA);
}
static const uint8_t breathing_table[64] PROGMEM = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 6, 10, 15, 23, 32, 44, 58, 74, 93, 113, 135, 157, 179, 199, 218, 233, 245, 252, 255, 252, 245, 233, 218, 199, 179, 157, 135, 113, 93, 74, 58, 44, 32, 23, 15, 10, 6, 4, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
ISR(TIMERx_COMPA_vect) {
static union {
uint16_t row;
struct {
uint8_t count : 8;
uint8_t duration : 2;
uint8_t index : 6;
} pwm;
} timer = {.row = 0};
timer.row++;
if (timer.pwm.count == 0) {
led_set(1 << USB_LED_CAPS_LOCK);
}
if (timer.pwm.count == pgm_read_byte(&breathing_table[timer.pwm.index])) {
led_set(0);
}
}