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


#include <eCxx/eCxx_InputDevice.h>

#include "AVR_Common.h"


//
// Pin numbers
//
static constexpr eCxx::uint8_t AXIS_1 = eCxx::AVR::A0;
static constexpr eCxx::uint8_t AXIS_2 = eCxx::AVR::A1;
static constexpr eCxx::uint8_t SWITCH = eCxx::AVR::A3;


//
// Instantiate the joystick reader and switch debouncer
//
static eCxx::AnalogJoystick<> ajoy;  // Use the default template paramaters
static eCxx::Debounce8Switch  db8sw;


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

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

    // Initialize joystick reader
    ajoy.begin(AXIS_1, AXIS_2, SWITCH);
    ajoy.setMaxCoordinate(4000, 3000);
}


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

    // Read the joysitck
    eCxx::uint16_t a1 = 0;
    eCxx::uint16_t a2 = 0;
    bool           sw = false;

    ajoy.readCoordinates(a1, a2, sw);

    // Debounce the joystick's switch
    db8sw.debounce(sw ? 0b00000001 : 0b00000000);

    // Check if the switch is pressed
    if( !db8sw.pressed(0b00000001) ) return;

    // Write the values to UART when the switch is pressed
    auto& uart = App::uart();

    uart.writeString( PGM_STR("Axis1 = ") );
    uart.writeDecString(a1, 5);

    uart.writeString( PGM_STR("   ;   Axis2 = ") );
    uart.writeDecStringln(a2, 5);
}
