
#include <stdint.h>
#include <stdio.h>


enum {
    //_xinfreq = 20_000_000,
    _xtlfreq = 20_000_000,
    _clkfreq = 360_000_000,

    DOWNLOAD_BAUD = 230_400,
    DEBUG_BAUD = DOWNLOAD_BAUD,

    CS = 29, //Rpi24
    CLK = 26, //rpi 23
    MOSI = 25, // rpi 19
    MISO = 1,  //P24, rpi 21, 0 = MISO+1, 1 = MISO-1, pairing is required for simultaneous management

    CPOL = 1,    // 1 true, 0 false.  SPI clocking mode, invert clock polarity
    CPHA = 1,    // 1 true, 0 false   SPI clocking mode, advance clock phase 180deg
    CSPD = 0,    // 1 true, 0 false.  Requires CPHA = 1.  This is a special high speed read data
                        // control bit used when Propspi's effective clock divider is below 6.

    SPINS = CPOL<<31 | CPHA<<30 | CSPD<<29 | MISO<<28 | MOSI<<12 | CLK<<6 | CS,

    BUFFSIZE = 19200,    // bytes (in multiples of 4)
};



struct __using("pllset.spin2") lib;
struct __using("propspi2.spin2") rpi;


unsigned char sbuff[BUFFSIZE];


void  main(void) {
    _pinh(30);
    _pinh(31);

    printf( "   clkfreq = %d   clkmode = 0x%x\n", _clockfreq(), _clockmode() );

    rpi.start_propspi( SPINS, sbuff, BUFFSIZE );


    // Slave cog is ready and waiting.  At this stage the tester program has not setup any of its pins,
    // so we are going to be glitching them from the start.
    unsigned  countx = 0, lastch, t1, t2, usec;

    _pollatn();
    while (1)
    {
        _waitatn();    // detect end
        t1 = _cnt();
        _waitatn();    // detect end
        t2 = _cnt();
        lastch = sbuff[BUFFSIZE-1];
        usec = lib.muldiv65( t2 - t1, 1000000, _clockfreq() );
        countx++;
        printf( " last byte = 0x%02x   countx = %d   t2-t1 = %d us\n", lastch, countx, usec );
    }
}
