/*
 * 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 "NodeMCU_Common.h"


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

    // There is no need to enable the 74LVC541 buffers on the eCxx NodeMCU development board because
    // the ADC pin is not (and cannot be) buffered and the UART is only used for communication with
    // the host PC

    // 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 < 500) return;
    else                            prvMillis = curMillis;

    // Read from ADC and write the result to UART
    const eCxx::uint16_t adc  = App::analogRead(eCxx::NodeMCU::A0);
          auto&          uart = App::uart();

    // NOTE : The minimum and maximum values of the input will depend on the
    //        voltage divider resistors on the development board
    const uint16_t mapped = eCxx::mapValue<uint16_t, true>(adc, 5, 855, 0, 500);
    const uint16_t whole  = mapped / 100;
    const uint16_t fract  = mapped - whole * 100;

    uart.writeDecString(whole);
    uart.write('.');
    uart.writeDecStringln(fract);
}
