/*
 * 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"


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

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


//
// The task function
//
void eCxx_user_task()
{
    // Process event and delay
    static eCxx::uint32_t prvMillis = 0;
           eCxx::uint32_t curMillis = App::processEvent();
    if(curMillis - prvMillis < 1000) return;
    else                             prvMillis = curMillis;

    // Measure temperature using ADC
    const eCxx::uint16_t temp = App::analogRead(eCxx::AVR::A_TempSenseK);

    // Measure the bandgap reference voltage using ADC (assume AVCC reference voltage)
#ifndef __AVR_ARCH_X__
    const eCxx::uint16_t vref = ( static_cast<eCxx::uint32_t>( App::analogRead(eCxx::AVR::A_Bandgap) ) * 500 ) >> 10;
#else
    const eCxx::uint16_t vref = ( static_cast<eCxx::uint32_t>( App::analogRead(eCxx::AVR::A_DACRef0) ) * 500 ) >> 10;
#endif

    // Print result to UART
    auto& uart = App::uart();

    uart.writeString   ( PGM_STR("Temperature = ")                   );
    uart.writeDecString( temp, 5, eCxx::Convert::NumSign::None_Minus );
    uart.writeStringln ( PGM_STR(" K")                               );

    uart.writeString   ( PGM_STR("V-Reference = ")                   );
    uart.writeDecString( vref, 5, eCxx::Convert::NumSign::None_Minus );
    uart.writeStringln ( PGM_STR(" V")                               );

    uart.write('\n');
}
