/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */


#include <eCxx/eCxx.h>

#include "../AVR_Common.h"


//
// Check the MCU
//
#ifndef __AVR_ARCH_X__
#error "this test application is meant for AVRX platform only"
#endif


//
// For convenience
//
using TCB = eCxx::TimerCounterB;


//
// The init function
//
void eCxx_user_init()
{
    // Initialize application
    initBasicAVRApp();

    // Initialize UART
    App::uart().begin(9600);

    // Initialize TCB1
    auto& tcb1 = *App::tcb1();

    tcb1.setClock(TCB::ClockSource::Peripheral2);
    tcb1.setMode(TCB::Mode::PWM8);
    tcb1.setPMOutput(TCB::PWMOutput::Alternate);
    tcb1.setPWMPeriodAndDutyCycle(255, 255 / 3); // ~31 kHz with ~33% duty cycle (at 16 MHz F_CPU)
    tcb1.start();

    // Initialize TCB2
    auto& tcb2 = *App::tcb2();

    tcb2.setClock(TCB::ClockSource::Peripheral2);
    tcb2.setMode(TCB::Mode::PeriodicInterrupt);
    tcb2.setPeriod(65535); // ~122 Hz (at 16 MHz F_CPU)
    tcb2.setPMOutput(TCB::PWMOutput::Alternate);
    tcb2.attachInterrupt( +[]() {
        static uint8_t delay = 0;
        ++delay;
        if(delay > 122) {
            delay = 0;
            App::uart().writeStringln( PGM_STR("TCB2 periodic interrupt!") );
        }
    } );
    tcb2.start();
}


//
// The task function
//
void eCxx_user_task()
{
    // Process event
    App::processEvent();
}
