/*
 * 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
//
#ifdef __AVR_ARCH_X__
#error "this test application is meant for AVR platform only"
#endif


//
// For convenience
//
using ACL = eCxx::AnalogComparatorLite;


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

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

    // Initialize analog comparator
    auto& acl = App::analogComparatorLite();

    acl.inputp = ACL::InputP::Bandgap;
    acl.inputn = ACL::InputN::ADCMux;
    acl.adcMux = 5;

    acl.attachInterrupt(
        +[]() {
            // Disable the analog comparator so that we can read the current voltage using ADC
            App::analogComparatorLite().end();
            // Read the current voltage using ADC
            const eCxx::uint32_t adcValTimes100 = (
                static_cast<eCxx::uint32_t>( App::analogRead(eCxx::AVR::A5) ) * 500 // Assume AVCC reference voltage
            ) >> 10;
            // Re-enable the analog comparator
            App::analogComparatorLite().begin();
            // Send some information via UART
            App::uart().writeString   ( PGM_STR("AC interrupt : ")                               );
            App::uart().writeDecString( eCxx::Bool( App::analogComparatorLite().getOutStatus() ) );
            App::uart().write         ( ' '                                                      );
            App::uart().write         ( '['                                                      );
            App::uart().writeDecString( adcValTimes100, 3                                        );
            App::uart().write         ( ']'                                                      );
            App::uart().write         ( '\n'                                                     );
        },
        App::InterruptMode::Change
    );

    acl.begin();
}


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