/*
 * PI-AR035-F1-1 / XC7A35T CVE2 EP12: 数字示波器 + 硬件 FIR/FFT 软硬对比
 *
 * 数据流：DDS 正弦（默认 1 kHz @ fs 100 kHz）-> 1024 点采集缓冲
 *        -> 硬件 32 抽头 FIR / 1024 点 FFT；CVE2 在同一批样本上复算，
 *        打印波形、谱线、软硬误差和周期数。
 *
 * UART 115200 8N1，行格式：
 *   EP12 ...
 *   S <k> <swmag> <hwmag>         k = 0..63
 *   W <n> <sample>                n = 0..31，原始波形前 32 点
 *   FIR <n> <hw> <sw> <diff>      前 32 点 FIR 对比
 */
#include <stdint.h>

#define DSP_EXP        (*(volatile unsigned int  *)0x40060034u)
#define UART_TX        (*(volatile unsigned char *)0x10000000u)
#define UART_STATUS    (*(volatile unsigned int  *)0x10000004u)

#define DSP_ID         (*(volatile unsigned int  *)0x40060000u)
#define DSP_CTRL       (*(volatile unsigned int  *)0x40060004u)
#define DSP_NCO        (*(volatile unsigned int  *)0x40060008u)
#define DSP_FSDIV      (*(volatile unsigned int  *)0x4006000Cu)
#define DSP_CAP        (*(volatile unsigned int  *)0x40060010u)
#define DSP_STATUS     (*(volatile unsigned int  *)0x40060014u)
#define DSP_FIR        (*(volatile unsigned int  *)0x40060018u)
#define DSP_FIR_LAT    (*(volatile unsigned int  *)0x4006001Cu)
#define DSP_SPEC       (*(volatile unsigned int  *)0x40060020u)
#define DSP_FFT_CYC    (*(volatile unsigned int  *)0x40060024u)
#define DSP_CYC        (*(volatile unsigned int  *)0x40060028u)
#define DSP_XADC       (*(volatile unsigned int  *)0x4006002Cu)

#define CTRL_DDS       (1u << 0)
#define CTRL_ARM       (1u << 1)
#define CTRL_FIR       (1u << 2)
#define CTRL_FFT       (1u << 3)
#define CTRL_XADC      (1u << 4)

#define ST_CAP_DONE    (1u << 0)
#define ST_FFT_DONE    (1u << 1)
#define ST_FFT_OVFL    (1u << 2)
#define ST_XADC_VALID  (1u << 3)

#define NSAMP 1024

static short cap[NSAMP];

/* cos(i*pi/512) * 32767, i = 0..255 */
static const short cos_lut[256] = {
    32767, 32766, 32765, 32761, 32757, 32752, 32745, 32737, 32728, 32717, 32705, 32692,
    32678, 32663, 32646, 32628, 32609, 32589, 32567, 32545, 32521, 32495, 32469, 32441,
    32412, 32382, 32351, 32318, 32285, 32250, 32213, 32176, 32137, 32098, 32057, 32014,
    31971, 31926, 31880, 31833, 31785, 31736, 31685, 31633, 31580, 31526, 31470, 31414,
    31356, 31297, 31237, 31176, 31113, 31050, 30985, 30919, 30852, 30783, 30714, 30643,
    30571, 30498, 30424, 30349, 30273, 30195, 30117, 30037, 29956, 29874, 29791, 29706,
    29621, 29534, 29447, 29358, 29268, 29177, 29085, 28992, 28898, 28803, 28706, 28609,
    28510, 28411, 28310, 28208, 28105, 28001, 27896, 27790, 27683, 27575, 27466, 27356,
    27245, 27133, 27019, 26905, 26790, 26674, 26556, 26438, 26319, 26198, 26077, 25955,
    25832, 25708, 25582, 25456, 25329, 25201, 25072, 24942, 24811, 24680, 24547, 24413,
    24279, 24143, 24007, 23870, 23731, 23592, 23452, 23311, 23170, 23027, 22884, 22739,
    22594, 22448, 22301, 22154, 22005, 21856, 21705, 21554, 21403, 21250, 21096, 20942,
    20787, 20631, 20475, 20317, 20159, 20000, 19841, 19680, 19519, 19357, 19195, 19032,
    18868, 18703, 18537, 18371, 18204, 18037, 17869, 17700, 17530, 17360, 17189, 17018,
    16846, 16673, 16499, 16325, 16151, 15976, 15800, 15623, 15446, 15269, 15090, 14912,
    14732, 14553, 14372, 14191, 14010, 13828, 13645, 13462, 13279, 13094, 12910, 12725,
    12539, 12353, 12167, 11980, 11793, 11605, 11417, 11228, 11039, 10849, 10659, 10469,
    10278, 10087, 9896, 9704, 9512, 9319, 9126, 8933, 8739, 8545, 8351, 8157,
    7962, 7767, 7571, 7375, 7179, 6983, 6786, 6590, 6393, 6195, 5998, 5800,
    5602, 5404, 5205, 5007, 4808, 4609, 4410, 4210, 4011, 3811, 3612, 3412,
    3212, 3012, 2811, 2611, 2410, 2210, 2009, 1809, 1608, 1407, 1206, 1005,
    804, 603, 402, 201
};

static const int coef[16] = {
    24, 29, 7, -48, -100, -67, 95, 284,
    276, -82, -626, -846, -207, 1386, 3353, 4713
};

static void putc_(char c)
{
    while (UART_STATUS & 1u)
        ;
    UART_TX = (unsigned char)c;
}

static void puts_(const char *s)
{
    while (*s) putc_(*s++);
}

static void putdec(int v)
{
    char buf[12];
    int i = 0;
    unsigned int u;
    if (v < 0) { putc_('-'); u = (unsigned int)(-v); }
    else       { u = (unsigned int)v; }
    if (u == 0u) { putc_('0'); return; }
    while (u && i < 10) { buf[i++] = (char)('0' + (u % 10u)); u /= 10u; }
    while (i > 0) putc_(buf[--i]);
}

static void putsp(void) { putc_(' '); }

/* cos(x) with x in [0,1024) = [0,2*pi) */
static int cos_q14(int idx)
{
    int q, off, v;
    idx &= 1023;
    q = idx >> 8;
    off = idx & 255;
    switch (q) {
    case 0:  v =  cos_lut[off]; break;
    case 1:  v = -cos_lut[255 - off]; break;
    case 2:  v = -cos_lut[off]; break;
    default: v =  cos_lut[255 - off]; break;
    }
    return v;
}

/* |re|+|im| style magnitude estimate to avoid sqrt */
static unsigned int mag_est(int re, int im)
{
    unsigned int a = (re < 0) ? (unsigned int)(-re) : (unsigned int)re;
    unsigned int b = (im < 0) ? (unsigned int)(-im) : (unsigned int)im;
    unsigned int lo = (a < b) ? a : b;
    unsigned int hi = (a < b) ? b : a;
    return hi + ((3u * lo) >> 3);
}

int main(void)
{
    int i, k, n;
    unsigned int t0, t1;
    int maxdiff = 0, worst = 0;
    unsigned int peak = 0, peak_bin = 0;
    unsigned int bexp = 0;

    puts_("\r\nEP12 digital scope / FIR+FFT bench\r\n");
    puts_("ID="); putdec((int)(DSP_ID & 0xFFFFu)); putc_('\r'); putc_('\n');

    DSP_FSDIV = 499u;          /* 50 MHz / 500 = 100 kHz */
    DSP_NCO   = 0x028F5C29u;   /* 1 kHz at fs = 100 kHz (0.01 * 2^32) */

    puts_("fs="); putdec(100000); puts_(" Hz  f0="); putdec(1000); puts_(" Hz\r\n");

    /* ---------- capture + hardware FIR ---------- */
    DSP_CTRL = CTRL_DDS | CTRL_ARM | CTRL_FIR;
    while ((DSP_STATUS & ST_CAP_DONE) == 0u)
        ;

    for (i = 0; i < NSAMP; i++) {
        unsigned int w = DSP_CAP;              /* auto-incrementing read port */
        cap[i] = (short)(w & 0xFFFFu);
    }

    /* software FIR on the same samples; compare with the hardware chain */
    for (i = 0; i < 32; i++) {
        int hw = (int)(DSP_FIR & 0xFFFFFFu);
        if (hw & 0x800000) hw |= (int)0xFF000000;
        puts_("FIR "); putdec(i); putsp();
        putdec(hw); putsp();

        int sw = 0;
        if (i >= 1) {
            int j, acc = 0;
            // hardware y[n] = sum c[j]*x[n-1-j] (one sample pipeline delay),
            // full-precision accumulate then a single >>14 (no per-tap truncation)
            for (j = 0; j < 32; j++) {
                int idx = i - 1 - j;
                int x = (idx < 0) ? 0 : (int)cap[idx];
                acc += x * coef[(j < 16) ? j : (31 - j)];
            }
            sw = acc >> 14;
        }
        putdec(sw); putsp();
        int d = hw - sw;
        if (d < 0) d = -d;
        putdec(d); puts_("\r\n");
        if (d > maxdiff) { maxdiff = d; worst = i; }
    }

    puts_("FIR lat="); putdec((int)DSP_FIR_LAT); puts_(" clk  maxdiff=");
    putdec(maxdiff); puts_(" @"); putdec(worst); puts_("\r\n");

    /* ---------- raw waveform (first 32 samples) ---------- */
    for (i = 0; i < 32; i++) {
        puts_("W "); putdec(i); putsp(); putdec((int)cap[i]); puts_("\r\n");
    }

    /* ---------- hardware FFT ---------- */
    t0 = DSP_CYC;
    DSP_CTRL = CTRL_DDS | CTRL_FIR | CTRL_FFT;
    while ((DSP_STATUS & ST_FFT_DONE) == 0u)
        ;
    t1 = DSP_CYC;
    bexp = DSP_EXP & 31u;
    puts_("FFT done, cycles="); putdec((int)(t1 - t0));
    puts_(" hw_cycles="); putdec((int)DSP_FFT_CYC); puts_(" exp="); putdec(bexp);
    if (DSP_STATUS & ST_FFT_OVFL) puts_(" OVERFLOW");
    puts_("\r\n");

    /* ---------- software 64-bin DFT vs hardware spectrum ---------- */
    puts_("S k swmag hwmag\r\n");
    for (k = 0; k < 64; k++) {
        int re = 0, im = 0;
        for (n = 0; n < NSAMP; n++) {
            int idx = (k * n) & 1023;
            int x = (int)cap[n];
            re += (x * cos_q14(idx)) >> 14;
            im += (x * cos_q14((idx + 768) & 1023)) >> 14;
        }
        unsigned int swm = mag_est(re, im);
        unsigned int hw = DSP_SPEC;            /* {im[15:0], re[15:0]} */
        int hre = (short)(hw & 0xFFFFu);
        int him = (short)((hw >> 16) & 0xFFFFu);
        unsigned int hwm = mag_est(hre, him) << bexp;

        puts_("S "); putdec(k); putsp();
        putdec((int)swm); putsp(); putdec((int)hwm); puts_("\r\n");

        if (hwm > peak) { peak = hwm; peak_bin = (unsigned int)k; }
    }

    puts_("HWP peak bin="); putdec((int)peak_bin); puts_(" mag="); putdec((int)peak); puts_("\r\n");
    puts_("TRAP="); putdec(0); puts_(" done\r\n");

    while (1)
        ;
    return 0;
}
