Index: AD5941_interface09302025/ad5941_library_extension.cpp =================================================================== diff -u -r155b2459fb174d166376c729458e8d3881e65f9b -r6dc43c82214e34a1441f4f8b3210104d3d08d36b --- AD5941_interface09302025/ad5941_library_extension.cpp (.../ad5941_library_extension.cpp) (revision 155b2459fb174d166376c729458e8d3881e65f9b) +++ AD5941_interface09302025/ad5941_library_extension.cpp (.../ad5941_library_extension.cpp) (revision 6dc43c82214e34a1441f4f8b3210104d3d08d36b) @@ -33,6 +33,32 @@ } #include +// Stores the instance of currently connected / detected Serial port +Stream* activeSerial = nullptr; + +Stream* serialPorts[] = { + &Serial, // USB virtual serial + &Serial1, // pins 0, 1 + &Serial2, // pins 7, 8 + &Serial3, // pins 14, 15 + &Serial4, // pins 16, 17 + &Serial5, // pins 21, 20 + &Serial6, // pins 24, 25 + &Serial7 // pins 28, 29 +}; + +const char* serialNames[] = { + "Serial (USB)", + "Serial1 (pins 0,1)", + "Serial2 (pins 7,8)", + "Serial3 (pins 14,15)", + "Serial4 (pins 16,17)", + "Serial5 (pins 21,20)", + "Serial6 (pins 24,25)", + "Serial7 (pins 28,29)" +}; + + uint32_t AppBuff[APPBUFF_SIZE]; // Arrays to store up to 5 measurements @@ -206,7 +232,7 @@ { ucInterrupted = 0; #ifdef triggDiag - Serial.println("clear trigger"); + activeSerial->println("clear trigger"); #endif return 1; @@ -233,13 +259,13 @@ vsnprintf(buffer, sizeof(buffer), format, args); // Print to serial with canary prefix - // Serial.print("🐤 "); // I commented this out, but it was funnier to have the canary function with this -MK - Serial.println(buffer); + // activeSerial->print("🐤 "); // I commented this out, but it was funnier to have the canary function with this -MK + activeSerial->println(buffer); va_end(args); // Force flush the serial buffer - Serial.flush(); + activeSerial->flush(); } } @@ -250,7 +276,7 @@ { ucInterrupted = 1; #ifdef triggDiag - Serial.println("triggered"); + activeSerial->println("triggered"); #endif } @@ -336,7 +362,7 @@ AD5940_Delay10us(t10us); uint32_t code = AD5940_ReadAfeResult(AFERESULT_SINC2); AD5940_AFECtrlS(AFECTRL_ADCCNV, bFALSE); - // Serial.println(code); + // activeSerial->println(code); return code; } @@ -363,7 +389,7 @@ // Wake up the AD5940 from low power mode if (AD5940_WakeUp(10) > 10) { - // Serial.println("ERROR: AD5940 wakeup timeout"); + // activeSerial->println("ERROR: AD5940 wakeup timeout"); return -1000.0f; } @@ -450,7 +476,7 @@ for (uint32_t i = 0; i < NUM_RTD_SAMPLES; ++i) { accRTD += sampleADC(1); // Increased sampling delay - // Serial.println(accRTD); + // activeSerial->println(accRTD); AD5940_Delay10us(10); // Small delay between samples } adcCode_rtd = accRTD / NUM_RTD_SAMPLES; @@ -490,7 +516,7 @@ // // Validate measurements // if (volt_ref <= 0.0f || volt_rtd <= 0.0f) { - // Serial.println("ERROR: Invalid voltage measurements"); + // activeSerial->println("ERROR: Invalid voltage measurements"); // return -1000.0f; // } @@ -500,64 +526,64 @@ // Verbose output if (verboseMode) { // shrinking this output to avoid being too long - // Serial.println(""); - // Serial.println("verboseMode output"); - // Serial.print("sensor_mV"); - // Serial.println(sensor_mV); - Serial.println(" "); + // activeSerial->println(""); + // activeSerial->println("verboseMode output"); + // activeSerial->print("sensor_mV"); + // activeSerial->println(sensor_mV); + activeSerial->println(" "); - Serial.println("RTD Measurement"); - Serial.print(" RCal Averaged Measurement: "); - Serial.println(adcCode_ref); - Serial.print(" RTD Averaged Measurement: "); - Serial.println(adcCode_rtd); - Serial.printf(" NUM_SAMPLES: %u", NUM_RTD_SAMPLES); - Serial.println(" "); - Serial.print(" RTD TIA Resistor: "); + activeSerial->println("RTD Measurement"); + activeSerial->print(" RCal Averaged Measurement: "); + activeSerial->println(adcCode_ref); + activeSerial->print(" RTD Averaged Measurement: "); + activeSerial->println(adcCode_rtd); + activeSerial->printf(" NUM_SAMPLES: %u", NUM_RTD_SAMPLES); + activeSerial->println(" "); + activeSerial->print(" RTD TIA Resistor: "); switch (RTD_RTIA) { case HSTIARTIA_200: - Serial.println("200 Ohm"); + activeSerial->println("200 Ohm"); break; case HSTIARTIA_1K: - Serial.println("1K Ohm"); + activeSerial->println("1K Ohm"); break; case HSTIARTIA_5K: - Serial.println("5K Ohm"); + activeSerial->println("5K Ohm"); break; case HSTIARTIA_10K: - Serial.println("10K Ohm"); + activeSerial->println("10K Ohm"); break; case HSTIARTIA_20K: - Serial.println("20K Ohm"); + activeSerial->println("20K Ohm"); break; case HSTIARTIA_40K: - Serial.println("40K Ohm"); + activeSerial->println("40K Ohm"); break; case HSTIARTIA_80K: - Serial.println("80K Ohm"); + activeSerial->println("80K Ohm"); break; case HSTIARTIA_160K: - Serial.println("160K Ohm"); + activeSerial->println("160K Ohm"); break; default: - Serial.println("Unknown"); + activeSerial->println("Unknown"); break; } - // Serial.print("volt_ref: "); - // Serial.println(volt_ref, 6); // More precision - // Serial.print("volt_rtd: "); - // Serial.println(volt_rtd, 6); - // Serial.print("volt_ref / volt_rtd: "); - // Serial.println(volt_ref / volt_rtd, 6); - // Serial.print("Calculated RTD resistance: "); - // Serial.println(rtd_resistance, 6); + // activeSerial->print("volt_ref: "); + // activeSerial->println(volt_ref, 6); // More precision + // activeSerial->print("volt_rtd: "); + // activeSerial->println(volt_rtd, 6); + // activeSerial->print("volt_ref / volt_rtd: "); + // activeSerial->println(volt_ref / volt_rtd, 6); + // activeSerial->print("Calculated RTD resistance: "); + // activeSerial->println(rtd_resistance, 6); } // Display result - Serial.print("Freq:0.0 1 RzMag: "); - Serial.print(rtd_resistance, 5); - Serial.println(" Ohm, RzPhase: 0.0"); + activeSerial->print("Freq:0.0 1 RzMag: "); + activeSerial->print(rtd_resistance, 5); + activeSerial->println(" Ohm, RzPhase: 0.0"); return rtd_resistance; } @@ -679,13 +705,13 @@ if (param == "save") { saveCurrentConfig(); - Serial.println("Configuration saved"); + activeSerial->println("Configuration saved"); return; } else if (param == "recall") { recallSavedConfig(); - Serial.println("Configuration recalled"); + activeSerial->println("Configuration recalled"); return; } @@ -694,27 +720,27 @@ { // Set sine wave frequency (Hz) pImpedanceCfg->SinFreq = value.toFloat(); - Serial.printf("Set SinFreq to: %.2f Hz\n", pImpedanceCfg->SinFreq); + activeSerial->printf("Set SinFreq to: %.2f Hz\n", pImpedanceCfg->SinFreq); } else if (param == "dacpp") { // Set DAC peak-to-peak voltage (mV) pImpedanceCfg->DacVoltPP = value.toFloat(); - Serial.printf("Set DacVoltPP to: %.2f mV\n", pImpedanceCfg->DacVoltPP); + activeSerial->printf("Set DacVoltPP to: %.2f mV\n", pImpedanceCfg->DacVoltPP); } else if (param == "bias") { // Set DC bias voltage (mV) pImpedanceCfg->BiasVolt = value.toFloat(); - Serial.printf("Set BiasVolt to: %.2f mV\n", pImpedanceCfg->BiasVolt); + activeSerial->printf("Set BiasVolt to: %.2f mV\n", pImpedanceCfg->BiasVolt); } else if (param == "rtia") { // Set TIA (Transimpedance Amplifier) feedback resistor value uint32_t rtia = DEFAULT_RTIA; // default value int valueTest = value.toInt(); - Serial.print("Value:"); - Serial.println(value); + activeSerial->print("Value:"); + activeSerial->println(value); // Map string values to corresponding constants if (valueTest == 0) rtia = HSTIARTIA_200; @@ -733,13 +759,13 @@ else if (valueTest == 7) rtia = HSTIARTIA_160K; else - Serial.print("no change to tia"); + activeSerial->print("no change to tia"); pImpedanceCfg->HstiaRtiaSel = rtia; - Serial.printf("Set RTIA to: %s\n", value.c_str()); + activeSerial->printf("Set RTIA to: %s\n", value.c_str()); currentTIA = rtia; - Serial.print("currentTIA: "); - Serial.println(currentTIA); + activeSerial->print("currentTIA: "); + activeSerial->println(currentTIA); } else if (param == "pga") { @@ -759,7 +785,7 @@ pga = ADCPGA_9; pImpedanceCfg->AdcPgaGain = pga; - Serial.printf("Set PGA gain to: %s\n", value.c_str()); + activeSerial->printf("Set PGA gain to: %s\n", value.c_str()); } else if (param == "dftnum") { @@ -779,7 +805,7 @@ dft = DFTNUM_256; pImpedanceCfg->DftNum = dft; - Serial.printf("Set DFT number to: %s\n", value.c_str()); + activeSerial->printf("Set DFT number to: %s\n", value.c_str()); } else if (param == "avgnum") { @@ -797,44 +823,44 @@ avg = ADCAVGNUM_16; pImpedanceCfg->ADCAvgNum = avg; - Serial.printf("Set ADC average number to: %s\n", value.c_str()); + activeSerial->printf("Set ADC average number to: %s\n", value.c_str()); } else if (param == "sweep") { // Enable/disable frequency sweep mode bool enableSweep = (value == "1" || value.equalsIgnoreCase("true")); pImpedanceCfg->SweepCfg.SweepEn = enableSweep ? bTRUE : bFALSE; - Serial.printf("Set sweep enable to: %d\n", pImpedanceCfg->SweepCfg.SweepEn); + activeSerial->printf("Set sweep enable to: %d\n", pImpedanceCfg->SweepCfg.SweepEn); } else if (param == "sweepstart") { // Set sweep start frequency (Hz) pImpedanceCfg->SweepCfg.SweepStart = value.toFloat(); - Serial.printf("Set sweep start frequency to: %.2f Hz\n", pImpedanceCfg->SweepCfg.SweepStart); + activeSerial->printf("Set sweep start frequency to: %.2f Hz\n", pImpedanceCfg->SweepCfg.SweepStart); } else if (param == "sweepstop") { // Set sweep stop frequency (Hz) pImpedanceCfg->SweepCfg.SweepStop = value.toFloat(); - Serial.printf("Set sweep stop frequency to: %.2f Hz\n", pImpedanceCfg->SweepCfg.SweepStop); + activeSerial->printf("Set sweep stop frequency to: %.2f Hz\n", pImpedanceCfg->SweepCfg.SweepStop); } else if (param == "sweeppoints") { // Set number of frequency points in the sweep pImpedanceCfg->SweepCfg.SweepPoints = value.toInt(); - Serial.printf("Set sweep points to: %d\n", pImpedanceCfg->SweepCfg.SweepPoints); + activeSerial->printf("Set sweep points to: %d\n", pImpedanceCfg->SweepCfg.SweepPoints); } else if (param == "sweeplog") { // Set logarithmic (true) or linear (false) frequency spacing bool logSpacing = (value == "1" || value.equalsIgnoreCase("true")); pImpedanceCfg->SweepCfg.SweepLog = logSpacing ? bTRUE : bFALSE; - Serial.printf("Set sweep log mode to: %d\n", pImpedanceCfg->SweepCfg.SweepLog); + activeSerial->printf("Set sweep log mode to: %d\n", pImpedanceCfg->SweepCfg.SweepLog); } else { // Handle unrecognized parameter - Serial.println("Malformed command: unrecognized parameter"); + activeSerial->println("Malformed command: unrecognized parameter"); return; } @@ -867,29 +893,29 @@ AppIMPCtrl(IMPCTRL_GETFREQ, &freq); // Print measurement frequency - // Serial.printf("Freq: %.2f Hz ", freq); + // activeSerial->printf("Freq: %.2f Hz ", freq); // Print the number of data points - // Serial.printf("DataPoints: %lu ", DataCount); + // activeSerial->printf("DataPoints: %lu ", DataCount); // // Process and print each impedance measurement // for (uint32_t i = 0; i < DataCount; i++) { // // Print magnitude in ohms and phase in degrees // // Note: Converting phase from radians to degrees (phase * 180 / π) - // Serial.printf("RzMag: %.2f Ohm, RzPhase: %.2f deg", + // activeSerial->printf("RzMag: %.2f Ohm, RzPhase: %.2f deg", // pImp[i].Magnitude, // pImp[i].Phase * 180 / MATH_PI); // // Add separator between multiple measurements if needed // if (i < DataCount - 1) { - // Serial.print(", "); + // activeSerial->print(", "); // } // } storedFrequency = freq; magnitudeArray[readingCount] = pImp[0].Magnitude; phaseArray[readingCount] = pImp[0].Phase * 180 / MATH_PI; // Add newline for better readability in serial monitor - // Serial.println(); + // activeSerial->println(); } /** @@ -980,19 +1006,19 @@ // Initialize SPI communication with AD5940 SPI.begin(); - // Serial.println("chipRead:"); + // activeSerial->println("chipRead:"); uint32_t testResult = AD5940_ReadReg(REG_AFECON_CHIPID); - // Serial.println(testResult); + // activeSerial->println(testResult); if (testResult == 0 || testResult == 65535) { - // Serial.println("System Cannot detect AD5940/1"); - // Serial.println(testResult); + // activeSerial->println("System Cannot detect AD5940/1"); + // activeSerial->println(testResult); SPI.end(); return 1; // chip not present } - // Serial.println(AD5940_ReadReg(REG_AFECON_CHIPID)); - // Serial.println("ENDchipRead"); + // activeSerial->println(AD5940_ReadReg(REG_AFECON_CHIPID)); + // activeSerial->println("ENDchipRead"); // Initialize AD5940 core functions AD5940_Initialize(); @@ -1121,11 +1147,11 @@ saveCurrentConfig(); return false; // Confirm initialization complete and display user information - // Serial.println("Startup Complete"); + // activeSerial->println("Startup Complete"); // printHelp(); // Show available commands // printCurrentConfigShort(); // Display current measurement settings // System is now ready for measurements - // Serial.println("System ready; enter b to perform reading"); + // activeSerial->println("System ready; enter b to perform reading"); } /** @@ -1180,7 +1206,7 @@ // Set up buffer for data collection and process the measurement bufferSize = APPBUFF_SIZE; AppIMPISR(AppBuff, &bufferSize); - // Serial.println("tset"); + // activeSerial->println("tset"); // Display the impedance measurement results // bufferSize now contains the actual number of valid data points @@ -1197,7 +1223,7 @@ // Handle timeout situation if (timeoutOccurred) { - // Serial.println("ERROR: Impedance measurement timeout occurred!"); + // activeSerial->println("ERROR: Impedance measurement timeout occurred!"); } return timeoutOccurred; } @@ -1219,23 +1245,23 @@ AppIMPGetCfg(&cfg); // Print header with separator - Serial.println("------------------------"); - Serial.println("Current Conductivity Settings"); + activeSerial->println("------------------------"); + activeSerial->println("Current Conductivity Settings"); // Print essential measurement parameters with units - Serial.printf("SinFreq: %.2f Hz\n", cfg->SinFreq); // Sine wave frequency - Serial.printf("DacVoltPP: %.2f mV\n", cfg->DacVoltPP); // DAC peak-to-peak voltage - Serial.printf("BiasVolt: %.2f mV\n", cfg->BiasVolt); // DC bias voltage + activeSerial->printf("SinFreq: %.2f Hz\n", cfg->SinFreq); // Sine wave frequency + activeSerial->printf("DacVoltPP: %.2f mV\n", cfg->DacVoltPP); // DAC peak-to-peak voltage + activeSerial->printf("BiasVolt: %.2f mV\n", cfg->BiasVolt); // DC bias voltage // Additional parameters (commented out for simplified display) // Uncomment these lines to display more detailed configuration - Serial.printf("RTIA: %lu\n", cfg->HstiaRtiaSel); // Transimpedance amplifier setting - Serial.printf("PGA Gain: %lu\n", cfg->AdcPgaGain); // Programmable gain amplifier setting - Serial.printf("DFT Points: %lu\n", cfg->DftNum); // Number of DFT points - Serial.printf("ADC Avg: %u\n", cfg->ADCAvgNum); // ADC averaging setting + activeSerial->printf("RTIA: %lu\n", cfg->HstiaRtiaSel); // Transimpedance amplifier setting + activeSerial->printf("PGA Gain: %lu\n", cfg->AdcPgaGain); // Programmable gain amplifier setting + activeSerial->printf("DFT Points: %lu\n", cfg->DftNum); // Number of DFT points + activeSerial->printf("ADC Avg: %u\n", cfg->ADCAvgNum); // ADC averaging setting // Print footer with separator - Serial.println("------------------------"); + activeSerial->println("------------------------"); } /** @@ -1248,43 +1274,43 @@ void printHelp() { - Serial.println("------------------"); - Serial.println("Version:"); - Serial.println(VERSION); - Serial.println(AUTHOR); + activeSerial->println("------------------"); + activeSerial->println("Version:"); + activeSerial->println(VERSION); + activeSerial->println(AUTHOR); - Serial.println("------------------"); - Serial.println("Available commands:"); + activeSerial->println("------------------"); + activeSerial->println("Available commands:"); // Measurement and system control commands - Serial.println("d - Perform measurement (Outputs: conductivity followed by temperature data,"); - Serial.println(" format: freq rzmag rzphase for each measurement separated by ;)"); - Serial.println("a - rerun initialize on all units"); + activeSerial->println("d - Perform measurement (Outputs: conductivity followed by temperature data,"); + activeSerial->println(" format: freq rzmag rzphase for each measurement separated by ;)"); + activeSerial->println("a - rerun initialize on all units"); - Serial.println("b - Perform measurement on all previously initialized units"); + activeSerial->println("b - Perform measurement on all previously initialized units"); - Serial.println(""); - Serial.println("s - Rerun system setup and initialization"); - Serial.println("y - Print current conductivity measurement settings"); - Serial.println("r - Restart microcontroller"); - Serial.println("i - Blink LED on teensy to id unit"); - Serial.println("j # - select unit 1 through 6; ie 'j 1' selected unit 1"); - Serial.println("v - toggle verbose mode for rtd measurement"); - Serial.println("load - read eeprom values"); - Serial.println("save - save values to eeprom (will prompt for confirmation) ie: 'save, 45.34,3634.344,63232.32,6232.2' will save those values to eeprom for currently selected unit upon confirmation"); - Serial.println(); - Serial.println(); + activeSerial->println(""); + activeSerial->println("s - Rerun system setup and initialization"); + activeSerial->println("y - Print current conductivity measurement settings"); + activeSerial->println("r - Restart microcontroller"); + activeSerial->println("i - Blink LED on teensy to id unit"); + activeSerial->println("j # - select unit 1 through 6; ie 'j 1' selected unit 1"); + activeSerial->println("v - toggle verbose mode for rtd measurement"); + activeSerial->println("load - read eeprom values"); + activeSerial->println("save - save values to eeprom (will prompt for confirmation) ie: 'save, 45.34,3634.344,63232.32,6232.2' will save those values to eeprom for currently selected unit upon confirmation"); + activeSerial->println(); + activeSerial->println(); // blink LED on teensy to id unit // Configuration command format and parameters - Serial.println("cfg - Change settings for conductivity measurement"); - Serial.println(" cfg,, - Configure parameters for conductivity measurement"); - Serial.println(" Parameters:"); - Serial.println(" sinfreq - Sine wave frequency (Hz)"); - Serial.println(" dacpp - DAC peak-to-peak voltage (mV, maximum: 800mVpp)"); - Serial.println(" bias - DC bias voltage (mV, maximum: 2200mV)"); + activeSerial->println("cfg - Change settings for conductivity measurement"); + activeSerial->println(" cfg,, - Configure parameters for conductivity measurement"); + activeSerial->println(" Parameters:"); + activeSerial->println(" sinfreq - Sine wave frequency (Hz)"); + activeSerial->println(" dacpp - DAC peak-to-peak voltage (mV, maximum: 800mVpp)"); + activeSerial->println(" bias - DC bias voltage (mV, maximum: 2200mV)"); - Serial.println("------------------"); + activeSerial->println("------------------"); } /** @@ -1298,26 +1324,25 @@ { // Read a line from the serial port until newline character - String command = Serial.readStringUntil('\n'); + String command = activeSerial->readStringUntil('\n'); // Handle configuration commands (format: cfg,parameter,value) if (command.startsWith("cfg,")) { handleConfigCommand(command); - // Serial.println(command); - // Serial.print("*"); + // activeSerial->println(command); + // activeSerial->print("*"); propagateSettingsChanges = 1; - Serial.println((int)updateCfgStataus); + activeSerial->println((int)updateCfgStataus); return; } if (command.startsWith("mst,")) { updateMeasurementSettings(command); propagateSettingsChanges = 1; - Serial.write((uint8_t *)&updateCfgStataus, sizeof(updateCfgStataus)); - Serial1.write((uint8_t *)&updateCfgStataus, sizeof(updateCfgStataus)); + activeSerial->write((uint8_t *)&updateCfgStataus, sizeof(updateCfgStataus)); return; } @@ -1332,8 +1357,7 @@ if (command.startsWith("upe,")) { updateEEPROMdata(command); - Serial.write((uint8_t *)&updateEepromStatus, sizeof(updateEepromStatus)); - Serial1.write((uint8_t *)&updateEepromStatus, sizeof(updateEepromStatus)); + activeSerial->write((uint8_t *)&updateEepromStatus, sizeof(updateEepromStatus)); return; } @@ -1361,28 +1385,28 @@ getInitStatus(); } selectFirstWorkingUnit(); - // Serial.print("*"); + // activeSerial->print("*"); } break; case '-': { // if (AD5940_IsAdcMaxSaturatedAndClear()) { - // Serial.println("SaturationFlag"); + // activeSerial->println("SaturationFlag"); // } else { - // Serial.println("noSat"); + // activeSerial->println("noSat"); // } } break; case '+': { // AD5940_EnableAdcMaxSaturationIRQ(/*max_code=*/0xFFFF, /*hysteresis=*/0x0080); - Serial.println("rearm"); + activeSerial->println("rearm"); } break; case 'b': { measureAllSuccessfulUnits(); - Serial.print("*"); + activeSerial->print("*"); } break; case 'c': @@ -1405,12 +1429,12 @@ { if (settling == 0) { - Serial.println("Performing settling measurements..."); + activeSerial->println("Performing settling measurements..."); } if (verboseMode) { - Serial.printf(" Settling Measurement#: %u ", settling); - Serial.println(" "); + activeSerial->printf(" Settling Measurement#: %u ", settling); + activeSerial->println(" "); } // Run one complete measurement cycle but discard results AppIMPInit(AppBuff, APPBUFF_SIZE); @@ -1441,42 +1465,42 @@ } if (verboseMode) { - Serial.println(" End Settling Measurements"); + activeSerial->println(" End Settling Measurements"); } } if (verboseMode) { - Serial.println("Conductivity"); - Serial.print(" Conductivity TIA Resistor: "); + activeSerial->println("Conductivity"); + activeSerial->print(" Conductivity TIA Resistor: "); switch (DEFAULT_RTIA) { case HSTIARTIA_200: - Serial.println("200 Ohm"); + activeSerial->println("200 Ohm"); break; case HSTIARTIA_1K: - Serial.println("1K Ohm"); + activeSerial->println("1K Ohm"); break; case HSTIARTIA_5K: - Serial.println("5K Ohm"); + activeSerial->println("5K Ohm"); break; case HSTIARTIA_10K: - Serial.println("10K Ohm"); + activeSerial->println("10K Ohm"); break; case HSTIARTIA_20K: - Serial.println("20K Ohm"); + activeSerial->println("20K Ohm"); break; case HSTIARTIA_40K: - Serial.println("40K Ohm"); + activeSerial->println("40K Ohm"); break; case HSTIARTIA_80K: - Serial.println("80K Ohm"); + activeSerial->println("80K Ohm"); break; case HSTIARTIA_160K: - Serial.println("160K Ohm"); + activeSerial->println("160K Ohm"); break; default: - Serial.println("Unknown"); + activeSerial->println("Unknown"); break; } } @@ -1489,11 +1513,11 @@ { if (AD5940_IsAdcMaxSaturatedAndClear()) { - Serial.println("SaturationFlag tripped!"); + activeSerial->println("SaturationFlag tripped!"); } else { - Serial.println("SaturationFlag NOT tripped!"); + activeSerial->println("SaturationFlag NOT tripped!"); } } float medianMag; @@ -1510,21 +1534,21 @@ medianPhase = calculateMedian(phaseArray, repeatNumber); } - Serial.printf("Freq: %.2f Hz ", storedFrequency); + activeSerial->printf("Freq: %.2f Hz ", storedFrequency); // Print the number of data points - Serial.printf("DataPoints: %lu ", 1); + activeSerial->printf("DataPoints: %lu ", 1); // Print magnitude in ohms and phase in degrees // Note: Converting phase from radians to degrees (phase * 180 / π) - Serial.printf("RzMag: %.2f Ohm, RzPhase: %.2f deg", + activeSerial->printf("RzMag: %.2f Ohm, RzPhase: %.2f deg", medianMag, medianPhase); // Add separator and perform RTD (temperature) measurement - Serial.print(";"); + activeSerial->print(";"); AppRTDMeasure(rtdVoltageValue); - Serial.print("*"); + activeSerial->print("*"); previousMillis = millis(); } break; @@ -1548,19 +1572,19 @@ } else { - Serial.println("bad value, not changing rtdVoltageValue"); + activeSerial->println("bad value, not changing rtdVoltageValue"); } } - Serial.println("rtdVoltageValue"); - Serial.println(rtdVoltageValue); + activeSerial->println("rtdVoltageValue"); + activeSerial->println(rtdVoltageValue); } break; case 't': // Read temperature at a user-defined RTD drive level (mV) { AppRTDMeasure(rtdVoltageValue); - Serial.print("*"); // optional “command complete” asterisk + activeSerial->print("*"); // optional “command complete” asterisk } case 's': // Perform system startup and configuration { @@ -1570,14 +1594,14 @@ // Save the configuration and stop any ongoing measurement saveCurrentConfig(); AppIMPCtrl(IMPCTRL_STOPSYNC, 0); - Serial.println("Startup Complete"); + activeSerial->println("Startup Complete"); } break; case 'p': { // propagate settings change through all units - Serial.println("function removed"); - Serial.println("*"); + activeSerial->println("function removed"); + activeSerial->println("*"); } case 'j': // Perform system startup and configuration { @@ -1593,15 +1617,15 @@ case 'x': // Echo test command { - Serial.println("z"); - Serial.println("*"); + activeSerial->println("z"); + activeSerial->println("*"); } break; case 'v': // Toggle verbose mode on/off { verboseMode = !verboseMode; - Serial.print("Verbose mode "); - Serial.println(verboseMode ? "ON" : "OFF"); + activeSerial->print("Verbose mode "); + activeSerial->println(verboseMode ? "ON" : "OFF"); } break; case 'y': // Print current configuration in short format @@ -1611,7 +1635,7 @@ break; case 'z': // Print current configuration in short format { - Serial.print("AlyIDNumber: "); + activeSerial->print("AlyIDNumber: "); // Read the 4 words (32-bits each) that make up the 128-bit serial number uint32_t serNum[4]; @@ -1627,15 +1651,15 @@ // Print each 32-bit word with leading zeros char buf[9]; snprintf(buf, sizeof(buf), "%08lX", serNum[i]); - Serial.print(buf); + activeSerial->print(buf); // Add a separator between words (except after the last one) if (i < 3) { - Serial.print("-"); + activeSerial->print("-"); } } - Serial.println(); + activeSerial->println(); } break; @@ -1666,8 +1690,7 @@ // Mesaure and transmit for all the initialized sensors if(false == getAllMesaurements()) { - Serial.write(0); - Serial1.write(0); + activeSerial->write((uint8_t)0); } } break; @@ -1708,7 +1731,7 @@ default: // Handle unknown commands { - Serial.println("Unknown command. Type ? for help."); + activeSerial->println("Unknown command. Type ? for help."); } break; } @@ -1720,7 +1743,7 @@ // Validate unit input (1-6) if (unitIn < 1 || unitIn > 6) { - // Serial.println("Error: Unit must be between 1 and 6"); + // activeSerial->println("Error: Unit must be between 1 and 6"); return; } @@ -1785,12 +1808,12 @@ singleSensorPacket.sensorNum = unitIn; // Conductivity Sensor number i.e unit 1 to 6. - // Serial.print("Selected Unit: "); - // Serial.print(unitIn); - // Serial.print(" | Reset Pin: "); - // Serial.print(TEENSY_RESET_PIN); - // Serial.print(" | Interrupt Pin: "); - // Serial.println(AD5940_INT_PIN); + // activeSerial->print("Selected Unit: "); + // activeSerial->print(unitIn); + // activeSerial->print(" | Reset Pin: "); + // activeSerial->print(TEENSY_RESET_PIN); + // activeSerial->print(" | Interrupt Pin: "); + // activeSerial->println(AD5940_INT_PIN); } // Write a mixed array (doubles first, then floats) to the EEPROM @@ -1948,8 +1971,8 @@ // Check if address is valid if (address >= EEPROM_SIZE) { - Serial.print("Error: Address out of range: "); - Serial.println(address); + activeSerial->print("Error: Address out of range: "); + activeSerial->println(address); return; } @@ -1986,8 +2009,8 @@ // Check if address is valid if (address >= EEPROM_SIZE) { - Serial.print("Error: Address out of range: "); - Serial.println(address); + activeSerial->print("Error: Address out of range: "); + activeSerial->println(address); return 0; } @@ -2031,7 +2054,7 @@ int firstComma = command.indexOf(','); if (firstComma < 0) { - Serial.println("Error: Invalid save command format"); + activeSerial->println("Error: Invalid save command format"); return; } String dataStr = command.substring(firstComma + 1); @@ -2082,50 +2105,50 @@ // Check if we got at least 1 value if (valueIndex == 0) { - Serial.println("Error: No valid values found"); + activeSerial->println("Error: No valid values found"); return; } if (valueIndex > maxTotal) { - Serial.print("Error: Too many values, maximum is "); - Serial.print(maxTotal); - Serial.print(" ("); - Serial.print(DOUBLE_COUNT); - Serial.print(" doubles + "); - Serial.print(maxFloats); - Serial.println(" floats)"); + activeSerial->print("Error: Too many values, maximum is "); + activeSerial->print(maxTotal); + activeSerial->print(" ("); + activeSerial->print(DOUBLE_COUNT); + activeSerial->print(" doubles + "); + activeSerial->print(maxFloats); + activeSerial->println(" floats)"); return; } int doubleCount = min(valueIndex, DOUBLE_COUNT); int floatCount = max(0, valueIndex - DOUBLE_COUNT); // Display the values and ask for confirmation - Serial.print("Preparing to save "); - Serial.print(valueIndex); - Serial.print(" values to EEPROM ("); - Serial.print(doubleCount); - Serial.print(" doubles, "); - Serial.print(floatCount); - Serial.println(" floats):"); + activeSerial->print("Preparing to save "); + activeSerial->print(valueIndex); + activeSerial->print(" values to EEPROM ("); + activeSerial->print(doubleCount); + activeSerial->print(" doubles, "); + activeSerial->print(floatCount); + activeSerial->println(" floats):"); // Display double values for (int i = 0; i < doubleCount; i++) { - Serial.print(i); - Serial.print(" (double): "); - Serial.println(doubleValues[i], 10); + activeSerial->print(i); + activeSerial->print(" (double): "); + activeSerial->println(doubleValues[i], 10); } // Display float values for (int i = 0; i < floatCount; i++) { - Serial.print(i + DOUBLE_COUNT); - Serial.print(" (float): "); - Serial.println(floatValues[i], 6); // Floats typically have 6-7 significant digits + activeSerial->print(i + DOUBLE_COUNT); + activeSerial->print(" (float): "); + activeSerial->println(floatValues[i], 6); // Floats typically have 6-7 significant digits } - Serial.println("Confirm write to EEPROM? (y/n)"); + activeSerial->println("Confirm write to EEPROM? (y/n)"); // Wait for user confirmation unsigned long startTime = millis(); @@ -2135,84 +2158,84 @@ // Check for timeout if (millis() - startTime > timeout) { - Serial.println("Timed out waiting for confirmation. Operation aborted."); + activeSerial->println("Timed out waiting for confirmation. Operation aborted."); return; } // Check if data is available to read - if (Serial.available() > 0) + if (activeSerial->available() > 0) { - char response = Serial.read(); + char response = activeSerial->read(); // Clear any remaining characters in buffer (like newline) - while (Serial.available() > 0) + while (activeSerial->available() > 0) { - Serial.read(); + activeSerial->read(); } // Process response if (response == 'y' || response == 'Y') { // User confirmed, write to EEPROM unsigned int baseAddress = 0; writeMixedValues(baseAddress, doubleValues, doubleCount, floatValues, floatCount); - Serial.println("save attempted"); + activeSerial->println("save attempted"); // Read back the values to confirm they were written correctly double readDoubles[DOUBLE_COUNT]; float readFloats[maxFloats]; readMixedValues(baseAddress, readDoubles, doubleCount, readFloats, floatCount); - Serial.println("Verification - Values read back from EEPROM:"); + activeSerial->println("Verification - Values read back from EEPROM:"); bool verificationSuccess = true; // Verify doubles for (int i = 0; i < doubleCount; i++) { - Serial.print(i); - Serial.print(" (double): "); - Serial.println(readDoubles[i], 10); + activeSerial->print(i); + activeSerial->print(" (double): "); + activeSerial->println(readDoubles[i], 10); if (abs(doubleValues[i] - readDoubles[i]) > 0.000000001) { verificationSuccess = false; - Serial.print("Warning: Double value "); - Serial.print(i); - Serial.println(" does not match exactly what was written"); + activeSerial->print("Warning: Double value "); + activeSerial->print(i); + activeSerial->println(" does not match exactly what was written"); } } // Verify floats for (int i = 0; i < floatCount; i++) { - Serial.print(i + DOUBLE_COUNT); - Serial.print(" (float): "); - Serial.println(readFloats[i], 6); + activeSerial->print(i + DOUBLE_COUNT); + activeSerial->print(" (float): "); + activeSerial->println(readFloats[i], 6); if (abs(floatValues[i] - readFloats[i]) > 0.000001) { verificationSuccess = false; - Serial.print("Warning: Float value "); - Serial.print(i + DOUBLE_COUNT); - Serial.println(" does not match exactly what was written"); + activeSerial->print("Warning: Float value "); + activeSerial->print(i + DOUBLE_COUNT); + activeSerial->println(" does not match exactly what was written"); } } if (verificationSuccess) { - Serial.println("Verification successful: All values match!"); + activeSerial->println("Verification successful: All values match!"); } else { - Serial.println("Verification Failed, confirm device attached and powered."); + activeSerial->println("Verification Failed, confirm device attached and powered."); } return; } else if (response == 'n' || response == 'N') { // User aborted - Serial.println("Operation aborted by user."); + activeSerial->println("Operation aborted by user."); return; } else { // Invalid response, ask again - Serial.println("Please enter 'y' to confirm or 'n' to abort:"); + activeSerial->println("Please enter 'y' to confirm or 'n' to abort:"); } } // Small delay to prevent CPU hogging @@ -2232,34 +2255,34 @@ readMixedValues(baseAddress, doubleValues, DOUBLE_COUNT, floatValues, maxFloats); - Serial.println("Loaded values from EEPROM:"); + activeSerial->println("Loaded values from EEPROM:"); // Display doubles for (int i = 0; i < DOUBLE_COUNT; i++) { - Serial.print(i); - Serial.print(" (double): "); - Serial.println(doubleValues[i], 10); + activeSerial->print(i); + activeSerial->print(" (double): "); + activeSerial->println(doubleValues[i], 10); } // Display floats for (int i = 0; i < maxFloats; i++) { - Serial.print(i + DOUBLE_COUNT); - Serial.print(" (float): "); - Serial.println(floatValues[i], 6); + activeSerial->print(i + DOUBLE_COUNT); + activeSerial->print(" (float): "); + activeSerial->println(floatValues[i], 6); } } // Function to initialize all units sequentially void initializeAllUnits() { - Serial.println("Initializing all units (1-6)..."); + activeSerial->println("Initializing all units (1-6)..."); for (int unit = 1; unit <= 6; unit++) { - Serial.print("Initializing Unit "); - Serial.println(unit); + activeSerial->print("Initializing Unit "); + activeSerial->println(unit); // Select the current unit selectUnit(unit); @@ -2273,38 +2296,37 @@ // Give some time for the initialization to complete delay(200); - Serial.print("Unit "); - Serial.print(unit); - Serial.println(" initialized successfully"); + activeSerial->print("Unit "); + activeSerial->print(unit); + activeSerial->println(" initialized successfully"); } - Serial.println("All units initialized successfully"); + activeSerial->println("All units initialized successfully"); } // Function to ask the user which units to initialize and then initialize them bool initializeSelectedUnits() { initStatus = INIT_STATUS_IN_PROGRESS; - Serial.write((uint8_t *)&initStatus, sizeof(initStatus)); - Serial1.write((uint8_t *)&initStatus, sizeof(initStatus)); + activeSerial->write((uint8_t *)&initStatus, sizeof(initStatus)); - // Serial.println("\nUnit Initialization"); - // Serial.println("Enter 'all' to initialize all units (1-6)"); - // Serial.println("Or enter specific units separated by commas (e.g., '1,3,5')"); - // Serial.println("Then press Enter:"); + // activeSerial->println("\nUnit Initialization"); + // activeSerial->println("Enter 'all' to initialize all units (1-6)"); + // activeSerial->println("Or enter specific units separated by commas (e.g., '1,3,5')"); + // activeSerial->println("Then press Enter:"); // // Wait for user input - // while (!Serial.available()) { + // while (!activeSerial->available()) { // // Wait for input // delay(100); // } // Read the input - String input = Serial.readStringUntil('\n'); + String input = activeSerial->readStringUntil('\n'); input.trim(); // Remove any whitespace // Initialize all units - // Serial.println("Initializing all units (1-6)..."); + // activeSerial->println("Initializing all units (1-6)..."); for (int unit = 1; unit <= 6; unit++) { @@ -2316,7 +2338,7 @@ // else { // // Parse the comma-separated list - // Serial.print("Initializing selected units: "); + // activeSerial->print("Initializing selected units: "); // // Start at the beginning of the string // int startPos = 0; @@ -2339,22 +2361,22 @@ // // Check if it's a valid unit number // if (unit >= 1 && unit <= 6) { - // Serial.print(unit); - // Serial.print(" "); + // activeSerial->print(unit); + // activeSerial->print(" "); // // Initialize this unit // initializeSingleUnit(unit); // } else { - // Serial.print("(Skipping invalid unit "); - // Serial.print(unitStr); - // Serial.print(") "); + // activeSerial->print("(Skipping invalid unit "); + // activeSerial->print(unitStr); + // activeSerial->print(") "); // } // // Move to the position after the comma // startPos = endPos + 1; // } - // Serial.println("\nSelected units initialization complete"); + // activeSerial->println("\nSelected units initialization complete"); // Print summary of unit status return isInitialized; @@ -2371,21 +2393,21 @@ int workingUnit = i + 1; selectUnit(workingUnit); - // Serial.print("\nAutomatically selected first working unit: Unit "); - // Serial.println(workingUnit); + // activeSerial->print("\nAutomatically selected first working unit: Unit "); + // activeSerial->println(workingUnit); startupAD5941(); return; // Exit after selecting the first working unit } } // If we get here, no working units were found - // Serial.println("\nNo working units available to select!"); + // activeSerial->println("\nNo working units available to select!"); } // Helper function to initialize a single unit void initializeSingleUnit(int unit) { - // Serial.print("\nInitializing Unit "); - // Serial.println(unit); + // activeSerial->print("\nInitializing Unit "); + // activeSerial->println(unit); // Select the unit selectUnit(unit); @@ -2397,19 +2419,19 @@ if (startupAD5941()) { // Startup failed - // Serial.print("Unit "); - // Serial.print(unit); - // Serial.println(" startup FAILED"); + // activeSerial->print("Unit "); + // activeSerial->print(unit); + // activeSerial->println(" startup FAILED"); // Record the failure in our status array (0-indexed) unitStatus[unit - 1] = STATUS_FAILED; } else { // Startup worked - // Serial.print("Unit "); - // Serial.print(unit); - // Serial.println(" startup SUCCESS"); + // activeSerial->print("Unit "); + // activeSerial->print(unit); + // activeSerial->println(" startup SUCCESS"); // Record the success in our status array unitStatus[unit - 1] = STATUS_SUCCESS; @@ -2441,61 +2463,61 @@ } // Print summary - Serial.println("\n----- Initialization Results -----"); + activeSerial->println("\n----- Initialization Results -----"); // Report units by status - Serial.print("Successful: "); - Serial.print(successCount); - Serial.print(", Failed: "); - Serial.print(failedCount); - Serial.print(", Skipped: "); - Serial.println(skippedCount); + activeSerial->print("Successful: "); + activeSerial->print(successCount); + activeSerial->print(", Failed: "); + activeSerial->print(failedCount); + activeSerial->print(", Skipped: "); + activeSerial->println(skippedCount); // List failed units if (failedCount > 0) { - Serial.print("Failed units: "); + activeSerial->print("Failed units: "); bool firstPrinted = false; for (int i = 0; i < 6; i++) { if (unitStatus[i] == STATUS_FAILED) { if (firstPrinted) { - Serial.print(", "); + activeSerial->print(", "); } - Serial.print(i + 1); + activeSerial->print(i + 1); firstPrinted = true; } } - Serial.println(); + activeSerial->println(); } // List skipped units if (skippedCount > 0) { - Serial.print("Skipped units: "); + activeSerial->print("Skipped units: "); bool firstPrinted = false; for (int i = 0; i < 6; i++) { if (unitStatus[i] == STATUS_SKIPPED) { if (firstPrinted) { - Serial.print(", "); + activeSerial->print(", "); } - Serial.print(i + 1); + activeSerial->print(i + 1); firstPrinted = true; } } - Serial.println(); + activeSerial->println(); } // Report available units - Serial.print("\nAvailable units: "); + activeSerial->print("\nAvailable units: "); if (successCount == 0) { - Serial.println("NONE - No successfully initialized units!"); + activeSerial->println("NONE - No successfully initialized units!"); } else { @@ -2508,16 +2530,16 @@ // Add comma if not the first available unit if (firstPrinted) { - Serial.print(", "); + activeSerial->print(", "); } - Serial.print(i + 1); + activeSerial->print(i + 1); firstPrinted = true; } } - Serial.println(); + activeSerial->println(); } - Serial.println("---------------------------------"); + activeSerial->println("---------------------------------"); } // Function to measure all successfully initialized units @@ -2537,13 +2559,13 @@ // If no successful units, report and return if (successCount == 0) { - Serial.println("No successfully initialized units to measure!"); + activeSerial->println("No successfully initialized units to measure!"); return; } - Serial.print("Measuring all "); - Serial.print(successCount); - Serial.println(" successful units..."); + activeSerial->print("Measuring all "); + activeSerial->print(successCount); + activeSerial->println(" successful units..."); AppIMPCfg_Type *pImpedanceCfg; // Loop through and measure each successful unit @@ -2566,15 +2588,15 @@ delay(50); // Print unit identifier before measurement - Serial.print("Unit "); - Serial.print(unit); - Serial.print(": "); + activeSerial->print("Unit "); + activeSerial->print(unit); + activeSerial->print(": "); // quick patch for fixing spontaneous measurements unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= jitterTimeout) { - Serial.println("Performing settling measurements..."); + activeSerial->println("Performing settling measurements..."); // Run multiple settling measurements in a loop for (int settling = 0; settling < numSettlingMeasurements; settling++) @@ -2627,28 +2649,28 @@ medianMag = calculateMedian(magnitudeArray, repeatNumber); medianPhase = calculateMedian(phaseArray, repeatNumber); } - Serial.printf("Freq: %.2f Hz ", storedFrequency); + activeSerial->printf("Freq: %.2f Hz ", storedFrequency); // Print the number of data points - Serial.printf("DataPoints: %lu ", 1); + activeSerial->printf("DataPoints: %lu ", 1); // Print magnitude in ohms and phase in degrees // Note: Converting phase from radians to degrees (phase * 180 / π) - Serial.printf("RzMag: %.2f Ohm, RzPhase: %.2f deg", + activeSerial->printf("RzMag: %.2f Ohm, RzPhase: %.2f deg", medianMag, medianPhase); // Add separator - Serial.print(";"); + activeSerial->print(";"); // Perform RTD (temperature) measurement AppRTDMeasure(rtdVoltageValue); // Line break between units - Serial.println(); + activeSerial->println(); } previousMillis = millis(); - Serial.println("All measurements complete."); + activeSerial->println("All measurements complete."); propagateSettingsChanges = 0; } @@ -2702,7 +2724,7 @@ AD5940_WriteReg(0x00003004, (1u << 5)); // INTCCLR: clear ADCMAX fail if (verboseMode) { - Serial.println("saturationFlagSet"); + activeSerial->println("saturationFlagSet"); } } @@ -2722,6 +2744,62 @@ // ************************************ Diality ********************************************** + +void detectSerial() { + for (int i = 0; i < 8; i++) { + beginSerial(serialPorts[i], 115200); + delay(50); // Give time for init + // For USB Serial, wait for connection + if (serialPorts[i] == &Serial) { + unsigned long start = millis(); + while (!Serial && millis() - start < 2000) { + // Wait up to 2s for USB + } + } + // Assume first port is good (or add handshake logic) + activeSerial = serialPorts[i]; + activeSerial->println(String("Using ") + serialNames[i]); + break; + } +} + + +void beginSerial(Stream* s, unsigned long baud) +{ + if (s == &Serial) + { + Serial.begin(baud); + } + else if (s == &Serial1) + { + Serial1.begin(baud); + } + else if (s == &Serial2) + { + Serial2.begin(baud); + } + else if (s == &Serial3) + { + Serial3.begin(baud); + } + else if (s == &Serial4) + { + Serial4.begin(baud); + } + else if (s == &Serial5) + { + Serial5.begin(baud); + } + else if (s == &Serial6) + { + Serial6.begin(baud); + } + else if (s == &Serial7) + { + Serial7.begin(baud); + } +} + // Function to measure all successfully initialized units bool getAllMesaurements(void) { @@ -2741,7 +2819,7 @@ if (successCount == 0) { retVal = false; // Error - // Serial.println("No successfully initialized units to measure!"); + // activeSerial->println("No successfully initialized units to measure!"); return retVal; } @@ -2855,8 +2933,7 @@ } } // Send all the sensor data to DD - Serial.write((uint8_t *)&sensorPacket, sizeof(sensorPacket)); - Serial1.write((uint8_t *)&sensorPacket, sizeof(sensorPacket)); + activeSerial->write((uint8_t *)&sensorPacket, sizeof(sensorPacket)); propagateSettingsChanges = 0; return retVal; @@ -2874,12 +2951,12 @@ { if (settling == 0) { - // Serial.println("Performing settling measurements..."); + // activeSerial->println("Performing settling measurements..."); } if (verboseMode) { - // Serial.printf(" Settling Measurement#: %u ", settling); - // Serial.println(" "); + // activeSerial->printf(" Settling Measurement#: %u ", settling); + // activeSerial->println(" "); } // Run one complete measurement cycle but discard results AppIMPInit(AppBuff, APPBUFF_SIZE); @@ -2910,42 +2987,42 @@ } if (verboseMode) { - // Serial.println(" End Settling Measurements"); + // activeSerial->println(" End Settling Measurements"); } } if (verboseMode) { - // Serial.println("Conductivity"); - // Serial.print(" Conductivity TIA Resistor: "); + // activeSerial->println("Conductivity"); + // activeSerial->print(" Conductivity TIA Resistor: "); switch (DEFAULT_RTIA) { case HSTIARTIA_200: - // Serial.println("200 Ohm"); + // activeSerial->println("200 Ohm"); break; case HSTIARTIA_1K: - // Serial.println("1K Ohm"); + // activeSerial->println("1K Ohm"); break; case HSTIARTIA_5K: - // Serial.println("5K Ohm"); + // activeSerial->println("5K Ohm"); break; case HSTIARTIA_10K: - // Serial.println("10K Ohm"); + // activeSerial->println("10K Ohm"); break; case HSTIARTIA_20K: - // Serial.println("20K Ohm"); + // activeSerial->println("20K Ohm"); break; case HSTIARTIA_40K: - // Serial.println("40K Ohm"); + // activeSerial->println("40K Ohm"); break; case HSTIARTIA_80K: - // Serial.println("80K Ohm"); + // activeSerial->println("80K Ohm"); break; case HSTIARTIA_160K: - // Serial.println("160K Ohm"); + // activeSerial->println("160K Ohm"); break; default: - // Serial.println("Unknown"); + // activeSerial->println("Unknown"); break; } } @@ -2958,11 +3035,11 @@ { if (AD5940_IsAdcMaxSaturatedAndClear()) { - // Serial.println("SaturationFlag tripped!"); + // activeSerial->println("SaturationFlag tripped!"); } else { - // Serial.println("SaturationFlag NOT tripped!"); + // activeSerial->println("SaturationFlag NOT tripped!"); } } float medianMag; @@ -2979,21 +3056,21 @@ medianPhase = calculateMedian(phaseArray, repeatNumber); } - // Serial.printf("Freq: %.2f Hz ", storedFrequency); + // activeSerial->printf("Freq: %.2f Hz ", storedFrequency); // Print the number of data points - // Serial.printf("DataPoints: %lu ", 1); + // activeSerial->printf("DataPoints: %lu ", 1); // Print magnitude in ohms and phase in degrees // Note: Converting phase from radians to degrees (phase * 180 / π) - // Serial.printf("RzMag: %.2f Ohm, RzPhase: %.2f deg", + // activeSerial->printf("RzMag: %.2f Ohm, RzPhase: %.2f deg", // medianMag, // medianPhase); // Add separator and perform RTD (temperature) measurement - // Serial.print(";"); + // activeSerial->print(";"); float rtd_res = getRTDMeasurements(rtdVoltageValue); - // Serial.print("*"); + // activeSerial->print("*"); previousMillis = millis(); // Check for "ERROR: AD5940 wakeup timeout" @@ -3013,8 +3090,7 @@ singleSensorPacket.rtdRzMag = rtd_res; // Value of rtd_resistance singleSensorPacket.rtdRzPhase = 0.0; // RTD Rz Phase. Hard coded to 0.0 } - Serial.write((uint8_t *)&singleSensorPacket, sizeof(singleSensorPacket)); - Serial1.write((uint8_t *)&singleSensorPacket, sizeof(singleSensorPacket)); + activeSerial->write((uint8_t *)&singleSensorPacket, sizeof(singleSensorPacket)); } float getRTDMeasurements(float sensor_mV) @@ -3031,7 +3107,7 @@ // Wake up the AD5940 from low power mode if (AD5940_WakeUp(10) > 10) { - // Serial.println("ERROR: AD5940 wakeup timeout"); + // activeSerial->println("ERROR: AD5940 wakeup timeout"); return -1000.0f; } @@ -3145,44 +3221,44 @@ // Verbose output if (verboseMode) { - Serial.println(" "); + activeSerial->println(" "); - // Serial.println("RTD Measurement"); - // Serial.print(" RCal Averaged Measurement: "); - Serial.println(adcCode_ref); - // Serial.print(" RTD Averaged Measurement: "); - Serial.println(adcCode_rtd); - // Serial.printf(" NUM_SAMPLES: %u", NUM_RTD_SAMPLES); - Serial.println(" "); - // Serial.print(" RTD TIA Resistor: "); + // activeSerial->println("RTD Measurement"); + // activeSerial->print(" RCal Averaged Measurement: "); + activeSerial->println(adcCode_ref); + // activeSerial->print(" RTD Averaged Measurement: "); + activeSerial->println(adcCode_rtd); + // activeSerial->printf(" NUM_SAMPLES: %u", NUM_RTD_SAMPLES); + activeSerial->println(" "); + // activeSerial->print(" RTD TIA Resistor: "); switch (RTD_RTIA) { case HSTIARTIA_200: - // Serial.println("200 Ohm"); + // activeSerial->println("200 Ohm"); break; case HSTIARTIA_1K: - // Serial.println("1K Ohm"); + // activeSerial->println("1K Ohm"); break; case HSTIARTIA_5K: - // Serial.println("5K Ohm"); + // activeSerial->println("5K Ohm"); break; case HSTIARTIA_10K: - // Serial.println("10K Ohm"); + // activeSerial->println("10K Ohm"); break; case HSTIARTIA_20K: - // Serial.println("20K Ohm"); + // activeSerial->println("20K Ohm"); break; case HSTIARTIA_40K: - // Serial.println("40K Ohm"); + // activeSerial->println("40K Ohm"); break; case HSTIARTIA_80K: - // Serial.println("80K Ohm"); + // activeSerial->println("80K Ohm"); break; case HSTIARTIA_160K: - // Serial.println("160K Ohm"); + // activeSerial->println("160K Ohm"); break; default: - // Serial.println("Unknown"); + // activeSerial->println("Unknown"); break; } } @@ -3196,7 +3272,7 @@ if (firstComma < 0) { updateEepromStatus = UPDATE_EEPROM_STATUS_INVALID_CMD; - // Serial.println("Error: Invalid save command format"); + // activeSerial->println("Error: Invalid save command format"); return; } String dataStr = command.substring(firstComma + 1); @@ -3247,19 +3323,19 @@ // Check if we got at least 1 value if (valueIndex == 0) { - // Serial.println("Error: No valid values found"); + // activeSerial->println("Error: No valid values found"); updateEepromStatus = UPDATE_EEPROM_STATUS_NO_VALID_VALUES; return; } if (valueIndex > maxTotal) { - // Serial.print("Error: Too many values, maximum is "); - // Serial.print(maxTotal); - // Serial.print(" ("); - // Serial.print(DOUBLE_COUNT); - // Serial.print(" doubles + "); - // Serial.print(maxFloats); - // Serial.println(" floats)"); + // activeSerial->print("Error: Too many values, maximum is "); + // activeSerial->print(maxTotal); + // activeSerial->print(" ("); + // activeSerial->print(DOUBLE_COUNT); + // activeSerial->print(" doubles + "); + // activeSerial->print(maxFloats); + // activeSerial->println(" floats)"); updateEepromStatus = UPDATE_EEPROM_STATUS_TOO_MANY_VALUES; return; } @@ -3268,34 +3344,33 @@ int floatCount = max(0, valueIndex - DOUBLE_COUNT); // Display the values and ask for confirmation - // Serial.print("Preparing to save "); - // Serial.print(valueIndex); - // Serial.print(" values to EEPROM ("); - // Serial.print(doubleCount); - // Serial.print(" doubles, "); - // Serial.print(floatCount); - // Serial.println(" floats):"); + // activeSerial->print("Preparing to save "); + // activeSerial->print(valueIndex); + // activeSerial->print(" values to EEPROM ("); + // activeSerial->print(doubleCount); + // activeSerial->print(" doubles, "); + // activeSerial->print(floatCount); + // activeSerial->println(" floats):"); // // Display double values // for (int i = 0; i < doubleCount; i++) // { - // Serial.print(i); - // Serial.print(" (double): "); - // Serial.println(doubleValues[i], 10); + // activeSerial->print(i); + // activeSerial->print(" (double): "); + // activeSerial->println(doubleValues[i], 10); // } // // Display float values // for (int i = 0; i < floatCount; i++) // { - // Serial.print(i + DOUBLE_COUNT); - // Serial.print(" (float): "); - // Serial.println(floatValues[i], 6); // Floats typically have 6-7 significant digits + // activeSerial->print(i + DOUBLE_COUNT); + // activeSerial->print(" (float): "); + // activeSerial->println(floatValues[i], 6); // Floats typically have 6-7 significant digits // } - // Serial.println("Confirm write to EEPROM? (y/n)"); + // activeSerial->println("Confirm write to EEPROM? (y/n)"); updateEepromStatus = UPDATE_EEPROM_STATUS_WAITING_FOR_CONFIRMATION; - Serial.write((uint8_t *)&updateEepromStatus, sizeof(updateEepromStatus)); - Serial1.write((uint8_t *)&updateEepromStatus, sizeof(updateEepromStatus)); + activeSerial->write((uint8_t *)&updateEepromStatus, sizeof(updateEepromStatus)); // Wait for user confirmation unsigned long startTime = millis(); @@ -3306,74 +3381,74 @@ if (millis() - startTime > timeout) { updateEepromStatus = UPDATE_EEPROM_STATUS_CONFIRMATION_TIMEOUT; - // Serial.println("Timed out waiting for confirmation. Operation aborted."); + // activeSerial->println("Timed out waiting for confirmation. Operation aborted."); return; } // Check if data is available to read - if (Serial.available() > 0) + if (activeSerial->available() > 0) { - char response = Serial.read(); + char response = activeSerial->read(); // Clear any remaining characters in buffer (like newline) - while (Serial.available() > 0) + while (activeSerial->available() > 0) { - Serial.read(); + activeSerial->read(); } // Process response if (response == 'y' || response == 'Y') { // User confirmed, write to EEPROM unsigned int baseAddress = 0; writeMixedValues(baseAddress, doubleValues, doubleCount, floatValues, floatCount); - // Serial.println("save attempted"); + // activeSerial->println("save attempted"); // Read back the values to confirm they were written correctly double readDoubles[DOUBLE_COUNT]; float readFloats[maxFloats]; readMixedValues(baseAddress, readDoubles, doubleCount, readFloats, floatCount); - // Serial.println("Verification - Values read back from EEPROM:"); + // activeSerial->println("Verification - Values read back from EEPROM:"); bool verificationSuccess = true; // Verify doubles for (int i = 0; i < doubleCount; i++) { - // Serial.print(i); - // Serial.print(" (double): "); - // Serial.println(readDoubles[i], 10); + // activeSerial->print(i); + // activeSerial->print(" (double): "); + // activeSerial->println(readDoubles[i], 10); if (abs(doubleValues[i] - readDoubles[i]) > 0.000000001) { verificationSuccess = false; - // Serial.print("Warning: Double value "); - // Serial.print(i); - // Serial.println(" does not match exactly what was written"); + // activeSerial->print("Warning: Double value "); + // activeSerial->print(i); + // activeSerial->println(" does not match exactly what was written"); updateEepromStatus = UPDATE_EEPROM_STATUS_ERR_DOUBLE_VALUES; } } // Verify floats for (int i = 0; i < floatCount; i++) { - // Serial.print(i + DOUBLE_COUNT); - // Serial.print(" (float): "); - // Serial.println(readFloats[i], 6); + // activeSerial->print(i + DOUBLE_COUNT); + // activeSerial->print(" (float): "); + // activeSerial->println(readFloats[i], 6); if (abs(floatValues[i] - readFloats[i]) > 0.000001) { verificationSuccess = false; - // Serial.print("Warning: Float value "); - // Serial.print(i + DOUBLE_COUNT); - // Serial.println(" does not match exactly what was written"); + // activeSerial->print("Warning: Float value "); + // activeSerial->print(i + DOUBLE_COUNT); + // activeSerial->println(" does not match exactly what was written"); updateEepromStatus = UPDATE_EEPROM_STATUS_ERR_FLOAT_VALUES; } } if (verificationSuccess) { updateEepromStatus = UPDATE_EEPROM_STATUS_VALUES_VERIFIED; - // Serial.println("Verification successful: All values match!"); + // activeSerial->println("Verification successful: All values match!"); } // else // { - // // Serial.println("Verification Failed, confirm device attached and powered."); + // // activeSerial->println("Verification Failed, confirm device attached and powered."); // } return; } @@ -3382,14 +3457,14 @@ updateEepromStatus = UPDATE_EEPROM_STATUS_OPERATION_ABORTED; // User aborted - // Serial.println("Operation aborted by user."); + // activeSerial->println("Operation aborted by user."); return; } else { updateEepromStatus = UPDATE_EEPROM_STATUS_INVALID_RESPONSE; // Invalid response, ask again - // Serial.println("Please enter 'y' to confirm or 'n' to abort:"); + // activeSerial->println("Please enter 'y' to confirm or 'n' to abort:"); } } // Small delay to prevent CPU hogging @@ -3421,8 +3496,7 @@ eepromDataPacket.floatValue[i] = floatValues[i]; } - Serial.write((uint8_t *)&eepromDataPacket, sizeof(eepromDataPacket)); - Serial1.write((uint8_t *)&eepromDataPacket, sizeof(eepromDataPacket)); + activeSerial->write((uint8_t *)&eepromDataPacket, sizeof(eepromDataPacket)); } void updateMeasurementSettings(String cmd) @@ -3470,13 +3544,13 @@ if (param == "save") { saveCurrentConfig(); - // Serial.println("Configuration saved"); + // activeSerial->println("Configuration saved"); return; } else if (param == "recall") { recallSavedConfig(); - // Serial.println("Configuration recalled"); + // activeSerial->println("Configuration recalled"); return; } @@ -3485,27 +3559,27 @@ { // Set sine wave frequency (Hz) pImpedanceCfg->SinFreq = value.toFloat(); - // Serial.printf("Set SinFreq to: %.2f Hz\n", pImpedanceCfg->SinFreq); + // activeSerial->printf("Set SinFreq to: %.2f Hz\n", pImpedanceCfg->SinFreq); } else if (param == "dacpp") { // Set DAC peak-to-peak voltage (mV) pImpedanceCfg->DacVoltPP = value.toFloat(); - // Serial.printf("Set DacVoltPP to: %.2f mV\n", pImpedanceCfg->DacVoltPP); + // activeSerial->printf("Set DacVoltPP to: %.2f mV\n", pImpedanceCfg->DacVoltPP); } else if (param == "bias") { // Set DC bias voltage (mV) pImpedanceCfg->BiasVolt = value.toFloat(); - // Serial.printf("Set BiasVolt to: %.2f mV\n", pImpedanceCfg->BiasVolt); + // activeSerial->printf("Set BiasVolt to: %.2f mV\n", pImpedanceCfg->BiasVolt); } else if (param == "rtia") { // Set TIA (Transimpedance Amplifier) feedback resistor value uint32_t rtia = DEFAULT_RTIA; // default value int valueTest = value.toInt(); - // Serial.print("Value:"); - // Serial.println(value); + // activeSerial->print("Value:"); + // activeSerial->println(value); // Map string values to corresponding constants if (valueTest == 0) rtia = HSTIARTIA_200; @@ -3525,13 +3599,13 @@ rtia = HSTIARTIA_160K; else updateCfgStataus = UPDATE_CFG_STATUS_NO_CHANGE_TO_TIA; - // Serial.print("no change to tia"); + // activeSerial->print("no change to tia"); pImpedanceCfg->HstiaRtiaSel = rtia; - // Serial.printf("Set RTIA to: %s\n", value.c_str()); + // activeSerial->printf("Set RTIA to: %s\n", value.c_str()); currentTIA = rtia; - // Serial.print("currentTIA: "); - // Serial.println(currentTIA); + // activeSerial->print("currentTIA: "); + // activeSerial->println(currentTIA); } else if (param == "pga") { @@ -3553,7 +3627,7 @@ updateCfgStataus = UPDATE_CFG_STATUS_NO_CHANGE_TO_PGA; pImpedanceCfg->AdcPgaGain = pga; - // Serial.printf("Set PGA gain to: %s\n", value.c_str()); + // activeSerial->printf("Set PGA gain to: %s\n", value.c_str()); } else if (param == "dftnum") { @@ -3575,7 +3649,7 @@ updateCfgStataus = UPDATE_CFG_STATUS_NO_CHANGE_TO_DFT_NUM; pImpedanceCfg->DftNum = dft; - // Serial.printf("Set DFT number to: %s\n", value.c_str()); + // activeSerial->printf("Set DFT number to: %s\n", value.c_str()); } else if (param == "avgnum") { @@ -3595,44 +3669,44 @@ updateCfgStataus = UPDATE_CFG_STATUS_NO_CHANGE_TO_AVG_NUM; pImpedanceCfg->ADCAvgNum = avg; - // Serial.printf("Set ADC average number to: %s\n", value.c_str()); + // activeSerial->printf("Set ADC average number to: %s\n", value.c_str()); } else if (param == "sweep") { // Enable/disable frequency sweep mode bool enableSweep = (value == "1" || value.equalsIgnoreCase("true")); pImpedanceCfg->SweepCfg.SweepEn = enableSweep ? bTRUE : bFALSE; - // Serial.printf("Set sweep enable to: %d\n", pImpedanceCfg->SweepCfg.SweepEn); + // activeSerial->printf("Set sweep enable to: %d\n", pImpedanceCfg->SweepCfg.SweepEn); } else if (param == "sweepstart") { // Set sweep start frequency (Hz) pImpedanceCfg->SweepCfg.SweepStart = value.toFloat(); - // Serial.printf("Set sweep start frequency to: %.2f Hz\n", pImpedanceCfg->SweepCfg.SweepStart); + // activeSerial->printf("Set sweep start frequency to: %.2f Hz\n", pImpedanceCfg->SweepCfg.SweepStart); } else if (param == "sweepstop") { // Set sweep stop frequency (Hz) pImpedanceCfg->SweepCfg.SweepStop = value.toFloat(); - // Serial.printf("Set sweep stop frequency to: %.2f Hz\n", pImpedanceCfg->SweepCfg.SweepStop); + // activeSerial->printf("Set sweep stop frequency to: %.2f Hz\n", pImpedanceCfg->SweepCfg.SweepStop); } else if (param == "sweeppoints") { // Set number of frequency points in the sweep pImpedanceCfg->SweepCfg.SweepPoints = value.toInt(); - // Serial.printf("Set sweep points to: %d\n", pImpedanceCfg->SweepCfg.SweepPoints); + // activeSerial->printf("Set sweep points to: %d\n", pImpedanceCfg->SweepCfg.SweepPoints); } else if (param == "sweeplog") { // Set logarithmic (true) or linear (false) frequency spacing bool logSpacing = (value == "1" || value.equalsIgnoreCase("true")); pImpedanceCfg->SweepCfg.SweepLog = logSpacing ? bTRUE : bFALSE; - // Serial.printf("Set sweep log mode to: %d\n", pImpedanceCfg->SweepCfg.SweepLog); + // activeSerial->printf("Set sweep log mode to: %d\n", pImpedanceCfg->SweepCfg.SweepLog); } else { // Handle unrecognized parameter - // Serial.println("Malformed command: unrecognized parameter"); + // activeSerial->println("Malformed command: unrecognized parameter"); updateCfgStataus = UPDATE_CFG_STATUS_ERR_UNRECOGNIZED_PARAM; return; } @@ -3658,8 +3732,7 @@ measurementSettingsPacket.AdcPgaGain = cfg->AdcPgaGain; measurementSettingsPacket.DftNum = cfg->DftNum; measurementSettingsPacket.ADCAvgNum = cfg->ADCAvgNum; - Serial.write((uint8_t *)&measurementSettingsPacket, sizeof(measurementSettingsPacket)); - Serial1.write((uint8_t *)&measurementSettingsPacket, sizeof(measurementSettingsPacket)); + activeSerial->write((uint8_t *)&measurementSettingsPacket, sizeof(measurementSettingsPacket)); } void getInitStatus(void) @@ -3707,8 +3780,7 @@ } } - Serial.write((uint8_t *)&initStatus, sizeof(initStatus)); - Serial1.write((uint8_t *)&initStatus, sizeof(initStatus)); + activeSerial->write((uint8_t *)&initStatus, sizeof(initStatus)); } void sendAllSensorData( void ) @@ -3717,7 +3789,7 @@ while(sendSensorData) { // Read a line from the serial port until newline character - String command = Serial.readStringUntil('\n'); + String command = activeSerial->readStringUntil('\n'); if(command.length() > 0) {