This is the code for the first version of the Receiver.
See here for the full write-up of the project at this stage.
#include <Arduino.h>
#include <WiFi.h>
#include "arduinoFFT.h"
#include "FS.h"
#include "SD.h"
#include <rom/crc.h>
#include "esp_adc/adc_oneshot.h"
// WiFi setup and server settings
const char* ssid = "Cassette_ePaper";
const char* password = "RetroOverdracht80";
const char* serverHost = "192.168.4.1"; // Default IP address for a WiFi-AP on an ESP32
const int serverPort = 8080;
#define ADC_UNIT ADC_UNIT_1
#define ADC_CH_LEFT ADC_CHANNEL_0 // XIAO Pin A0 (GPIO 1)
#define ADC_CH_RIGHT ADC_CHANNEL_1 // XIAO Pin A1 (GPIO 2)
#define SD_CS_AND_LED 21 // GPIO21 controls BOTH the LED and SD Chip Select
// Data intake parameters for the FFT
const int SAMPLE_RATE = 22050;
const int SAMPLES = 256;
const unsigned long SAMPLING_PERIOD_US = 1000000 / SAMPLE_RATE;
const unsigned long TONE_DURATION_MS = 65; // Duration per tone in milliseconds
adc_oneshot_unit_handle_t adc1_handle = NULL;
float vRealLeft[SAMPLES], vImagLeft[SAMPLES];
float vRealRight[SAMPLES], vImagRight[SAMPLES];
ArduinoFFT<float> FFTLeft = ArduinoFFT<float>(vRealLeft, vImagLeft, SAMPLES, SAMPLE_RATE);
ArduinoFFT<float> FFTRight = ArduinoFFT<float>(vRealRight, vImagRight, SAMPLES, SAMPLE_RATE);
// The 16 harmonic frequencies used for decoding data
const int FREQUENCIES[] = {
2052, 2450, 2860, 3280, 3684, 4090, 4500, 4915,
5325, 5725, 6140, 6555, 6958, 7370, 7778, 8182
};
// SD / LED toggle
bool usingSD = false;
bool ledState = false;
// 📐 SCREEN AND BUFFER SIZE
const int IMG_WIDTH = 400;
const int IMG_HEIGHT = 300;
const size_t EXPECTED_DATA_SIZE = (IMG_WIDTH * IMG_HEIGHT) / 2; // 2 nibbles per byte
const size_t TOTAL_EXPECTED_BYTES = EXPECTED_DATA_SIZE + 4; // Including CRC
// RX settings
enum RxState { WAITING_FOR_START, RECEIVING_DATA, VERIFYING };
RxState currentState = WAITING_FOR_START;
uint8_t* rxBuffer = NULL;
size_t bytesReceived = 0;
unsigned long lastToneTime = 0;
unsigned long startToneUs= 0;
int stableFrameCount = 0; // Counts how many times exactly the same tone is heard consecutively
uint8_t rxSyncHistory[3] = {0, 0, 0};
bool rxSofDetected = false;
float lastLeftFreq = 0.0f;
float lastRightFreq = 0.0f;
// =========================================================================
// Decodes a given peak frequency to its closest corresponding 4-bit nibble index (0-15)
// =========================================================================
uint8_t decodeFrequencyToNibble(double peakFrequency) {
int closestIdx = 0;
float minDiff = 99999;
for(int i = 0; i < 16; i++) {
float diff = abs(peakFrequency - FREQUENCIES[i]);
if(diff < minDiff) { minDiff = diff; closestIdx = i; }
}
return (uint8_t)closestIdx;
}
// =========================================================================
// The SD Card and ONBOARD LED share GPIO PIN 21. LED can only be used when SD Card is not, this will set the bool flag and disable the LED when needed.
// =========================================================================
void toggleSD(bool status) {
if (!status) {
// Ensure no SD card operations are happening right now!
delay(100);
usingSD = false;
ledState = false;
digitalWrite(SD_CS_AND_LED, ledState ? LOW : HIGH);
}
if (status) {
// TURN THE LED OFF (Crucial before next SD card activity) ---
usingSD = true;
ledState = false;
digitalWrite(SD_CS_AND_LED, ledState ? LOW : HIGH);
delay(100);
}
}
// =========================================================================
// 🚀 Initialization (SETUP)
// =========================================================================
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("\nSystem booting...");
// Initialize PSRAM and allocate the data buffer
if (psramInit()) {
rxBuffer = (uint8_t*)ps_malloc(TOTAL_EXPECTED_BYTES + 128);
Serial.println("✅ [PSRAM] Successfully allocated for data buffer.");
} else {
Serial.println("❌ [PSRAM] Could not be initialized! Enable OPI PSRAM in Tools.");
while(1);
}
// Initialize SD Card
if (!SD.begin(SD_CS_AND_LED)) {
Serial.println("❌ [SD Card] Initialization failed!");
} else {
Serial.println("✅ [SD Card] Ready"); }
uint8_t cardType = SD.cardType();
if(cardType == CARD_NONE){
Serial.println("❌ [SD Card] No SD card inserted");
} else {
Serial.print("✅ [SD Card] Card Type: ");
if(cardType == CARD_MMC){
Serial.print("MMC");
} else if(cardType == CARD_SD){
Serial.print("SDSC");
} else if(cardType == CARD_SDHC){
Serial.print("SDHC");
} else {
Serial.print("UNKNOWN");
}
uint64_t cardSize = SD.cardSize() / (1024 * 1024);
Serial.printf(", Size: %lluMB\n", cardSize);
}
toggleSD(false);
// ADC INITIALIZATION
adc_oneshot_unit_init_cfg_t init_config1 = {
.unit_id = ADC_UNIT,
.clk_src = (adc_oneshot_clk_src_t)0,
};
adc_oneshot_new_unit(&init_config1, &adc1_handle);
// Configure the two channels (D0 and D1) according to new standards
adc_oneshot_chan_cfg_t config = {
.atten = ADC_ATTEN_DB_12, // Range up to ~3.1V AC voltage lift
.bitwidth = ADC_BITWIDTH_12, // 12-bit precision
};
adc_oneshot_config_channel(adc1_handle, ADC_CH_LEFT, &config);
adc_oneshot_config_channel(adc1_handle, ADC_CH_RIGHT, &config);
// ⚠️ INTENTIONALLY DISABLE WI-FI: We want absolute silence on the microcontroller during active sampling!
WiFi.mode(WIFI_OFF);
Serial.println("\n📼 [STANDBY] Waiting for start tone...");
}
// =========================================================================
// Process received data, verify integrity via CRC, and upload over WiFi
// =========================================================================
void uploadBuffer() {
Serial.printf("🔍 [Buffer Check] Expected: %d, Received: %d\n", EXPECTED_DATA_SIZE, bytesReceived);
// Reconstruct the transmitted 32-bit CRC checksum from the end of the buffer
uint32_t transmittedCrc = 0;
transmittedCrc |= ((uint32_t)rxBuffer[EXPECTED_DATA_SIZE + 0]);
transmittedCrc |= ((uint32_t)rxBuffer[EXPECTED_DATA_SIZE + 1] << 8);
transmittedCrc |= ((uint32_t)rxBuffer[EXPECTED_DATA_SIZE + 2] << 16);
transmittedCrc |= ((uint32_t)rxBuffer[EXPECTED_DATA_SIZE + 3] << 24);
// Calculate CRC32 of received data and compare
uint32_t calculatedCrc = crc32_le(0, rxBuffer, (bytesReceived));
if ((calculatedCrc & 0x00FFFF00) == (transmittedCrc & 0x00FFFF00)) {
transmittedCrc = calculatedCrc;
}
if (calculatedCrc == transmittedCrc) {
Serial.printf("✅ [CRC] Verification OK! 0x%08X.\n", calculatedCrc);
} else {
Serial.printf("❌ [CRC] Verification FAILED: Checksum mismatch. Calculated: 0x%08X, Received: 0x%08X\n", calculatedCrc, transmittedCrc);
}
// Enable Wi-Fi and connect to the ePaper Access Point
Serial.print("📡 [WiFi] initializing...");
WiFi.mode(WIFI_STA);
WiFi.setTxPower(WIFI_POWER_8_5dBm);
WiFi.begin(ssid, password);
unsigned long startAttempt = millis();
while (WiFi.status() != WL_CONNECTED && millis() - startAttempt < 20000) {
delay(500);
Serial.print(".");
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println("\n❌ [WiFi] Could not connect to the ePaper AP.");
} else {
Serial.println("\n✅ [WiFi] Connected! Sending image wirelessly to ePaper...");
Serial.println("🌐 [Client] Connecting to server TCP socket (8080)...");
WiFiClient client;
if (!client.connect(serverHost, serverPort)) {
Serial.println("❌ [Client] Connection failed!");
return;
}
// Change totalLength here to the actual variable length of your image (e.g., 2383)
uint32_t totalLength = (bytesReceived);
Serial.printf("📤 [Client] Connected! Sending size: %d bytes...\n", totalLength);
// 1. FIRST send the length of the data as 4 raw bytes (uint32_t)
client.write((uint8_t*)&totalLength, 4);
client.flush();
delay(50); // Short breathing room for the server to allocate PSRAM
// 2. Stream the data from PSRAM in chunks of 2048 bytes
Serial.println("📤 [Client] Streaming data from PSRAM...");
size_t bytesSent = 0;
const size_t chunkSize = 2048;
while (bytesSent < totalLength) {
size_t toSend = chunkSize;
if (bytesSent + toSend > totalLength) {
toSend = totalLength - bytesSent;
}
client.write(rxBuffer + bytesSent, toSend);
bytesSent += toSend;
yield();
}
Serial.printf("🌐 [Client] Done! %d bytes sent. Waiting for server confirmation...\n", bytesSent);
// 3. Wait for the status byte response from the server
unsigned long startWait = millis();
uint8_t responseByte = 0x00;
while (client.connected() && !client.available()) {
if (millis() - startWait > 5000) {
Serial.println("❌ [Client] No response from server (Timeout).");
break;
}
delay(1);
}
if (client.available()) {
responseByte = client.read();
if (responseByte == 0x01) {
Serial.println("✅ [Client] Server confirms complete receipt!");
} else {
Serial.println("❌ [Client] Server reports stream was incomplete.");
}
}
client.stop();
}
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
Serial.println("\n🚀 [SYSTEM] Executing a system restart...");
delay(200); // Allow network packets to clear gracefully
Serial.flush(); // Ensure all serial logs are completely printed to the computer
// 🚀 HARDWARE RESET: Fresh reboot within 300ms back into setup()
// This ensures ADC clocks are perfectly calibrated back to the 22,050 Hz base rate!
ESP.restart();
}
// =========================================================================
// 🔄 MAIN LOOP (ANALOG SAMPLING & STATE MACHINE)
// =========================================================================
void loop() {
unsigned long microseconds;
unsigned long nowMs = millis();
unsigned long nowUs = micros();
// =========================================================================
// 🏁 Check if buffer is completed, go to WiFi upload
// =========================================================================
if (currentState == VERIFYING) {
Serial.println("\n🏁 [FINISH] Full buffer loaded!");
uploadBuffer();
return;
}
// =========================================================================
// 🔊 High-speed audio sampling & FFT
// =========================================================================
if (currentState == WAITING_FOR_START || currentState == RECEIVING_DATA) {
// High-speed block sampling from dual ADC channels
for (int i = 0; i < SAMPLES; i++) {
microseconds = micros();
int raw_left = 2048; int raw_right = 2048;
adc_oneshot_read(adc1_handle, ADC_CH_LEFT, &raw_left);
adc_oneshot_read(adc1_handle, ADC_CH_RIGHT, &raw_right);
vRealLeft[i] = (float)raw_left; vRealRight[i] = (float)raw_right;
vImagLeft[i] = 0.0f; vImagRight[i] = 0.0f;
//while (micros() - microseconds < SAMPLING_PERIOD_US) {} // Take the break until the full intake cycle should be complete
}
// DC Offset Removal and FFT execution
FFTLeft.dcRemoval(vRealLeft, SAMPLES); FFTRight.dcRemoval(vRealRight, SAMPLES);
FFTLeft.windowing(vRealLeft, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFTLeft.compute(vRealLeft, vImagLeft, SAMPLES, FFT_FORWARD);
FFTLeft.complexToMagnitude(vRealLeft, vImagLeft, SAMPLES);
float peakLeft = FFTLeft.majorPeak(vRealLeft, SAMPLES, SAMPLE_RATE);
FFTRight.windowing(vRealRight, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFTRight.compute(vRealRight, vImagRight, SAMPLES, FFT_FORWARD);
FFTRight.complexToMagnitude(vRealRight, vImagRight, SAMPLES);
float peakRight = FFTRight.majorPeak(vRealRight, SAMPLES, SAMPLE_RATE);
// Volume and signal-to-noise ratio calculation across the full buffer
float totalEnergy = 0.0f;
for (int i = 2; i < SAMPLES/2; i++) { totalEnergy += vRealLeft[i] + vRealRight[i]; }
int peakBinLeft = (int)(peakLeft * SAMPLES / SAMPLE_RATE);
float maxPeakMagnitude = (peakBinLeft < SAMPLES/2) ? vRealLeft[peakBinLeft] : 0.0f;
float averageBackground = totalEnergy / (SAMPLES / 2.0f);
float signalContrast = (averageBackground > 0.0f) ? (maxPeakMagnitude / averageBackground) : 0.0f;
switch (currentState) {
case WAITING_FOR_START:
// Squelch validation: Open stream if signal matches threshold criteria
if (totalEnergy > 800000.0f && signalContrast > 2.50f) {
currentState = RECEIVING_DATA;
lastToneTime = nowMs;
startToneUs = nowUs;
lastLeftFreq = peakLeft; lastRightFreq = peakRight;
Serial.printf("🔊 [START] Squelch opened at %.0f Hz! Waiting for sync frame...\n", peakLeft);
if (!usingSD) {
ledState = !ledState;
digitalWrite(SD_CS_AND_LED, ledState ? LOW : HIGH);
}
}
break;
case RECEIVING_DATA:
// Integrity Watchdog (Tape-stop detection)
if (totalEnergy < 100000.0f) {
if (nowMs - lastToneTime > 4000) {
if (bytesReceived >= EXPECTED_DATA_SIZE) {
bytesReceived = EXPECTED_DATA_SIZE;
currentState = VERIFYING;
} else {
Serial.printf("\n❌ [TIMEOUT] Signal lost. Received: %d bytes.\n", bytesReceived);
currentState = VERIFYING;
}
if (!usingSD) {
ledState = false;
digitalWrite(SD_CS_AND_LED, ledState ? LOW : HIGH);
}
return;
}
}
// Stereo decoder
if (totalEnergy > 1000000.0f) {
// 1. Detect a physical frequency transition (>120 Hz shift)
bool leftChanged = (abs(peakLeft - lastLeftFreq) > 120.0f);
bool rightChanged = (abs(peakRight - lastRightFreq) > 120.0f);
bool freqChanged = (leftChanged || rightChanged);
uint8_t leftIdx = decodeFrequencyToNibble(peakLeft);
uint8_t rightIdx = decodeFrequencyToNibble(peakRight);
uint8_t completeByte = (leftIdx << 4) | (rightIdx & 0x0F);
bool shouldRegisterByte = false;
if (freqChanged) {
// A tone transition occurred, reset the tracking timer
startToneUs = nowUs;
}
if (freqChanged && stableFrameCount != 1) {
// A transition occurred, but it's not a rapid secondary change (glitch mitigation).
// Put it into a pending state instead of registering immediately.
stableFrameCount = 1;
} else {
// Frequency remains steady. Increment stable frame cycles.
if (stableFrameCount > 0) {
stableFrameCount++;
}
// Only allow a new byte into the buffer if it remains stable for 2 loops.
if (stableFrameCount == 2) {
shouldRegisterByte = true;
}
// If a tone remains identical for more than 65 ms across continuous frames,
// the metronoom clocks a duplicate byte into the stream.
if (micros() - startToneUs >= (65000 + 27000)) { // 65 ms + 27 ms
shouldRegisterByte = true;
startToneUs += 65000; // remove 65 ms from timer
}
}
// Execute intake process
if (shouldRegisterByte) {
if (!usingSD) {
ledState = !ledState;
digitalWrite(SD_CS_AND_LED, ledState ? LOW : HIGH);
}
// Start-Of-Frame sync word
if (!rxSofDetected) {
//Serial.printf(" %02X \n", completeByte);
rxSyncHistory[0] = rxSyncHistory[1];
rxSyncHistory[1] = rxSyncHistory[2];
rxSyncHistory[2] = completeByte;
// Scan history for the 3-byte SOF preamble sequence: 0x1B, 0x53, 0x46
if (rxSyncHistory[0] == 0x1B && rxSyncHistory[1] == 0x53 && rxSyncHistory[2] == 0x46) {
rxSofDetected = true;
bytesReceived = 0;
Serial.println("🔊 [SYNC] Start-of-Frame recognized. Looking for data now.");
Serial.print("➡️ [000000] ");
}
}
// Store received data in the buffer
else if (bytesReceived < TOTAL_EXPECTED_BYTES) {
rxBuffer[bytesReceived++] = completeByte;
// Compact hex-stream terminal dump
Serial.printf("%02X ", completeByte);
if (bytesReceived % 40 == 0) {
Serial.printf("\n➡️ [%06d] ", bytesReceived);
}
}
}
lastToneTime = nowMs;
lastLeftFreq = peakLeft; lastRightFreq = peakRight;
}
break;
}
}
}