
/*
 * Copyright 2017-2024 Oleg Borodin <onborodin@gmail.com>
 */

#include <avr/interrupt.h>
#include <util/delay.h>

#include <tool.h>
#include <timer.h>

void timer0_init(void) {
    /* TCCR0A */
    /* Disable comparators */
    REG_SETDOWN_BIT(TCCR0A, COM0A1);
    REG_SETDOWN_BIT(TCCR0A, COM0A0);
    REG_SETDOWN_BIT(TCCR0A, COM0B1);
    REG_SETDOWN_BIT(TCCR0A, COM0B0);
    /* Set normal mode */
    REG_SETDOWN_BIT(TCCR0A, WGM01);
    REG_SETDOWN_BIT(TCCR0A, WGM00);

    /* TCCR0B */
    /* Set prescaler */
    REG_SETUP_BIT(TCCR0B, CS02);
    REG_SETDOWN_BIT(TCCR0B, CS01);
    REG_SETDOWN_BIT(TCCR0B, CS00);

    //REG_SETUP(TCNT0, TIMER0_PRESIZE);
    /* TIMSK0 */
    /* Enable timer interrupt */
    REG_SETUP_BIT(TIMSK0, TOIE0);
}

void timer1_init(void) {
    /* TCCR1A */
    REG_SETDOWN_BIT(TCCR1A, COM1A1);
    REG_SETDOWN_BIT(TCCR1A, COM1A0);
    REG_SETDOWN_BIT(TCCR1A, COM1B1);
    REG_SETDOWN_BIT(TCCR1A, COM1B0);
    REG_SETDOWN_BIT(TCCR1A, WGM11);
    REG_SETDOWN_BIT(TCCR1A, WGM10);

    /* TCCR1B */
    /* Disable capture noise canceler */
    REG_SETDOWN_BIT(TCCR1B, ICNC1);
    /* Set Capture Edge */
    REG_SETUP_BIT(TCCR1B, ICES1);
    /* Disable waveform generation */
    REG_SETDOWN_BIT(TCCR1B, WGM13);
    REG_SETDOWN_BIT(TCCR1B, WGM12);
    /* Set prescaler */
    REG_SETDOWN_BIT(TCCR1B, CS10);
    REG_SETUP_BIT(TCCR1B, CS11);
    REG_SETUP_BIT(TCCR1B, CS12);

    /* TIMSK1 */
    /* Disable capture interrupt */
    REG_SETDOWN_BIT(TIMSK1, ICIE1);
    /* Disable compare interrupt */
    REG_SETDOWN_BIT(TIMSK1, OCIE1B);
    REG_SETDOWN_BIT(TIMSK1, OCIE1A);
    /* ENABLE overflow interrupt */
    REG_SETUP(TCNT1, TIMER1_PRESIZE);
    REG_SETUP_BIT(TIMSK1, TOIE1);
}
