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


//
// Pin numbers
//
static constexpr eCxx::uint8_t DATA  = 8;
static constexpr eCxx::uint8_t SHIFT = 7;
static constexpr eCxx::uint8_t LATCH = 4;


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

    // Set pin modes for driving the 7-segments
    App::setPinMode(DATA,  App::PinMode::Output);
    App::setPinMode(SHIFT, App::PinMode::Output);
    App::setPinMode(LATCH, App::PinMode::Output);
}


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

    // Shift out data to the 7-segments
    // 0      1      2      3      4      5      6      7      8      9      Off
    // 0xC0   0xF9   0xA4   0xB0   0x99   0x92   0x82   0xF8   0x80   0x90   0xFF
    App::shiftOut( DATA, SHIFT, eCxx::ActiveClockEdge::Rising, LATCH, eCxx::ActiveState::High, eCxx::BitOrder::MSBFirst, eCxx::makeArray<eCxx::uint8_t, 0xC0, 0x01>() );
    App::shiftOut( DATA, SHIFT, eCxx::ActiveClockEdge::Rising, LATCH, eCxx::ActiveState::High, eCxx::BitOrder::MSBFirst, eCxx::makeArray<eCxx::uint8_t, 0xF9, 0x02>() );
    App::shiftOut( DATA, SHIFT, eCxx::ActiveClockEdge::Rising, LATCH, eCxx::ActiveState::High, eCxx::BitOrder::MSBFirst, eCxx::makeArray<eCxx::uint8_t, 0xA4, 0x04>() );
    App::shiftOut( DATA, SHIFT, eCxx::ActiveClockEdge::Rising, LATCH, eCxx::ActiveState::High, eCxx::BitOrder::MSBFirst, eCxx::makeArray<eCxx::uint8_t, 0xB0, 0x08>() );
    App::shiftOut( DATA, SHIFT, eCxx::ActiveClockEdge::Rising, LATCH, eCxx::ActiveState::High, eCxx::BitOrder::MSBFirst, eCxx::makeArray<eCxx::uint8_t, 0xFF, 0x08>() );
}
