//#DOC Main, program entry and main loop
#include "main.h"

// Uncomment this define to test fast sampling
#define FAST_ACQ

#ifdef FAST_ACQ
    // Embedded memory is very fast but with very small size!
    #define SAMPLES     1024
    S16     buff[SAMPLES];
#else
    // Heap is very large but not fast!
    #define SAMPLES     100000
    S16     * buff;
#endif

otADS868x       adc;
otUSB           usb;        // Declare USB library
otDAQ           daq;        // Debug

void setup()
{
    // Init connection with the console via UART0
    UartEnableSignals(UART0);
    UartSetBaud(UART0, 115200);
    // Init stout used by printf
    setStdout(4096, UART0);   // printf output is now directed on UART0
    
    // Init the timer for time measure
    TimerSetAsCounter(TIMER0);
    TimerEnable(TIMER0, true);
    
    adc.init();
    // Set ADC range
    adc.setRange(otADS868x::BIP_12V);
    
    DelayMs(1000);
    
    // Init USB channel, the command list can accept 64 different commands
    usb.init(64);
    
    // Debug system
    daq.init(&usb);
    
#ifndef FAST_ACQ
    buff = (S16 *) _malloc(sizeof(S16) * SAMPLES);
#endif
    // Create a dialog on the desktop, the program stops until the open window is closed
    daq.pause();
    // Prepare the plot area with the respective axis names
    daq.plotOpen("DIGITAL SCOPE", "SAMPLES", "mV");
    // Creates a curve to be displayed in the plot area, a maximum of sixteen are possible ...
    daq.plotCurve(0, "CH:0");
}

void loop()
{
    // Read the ADC
    adc.read(buff, SAMPLES);
    // Handle for some local commands
    if(UartCheckChar(UART0))
    {
        U8  ch = UartChar(UART0);
        switch(ch)
        {
            case ' ':
                    daq.pause();
                    break;
        }
    }
    // Convert to mV sampled data
    for(unsigned i = 0; i < SAMPLES; i++)
        buff[i] = adc.toVolt(buff[i]) * 1000.0f;
    // Update plot with sampled data
    daq.plotUpdate(0, SAMPLES, buff);
    // Handle for USB commands
    usb.process();
}