// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: Copyright (c) 2026 Ashwin Whitchurch, Protocentral Electronics

/*
 * 02_SingleChannel - Single-channel raw + frequency readout on CH0
 *
 * Copyright (c) 2026 Ashwin Whitchurch, Protocentral Electronics
 * Email: info@protocentral.com
 *
 * Configures the ProtoCentral FDC2214 in single-channel mode on CH0 and
 * prints the 28-bit raw conversion result alongside the corresponding sensor
 * frequency. The column header is re-printed periodically so a Serial
 * Monitor opened after upload still sees what the columns mean.
 *
 * Default I2C address on the ProtoCentral breakout is 0x2B (ADDR pulled HIGH).
 *
 * This software is licensed under the MIT License.
 */

//////////////////////////////////////////////////////////////////////////////////////////
//
//    Hardware Setup:
//      Connect your LC tank between IN0A and IN0B.
//        3.3V -> VCC
//        GND  -> GND
//        SDA  -> SDA (A4 on Uno)
//        SCL  -> SCL (A5 on Uno)
//
/////////////////////////////////////////////////////////////////////////////////////////

#include <Wire.h>
#include <Protocentral_FDC2214.h>

FDC2214 fdc;

bool     initialized       = false;
uint32_t lastInitAttemptMs = 0;
uint32_t lastHeaderMs      = 0;

void setup() {
    Serial.begin(115200);
    Wire.begin();
}

void initSensor() {
    Serial.println(F("Initializing FDC2214 on I2C 0x2B ..."));

    if (!fdc.begin()) {
        Serial.println(F("FDC2214 not found. Check wiring/power/ADDR. Retrying in 2s."));
        return;
    }

    fdc.configureDefaults();
    fdc.setActiveChannel(FDC2214_CH0);
    fdc.setAutoscan(false);
    fdc.start();

    Serial.println(F("FDC2214 started in single-channel mode (CH0)."));
    Serial.println(F("CH0 raw\tFreq (MHz)"));
    initialized   = true;
    lastHeaderMs  = millis();
}

void loop() {
    uint32_t now = millis();

    if (!initialized) {
        if (now - lastInitAttemptMs >= 2000) {
            lastInitAttemptMs = now;
            initSensor();
        }
        return;
    }

    // Re-print the column header occasionally so a late-opened Serial Monitor
    // still sees what the columns mean.
    if (now - lastHeaderMs >= 5000) {
        Serial.println(F("CH0 raw\tFreq (MHz)"));
        lastHeaderMs = now;
    }

    if (fdc.isDataReady(FDC2214_CH0)) {
        uint32_t raw = fdc.readRawChannel(FDC2214_CH0);
        float    f   = fdc.readFrequencyHz(FDC2214_CH0);

        Serial.print(raw);
        Serial.print('\t');
        Serial.println(f / 1.0e6f, 6);
    }
    delay(50);
}
