//#DOC Main, program entry and main loop
#include "main.h"
#include <otSerial.h>
#include <otTimer.h>
#include <otI2cBus.h>
#include <otFPGA.h>
#include <otMalloc.h>
#include <otPrintf.h>
#include <otLCD.h>

otLCD       lcd;

U8          perc = 0;
S8          dir = +1;

U32 counts = 0;

// For all interrupts service routine you MUST specify FAST_CODE_1 or
// FAST_CODE_2 as locator attribute!
FAST_CODE_2 void _coreTimerCallBack()
{
    counts++;
}

void setup()
{
    UartEnableSignals(UART0);
    UartSetBaud(UART0, 115200);
    setStdout(4096, UART0); // printf output is now directed on UART0
    
    I2cBusReset();
    I2cBusFrequency(800, 40);
    
    // Init FPGA
    FpgaInit();
    FpgaHiddenPort(HP_EXT_I2C, true);
    
    lcd.init(20, 4);
    lcd.backLight();
    lcd.print(4,  0, "SHARKDUINO++");
    // Create a bar graph
    lcd.bargraph(otLCD::HORIZONTAL_BAR_GRAPH);
    
    // Prescaler action 400MHz / 40 (39+1) = 10MHz (100ns)
    // Period: 10000000 * 100ns = 1.0s
    CoreTimerSetInterruptService(39, 10000000, true, _coreTimerCallBack);
    CoreTimerEnable(true);
}

void loop()
{
    // Create an animation with numbers and graphs
    lcd.drawHorizontalGraph(2, 0, 20, (U8) (100 - perc));
    lcd.drawHorizontalGraph(3, 0, 20, perc);
    lcd.print(0, 1, "%3d %% -------- %5u", (S32) perc, counts);
    perc += dir;
    if(perc == 99) dir *= -1;
    if(perc == 0) dir *= -1;
}