Hardware Prototype Timeline
flux
3V3, GND, I2C_SDA, and I2C_SCL.HEATER_LOW_SIDE trace passing R10 with only about 0.36 mm local copper separation. It technically passes the present clearance rule, but it is poor margin in a noisy switching area.flux
Waiting for input
0x29. If a different RGB/clear sensor is fitted, replace only the optical driver and preserve the safety state machine.platformio.ini:Ini
[env:pico] platform = https://github.com/maxgerhardt/platform-raspberrypi.git board = pico framework = arduino board_build.core = earlephilhower monitor_speed = 115200 lib_deps = adafruit/Adafruit ADS1X15 adafruit/Adafruit MAX31856 library adafruit/Adafruit TCS34725
Bash
python -m pip install --upgrade platformio pio run pio run -t upload pio device monitor -b 115200
RPI-RP2 mass-storage drive.pio run, then copy .pio/build/pico/firmware.uf2 onto RPI-RP2.pio device monitor -b 115200 and send commands followed by Enter.Table
| Pico signal | GPIO | Schematic net/function |
|---|---|---|
| SDA | GP4 | I2C_SDA: U2, J7, J9 |
| SCL | GP5 | I2C_SCL: U2, J7, J9 |
| ADC ready | GP6 | ADC_DRDY |
| white/red/green/blue | GP10/11/12/13 | LED_*_CMD |
| optical INT | GP14 | OPT_INT |
| status LED | GP15 | STATUS_LED_CMD |
| heater PWM | GP16 | HEATER_PWM_CMD into hardware AND U4 |
| interlock monitor | GP17 | INTERLOCK_MON |
| SPI SCK/MOSI/MISO/CS | GP18/19/20/21 | MAX31856 |
| TC DRDY/FAULT | GP22/GP26 | TC_DRDY_N, TC_FAULT_N |
src/main.cppCpp
#include <Arduino.h> #include <Wire.h> #include <SPI.h> #include <math.h> #include <Adafruit_ADS1X15.h> #include <Adafruit_MAX31856.h> #include <Adafruit_TCS34725.h> constexpr uint8_t PIN_ADC_RDY=6, PIN_LED_W=10, PIN_LED_R=11, PIN_LED_G=12; constexpr uint8_t PIN_LED_B=13, PIN_OPT_INT=14, PIN_STATUS=15, PIN_HEATER=16; constexpr uint8_t PIN_INTERLOCK=17, PIN_TC_SCK=18, PIN_TC_MOSI=19; constexpr uint8_t PIN_TC_MISO=20, PIN_TC_CS=21, PIN_TC_DRDY=22, PIN_TC_FAULT=26; constexpr float SETPOINT_C=65.0f, HARD_BLOCK_LIMIT_C=75.0f, HARD_LIQUID_LIMIT_C=72.0f; constexpr uint32_t CONTROL_MS=100, LOG_MS=200, LIQUID_HISTORY_MS=1000; constexpr uint32_t TC_STALE_MS=1000, TC_OPEN_CIRCUIT_VALID_MS=2000; constexpr uint32_t ACTIVE_CYCLE_TIMEOUT_MS=90UL*60UL*1000UL; // configurable experiment bound constexpr uint32_t EQUIL_WINDOW_MS=60000; constexpr float EQUIL_BAND_C=0.5f, EQUIL_MAX_SLOPE_C_PER_MIN=0.1f; constexpr float BLOCK_MIN_C=-20.0f, BLOCK_MAX_C=150.0f, BLOCK_MAX_RATE_C_PER_S=30.0f; constexpr float LIQUID_MIN_C=-50.0f, LIQUID_MAX_C=150.0f, LIQUID_MAX_RATE_C_PER_S=20.0f; constexpr size_t LIQUID_HISTORY_N=61; // 61 one-second samples span 60 seconds Adafruit_ADS1115 ads; Adafruit_MAX31856 tc(PIN_TC_CS, &SPI); Adafruit_TCS34725 rgb(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X); bool adsOK=false, tcOK=false, rgbOK=false; enum class State { SAFE, PREHEAT, WAIT_INSERT, EQUILIBRATE, RUN, FAULT }; State state=State::SAFE; String fault="none"; float blockC=NAN, liquidC=NAN, integral=0.0f, previousError=0.0f; float liquidSlopeCPerMin=NAN; int16_t adsCode=0; uint8_t duty=0; uint32_t lastControl=0, lastLog=0, lastLiquidHistory=0, bandSince=0, runStartMs=0; uint32_t cycleStartMs=0; uint32_t lastTcSampleMs=0, lastBlockSampleMs=0; uint8_t tcFaultNow=0, tcFaultLatched=0; bool tcStartupValidated=false; float previousBlockC=NAN; char lastOptLed='D'; uint16_t optR=0,optG=0,optB=0,optC=0; uint16_t darkR=0,darkG=0,darkB=0,darkC=0; uint32_t lastOptCommandMs=0; float liquidHistoryC[LIQUID_HISTORY_N]; uint32_t liquidHistoryT[LIQUID_HISTORY_N]; size_t liquidHead=0, liquidCount=0; char commandBuffer[32]; size_t commandLength=0; const char* stateName(){ switch(state){ case State::SAFE:return "SAFE"; case State::PREHEAT:return "PREHEAT"; case State::WAIT_INSERT:return "WAIT_INSERT"; case State::EQUILIBRATE:return "EQUILIBRATE"; case State::RUN:return "RUN"; default:return "FAULT"; } } bool activeThermalState(){ return state==State::PREHEAT || state==State::WAIT_INSERT || state==State::EQUILIBRATE || state==State::RUN; } bool interlockOK(){ return digitalRead(PIN_INTERLOCK)==HIGH; } void allEmittersOff(){ digitalWrite(PIN_LED_W,LOW); digitalWrite(PIN_LED_R,LOW); digitalWrite(PIN_LED_G,LOW); digitalWrite(PIN_LED_B,LOW); } void heaterOff(){ duty=0; analogWrite(PIN_HEATER,0); } void clearEquilibriumHistory(){ liquidHead=0; liquidCount=0; liquidSlopeCPerMin=NAN; lastLiquidHistory=0; bandSince=0; } void trip(const char* why){ heaterOff(); allEmittersOff(); clearEquilibriumHistory(); fault=why; state=State::FAULT; } void retainTcFault(uint8_t code){ tcFaultNow=code; tcFaultLatched|=code; } float readBlockC(){ adsCode=ads.readADC_SingleEnded(0); const float v=ads.computeVolts(adsCode); const float vref=3.3f, rFixed=10000.0f; // replace vref with calibrated measured rail if(v<=0.01f || v>=vref-0.01f) return NAN; const float rNtc=rFixed*v/(vref-v); // NTC is low-side at J5 const float r0=10000.0f, beta=3950.0f, t0=298.15f; // provisional; replace with calibration fit return 1.0f/(1.0f/t0 + logf(rNtc/r0)/beta)-273.15f; } bool sampleThermocouple(uint32_t now){ if(!tcOK || digitalRead(PIN_TC_DRDY)!=LOW) return false; retainTcFault(tc.readFault()); if(tcFaultNow!=0){ if(activeThermalState()) trip("thermocouple_fault"); return false; } const float next=tc.readThermocoupleTemperature(); if(!isfinite(next) || next<LIQUID_MIN_C || next>LIQUID_MAX_C){ if(activeThermalState()) trip("liquid_implausible"); return false; } if(isfinite(liquidC) && lastTcSampleMs!=0){ const float dt=(now-lastTcSampleMs)/1000.0f; if(dt>0.0f && fabsf(next-liquidC)/dt>LIQUID_MAX_RATE_C_PER_S){ if(activeThermalState()) trip("liquid_jump"); return false; } } liquidC=next; lastTcSampleMs=now; return true; } void driveEmitter(char ch){ allEmittersOff(); if(ch=='W') digitalWrite(PIN_LED_W,HIGH); else if(ch=='R') digitalWrite(PIN_LED_R,HIGH); else if(ch=='G') digitalWrite(PIN_LED_G,HIGH); else if(ch=='B') digitalWrite(PIN_LED_B,HIGH); } void acquireOptical(char ch){ lastOptLed=ch; if(!rgbOK){ optR=optG=optB=optC=0; lastOptLed='X'; return; } const uint32_t started=millis(); driveEmitter(ch); // 'D' leaves every emitter off delay(ch=='D' ? 10 : 60); // off-settle or emitter warm-up rgb.getRawData(&optR,&optG,&optB,&optC); allEmittersOff(); lastOptCommandMs=millis()-started; if(ch=='D'){ darkR=optR; darkG=optG; darkB=optB; darkC=optC; } } void pushLiquidHistory(uint32_t now){ if(state!=State::EQUILIBRATE || !isfinite(liquidC)) return; if(lastLiquidHistory!=0 && now-lastLiquidHistory<LIQUID_HISTORY_MS) return; lastLiquidHistory=now; liquidHistoryC[liquidHead]=liquidC; liquidHistoryT[liquidHead]=now; liquidHead=(liquidHead+1)%LIQUID_HISTORY_N; if(liquidCount<LIQUID_HISTORY_N) ++liquidCount; if(fabsf(liquidC-SETPOINT_C)<=EQUIL_BAND_C){ if(bandSince==0) bandSince=now; } else { bandSince=0; } liquidSlopeCPerMin=NAN; if(liquidCount==LIQUID_HISTORY_N){ const size_t oldest=liquidHead; const size_t newest=(liquidHead+LIQUID_HISTORY_N-1)%LIQUID_HISTORY_N; const uint32_t span=liquidHistoryT[newest]-liquidHistoryT[oldest]; bool cadenceOK=span>=EQUIL_WINDOW_MS; double sumT=0.0,sumY=0.0,sumTT=0.0,sumTY=0.0; uint32_t previousT=liquidHistoryT[oldest]; for(size_t n=0;n<LIQUID_HISTORY_N;n++){ const size_t i=(oldest+n)%LIQUID_HISTORY_N; if(n>0 && liquidHistoryT[i]-previousT>1500) cadenceOK=false; previousT=liquidHistoryT[i]; const double t=(liquidHistoryT[i]-liquidHistoryT[oldest])/60000.0; const double y=liquidHistoryC[i]; sumT+=t; sumY+=y; sumTT+=t*t; sumTY+=t*y; } const double denominator=LIQUID_HISTORY_N*sumTT-sumT*sumT; if(cadenceOK && denominator>0.0) liquidSlopeCPerMin=(float)((LIQUID_HISTORY_N*sumTY-sumT*sumY)/denominator); } } bool liquidEquilibrated(uint32_t now){ const bool heldBand=bandSince!=0 && now-bandSince>=EQUIL_WINDOW_MS; const bool slopeOK=isfinite(liquidSlopeCPerMin) && fabsf(liquidSlopeCPerMin)<EQUIL_MAX_SLOPE_C_PER_MIN; bool allSamplesInBand=liquidCount==LIQUID_HISTORY_N; for(size_t n=0;n<liquidCount;n++){ const size_t i=(liquidHead+LIQUID_HISTORY_N-liquidCount+n)%LIQUID_HISTORY_N; if(fabsf(liquidHistoryC[i]-SETPOINT_C)>EQUIL_BAND_C) allSamplesInBand=false; } return heldBand && allSamplesInBand && slopeOK; } void controlHeater(){ const uint32_t now=millis(); if(activeThermalState() && cycleStartMs!=0 && now-cycleStartMs>=ACTIVE_CYCLE_TIMEOUT_MS){ trip("active_cycle_timeout"); return; } blockC=adsOK?readBlockC():NAN; if(!isfinite(blockC)){ trip("block_sensor"); return; } if(blockC<BLOCK_MIN_C || blockC>BLOCK_MAX_C){ trip("block_implausible"); return; } if(isfinite(previousBlockC) && lastBlockSampleMs!=0){ const float dt=(now-lastBlockSampleMs)/1000.0f; if(dt>0.0f && fabsf(blockC-previousBlockC)/dt>BLOCK_MAX_RATE_C_PER_S){ trip("block_jump"); return; } } previousBlockC=blockC; lastBlockSampleMs=now; sampleThermocouple(now); if(state==State::FAULT) return; if(activeThermalState() && (!tcOK || lastTcSampleMs==0 || now-lastTcSampleMs>TC_STALE_MS)){ trip("thermocouple_stale"); return; } if(blockC>HARD_BLOCK_LIMIT_C){ trip("block_overtemp"); return; } if(isfinite(liquidC) && liquidC>HARD_LIQUID_LIMIT_C){ trip("liquid_overtemp"); return; } if(!interlockOK()){ heaterOff(); clearEquilibriumHistory(); runStartMs=0; if(state!=State::SAFE && state!=State::FAULT) state=State::WAIT_INSERT; return; } if(!activeThermalState()){ heaterOff(); return; } // PREHEAT, WAIT_INSERT, EQUILIBRATE, and RUN all maintain the block setpoint // while the guard is closed. Re-closing the guard never advances WAIT_INSERT. const float e=SETPOINT_C-blockC; integral=constrain(integral + e*0.1f,-30.0f,30.0f); const float derivative=(e-previousError)/0.1f; previousError=e; const float u=18.0f*e + 0.8f*integral + 2.0f*derivative; // conservative starter only duty=(uint8_t)constrain(u,0.0f,255.0f); analogWrite(PIN_HEATER,duty); if(state==State::PREHEAT && fabsf(blockC-SETPOINT_C)<=EQUIL_BAND_C){ state=State::WAIT_INSERT; } pushLiquidHistory(now); if(state==State::EQUILIBRATE && liquidEquilibrated(now)){ runStartMs=now; state=State::RUN; } } void printCSV(){ const uint32_t runElapsedMs=(state==State::RUN && runStartMs!=0)?millis()-runStartMs:0; const uint32_t cycleElapsedMs=(cycleStartMs!=0)?millis()-cycleStartMs:0; Serial.printf("%lu,%s,%s,%.3f,%.3f,%d,%u,%d,%u,%u,%c,%u,%u,%u,%u,%u,%u,%u,%u,%.4f,%d,%lu,%lu,%lu\n", millis(),stateName(),fault.c_str(),blockC,liquidC,adsCode,duty,interlockOK(), tcFaultNow,tcFaultLatched,lastOptLed,optR,optG,optB,optC,darkR,darkG,darkB,darkC, liquidSlopeCPerMin,liquidEquilibrated(millis()),lastOptCommandMs,runElapsedMs,cycleElapsedMs); } void handleCommand(String s){ s.trim(); s.toUpperCase(); if(s=="ARM" && state==State::SAFE && interlockOK()){ if(tcOK) retainTcFault(tc.readFault()); if(!adsOK || !tcOK || !tcStartupValidated || tcFaultNow!=0 || digitalRead(PIN_TC_FAULT)==LOW) trip("thermal_init"); else { fault="none"; integral=0; previousError=0; runStartMs=0; cycleStartMs=millis(); clearEquilibriumHistory(); state=State::PREHEAT; } } else if(s=="INSERT" && state==State::WAIT_INSERT && interlockOK()){ clearEquilibriumHistory(); state=State::EQUILIBRATE; } else if(s=="STOP"){ heaterOff(); allEmittersOff(); runStartMs=0; cycleStartMs=0; clearEquilibriumHistory(); state=State::SAFE; } else if(s=="CLEAR" && state==State::FAULT && interlockOK() && isfinite(blockC) && blockC<70.0f){ fault="none"; cycleStartMs=0; state=State::SAFE; // tcFaultLatched intentionally retained for diagnosis } else if(s=="DARK") acquireOptical('D'); else if(s=="WHITE") acquireOptical('W'); else if(s=="RED") acquireOptical('R'); else if(s=="GREEN") acquireOptical('G'); else if(s=="BLUE") acquireOptical('B'); } void pollSerial(){ while(Serial.available()){ const char c=(char)Serial.read(); if(c=='\r') continue; if(c=='\n'){ commandBuffer[commandLength]='\0'; if(commandLength) handleCommand(String(commandBuffer)); commandLength=0; } else if(commandLength<sizeof(commandBuffer)-1){ commandBuffer[commandLength++]=c; } else { commandLength=0; // discard an overlength command without blocking control } } } void setup(){ pinMode(PIN_HEATER,OUTPUT); heaterOff(); const uint8_t outputs[]={PIN_LED_W,PIN_LED_R,PIN_LED_G,PIN_LED_B,PIN_STATUS}; for(uint8_t p:outputs) pinMode(p,OUTPUT); allEmittersOff(); digitalWrite(PIN_STATUS,LOW); pinMode(PIN_INTERLOCK,INPUT); pinMode(PIN_ADC_RDY,INPUT_PULLUP); pinMode(PIN_OPT_INT,INPUT_PULLUP); pinMode(PIN_TC_DRDY,INPUT_PULLUP); pinMode(PIN_TC_FAULT,INPUT_PULLUP); analogWriteFreq(1000); analogWriteRange(255); Serial.begin(115200); while(!Serial && millis()<3000) delay(10); Wire.setSDA(4); Wire.setSCL(5); Wire.begin(); adsOK=ads.begin(0x48,&Wire); if(adsOK) ads.setGain(GAIN_ONE); // +/-4.096 V range SPI.setSCK(PIN_TC_SCK); SPI.setTX(PIN_TC_MOSI); SPI.setRX(PIN_TC_MISO); SPI.begin(); tcOK=tc.begin(); if(tcOK){ tc.setThermocoupleType(MAX31856_TCTYPE_K); tc.setNoiseFilter(MAX31856_NOISE_FILTER_60HZ); tc.setConversionMode(MAX31856_CONTINUOUS); // Adafruit begin() configures automatic open-circuit mode 01. In automatic // conversion that test occurs once per 16 conversions; 2.0 s exceeds the // 60 Hz-filter worst-case sequence plus the fault-test interval. const uint32_t tcQualificationStart=millis(); while(millis()-tcQualificationStart<TC_OPEN_CIRCUIT_VALID_MS) delay(1); // startup only retainTcFault(tc.readFault()); tcStartupValidated=digitalRead(PIN_TC_DRDY)==LOW && digitalRead(PIN_TC_FAULT)==HIGH && tcFaultNow==0; if(!tcStartupValidated) tcOK=false; else { liquidC=tc.readThermocoupleTemperature(); tcOK=isfinite(liquidC) && liquidC>=LIQUID_MIN_C && liquidC<=LIQUID_MAX_C; tcStartupValidated=tcOK; if(tcOK) lastTcSampleMs=millis(); } } rgbOK=rgb.begin(TCS34725_ADDRESS,&Wire); Serial.println("timestamp_ms,state,fault,block_c,liquid_c,ads_code,heater_duty,interlock,tc_fault_now,tc_fault_latched,opt_led,opt_r,opt_g,opt_b,opt_clear,dark_r,dark_g,dark_b,dark_clear,liquid_slope_c_per_min,liquid_equilibrated,opt_command_ms,run_elapsed_ms,cycle_elapsed_ms"); } void loop(){ pollSerial(); if(tcOK && digitalRead(PIN_TC_FAULT)==LOW){ retainTcFault(tc.readFault()); if(activeThermalState()) trip("thermocouple_fault"); } const uint32_t now=millis(); if(now-lastControl>=CONTROL_MS){ lastControl=now; controlHeater(); } if(now-lastLog>=LOG_MS){ lastLog=now; digitalWrite(PIN_STATUS,state!=State::FAULT && ((now/500)&1)); printCSV(); } }
ARM preheats the empty block. Entering WAIT_INSERT does not turn heat off while the guard is closed; the controller continues maintaining the block at 65 °C.WAIT_INSERT. Re-closing the guard resumes block-temperature maintenance but remains in WAIT_INSERT; only an explicit INSERT command starts EQUILIBRATE.01. Startup waits 2.0 s—longer than the worst-case first plus 15 subsequent 60 Hz conversions and the mode-01 fault-test interval—then reads and latches the detailed fault register before ARM can succeed.FAULT if samples become stale for more than 1 s, the hardware fault pin/status register asserts, or a sample/rate is implausible. tc_fault_latched preserves every observed MAX31856 status bit across CLEAR for diagnosis.RUN.FAULT and turns heater and emitters off.ARM; expiry latches active_cycle_timeout and forces heater/emitter outputs off. Change and validate ACTIVE_CYCLE_TIMEOUT_MS for experiments that require a different bound.timestamp_ms,state,fault,block_c,liquid_c,ads_code,heater_duty,interlock,tc_fault_now,tc_fault_latched,opt_led,opt_r,opt_g,opt_b,opt_clear,dark_r,dark_g,dark_b,dark_clear,liquid_slope_c_per_min,liquid_equilibrated,opt_command_ms,run_elapsed_ms,cycle_elapsed_ms.ambient_c,tube_id,tube_lot,fill_ul,orientation,standard_id,notes are host/operator metadata because no corresponding sensors or identification hardware exist in the schematic. Add those columns during capture or join them to the device CSV by timestamp/run ID; firmware must not fabricate them.VBUS intentionally remains physically unconnected. The Pico module's onboard USB connector supplies its own VBUS; tying U1 VBUS to carrier 5V_LOGIC could cause source contention. The library marks VBUS as a power input, so the unsuppressed ERC reports one intentional missing-power error.Toolchain
Build, flash, and monitor
Actual pin map
Starter `src/main.cpp`
State and safety behavior
CSV ownership and validation-plan reconciliation
Known schematic-library ERC limitations