Community project

Solar Kiln Temperature Logger

Photo of Solar Kiln Temperature Logger
Generated with AI

Abhijeet Singh

Published November 29, 2026

This project builds a solar-powered temperature logger for monitoring kiln firing cycles using an ESP32 microcontroller and a precision thermocouple sensor. The system captures temperature data over time, stores readings locally, and provides real-time feedback through an LED and buzzer while running entirely off a rechargeable LiFePO4 battery charged by a small solar panel.

The guide includes a complete parts list, wiring diagram for the MAX31856 thermocouple breakout and DS3231 real-time clock, step-by-step assembly instructions, and firmware with Bluetooth connectivity for data retrieval. Builders will learn how to integrate solar charging, implement low-power operation, and log temperature profiles for ceramics, glass, or other heat-treatment applications.

Wiring diagram

Wiring diagram for Solar Kiln Temperature Logger
Loading diagram…

Gather all the parts

QtyComponent
1

Adafruit MAX31856 breakout 3263

Type K, one-shot conversion, 50Hz filtering. Second channel reserved on GPIO14.

1

Type K mineral insulated ungrounded probe

Order Inconel sheath rated for continuous 1100C; Class 1 tolerance only specified through 1000C. Type K extension and thermocouple-alloy M12 contacts.

1

Adafruit DS3231 Precision RTC Breakout

DS3231 precision real-time clock breakout with integrated TCXO and crystal for accurate timekeeping over I2C.

1

CR1220 non-rechargeable backup cell

Fits Adafruit DS3231 holder; no charging circuit.

1

LED

high brightness red

Standard 3mm/5mm through-hole LED. A current-limiting series resistor is added automatically.

1

Resistor

220 ohm

Through-hole resistor (current-limiting in series with an LED)

1

Push Button

Momentary push button switch

1

Piezo Buzzer

Small passive piezo buzzer (TDK PS1240) for beeps, tones and alerts. It has no built-in oscillator, so drive one lead with a 3-30 V square wave from a microcontroller pin using tone() or PWM and connect the other lead to ground. It is loudest around 4 kHz and works from about 2 to 10 kHz; driving both leads in antiphase roughly doubles the volume.

1

NPN Transistor (2N2222 / BC547)

General-purpose NPN bipolar junction transistor (BJT) in TO-92 package. Used as a low-side switch to drive loads (e.g. buzzers) whose current exceeds ESP32 GPIO source capability (~12 mA). A ~1 kΩ base resistor is placed between the ESP32 GPIO and the transistor base. The collector connects to the load negative terminal (buzzer –), and the emitter connects to GND. When the GPIO goes HIGH (3.3 V), the transistor saturates and switches the load on. Compatible with both 2N2222/2N2222A and BC547/BC547B variants. Add a flyback diode (e.g. 1N4148) across inductive load terminals.

1

Resistor

1 kohm

Through-hole resistor (current-limiting in series with an LED)

1

Resistor

100 kohm

Through-hole resistor (current-limiting in series with an LED)

1

6V 6W solar panel

Vmp near 6V, weatherproof panel; confirm Voc below charger limit.

1

Voltaic BQ24650 LiFePO4 MPPT charger module

Set 5.9V MPP and 1S LiFePO4 3.6V BEFORE connection. Fit cell-contact external thermistor using maker TP3/TP4 instructions. Not generic Li-ion charger.

1

Protected 1S LiFePO4 32650 6000mAh pack

Buy assembled protected pack with leads, short circuit and undervoltage protection. No soldering directly to cell.

1

Pololu S9V11F3S5 buck boost module

Default 3.3V; SEL left low. EN default pulled high. Module includes inductor and capacitors.

1

Resistor

100 kohm

Through-hole resistor (current-limiting in series with an LED)

1

Resistor

100 kohm

Through-hole resistor (current-limiting in series with an LED)

1

Electrolytic Capacitor

470uF 10V

Radial aluminium electrolytic capacitor bought by value and voltage rating, such as 10 µF, 100 µF or 1000 µF 10 V. It is polarised: the + lead goes to the higher voltage and the - lead, marked by the stripe on the sleeve, to the lower voltage or ground. It is mostly used for bulk filtering across a power rail, with a voltage rating comfortably above the rail.

1

ADXL345 Accelerometer

Digital ADXL345 triple-axis accelerometer breakout with I2C/SPI interface, STEMMA QT/Qwiic connectors, on-board 3.3 V regulator, and logic-level shifting for 3 V or 5 V microcontrollers.

Assemble it in 5 steps

1. Build and verify the power supply first

Disconnect everything. Set charger to 5.9V MPP and 1S LiFePO4 3.6V. Fit an external cell-contact thermistor following the charger maker instructions. Use a protected assembled pack. Connect battery, then panel, and verify regulator output is 3.3V before connecting electronics.

  • Never use 4.2V Li-ion charging settings. Shade the cell; charging must stop outside the cell manufacturer's temperature limits, normally 0–45°C.
  • Disconnect solar and battery before changing selector switches. Do not simultaneously feed the prototype 3V3 externally and connect USB power.

2. Wire the sensing electronics

SPI clock GPIO12, data to converter GPIO11, data from converter GPIO13, select GPIO10. RTC and accelerometer share GPIO8 data and GPIO9 clock. Motion interrupt goes to GPIO5. All logic is 3.3V. Fit the CR1220 backup cell.

3. Connect the kiln probe

Connect Type K positive to T+ and negative to T-. Use only Type K extension cable and thermocouple-alloy M12 contacts; ordinary copper contacts introduce errors at temperature gradients. Specify ungrounded mineral-insulated Inconel probe with continuous 1100°C rating.

  • Class 1 Type K accuracy is not specified above 1000°C. Have the vendor characterize 1100°C performance.
  • Only the probe enters the kiln. Stay clear of steam during quench.

4. Fit indicators and button

GPIO17 drives the red LED through 220 ohms. GPIO16 drives the transistor base through 1 kohm; 100 kohms keeps it off in sleep. This prototype uses a passive piezo with 4kHz drive, not a verified 85dB active sounder. GPIO4 button shorts to ground. The two 100 kohm battery-divider resistors feed GPIO1.

5. Weatherproof and mount

Mount in a shaded IP67 enclosure on a stake 1.5–2m from the kiln. Use sealed cable glands, strain relief, an acoustic waterproof membrane, and an external solar panel. Reserve a QR area for device ID and pairing data. Conformal coat the PCB but mask connectors, button and thermocouple terminals. Keep the antenna clear of metal and battery.

  • Do not field-deploy the bench security protocol. An ordinary open buzzer hole invalidates IP67. Verify enclosure temperature in direct sun.

Review all connections

1. Connections between "tc" and "ESP32"

FunctiontcESP32
spiSCKGPIO 12
spiSDIGPIO 11
spiSDOGPIO 13
digitalCSGPIO 10
powerVin3V3
groundGNDGND

2. Connections between "probe" and "ESP32"

FunctionprobeESP32
analogPLUS → Adafruit MAX31856 breakout 3263 T+EXT
analogMINUS → Adafruit MAX31856 breakout 3263 T-EXT

3. Connections between "rtc" and "ESP32"

FunctionrtcESP32
powerVIN3V3
groundGNDGND
i2cSDAGPIO 8
i2cSCLGPIO 9

4. Connections between "coin" and "ESP32"

FunctioncoinESP32
powerPLUS → Adafruit DS3231 Precision RTC Breakout BATEXT
groundMINUSGND

5. Connections between "rl" and "ESP32"

FunctionrlESP32
digitalP1GPIO 17
digitalP2 → LED ANODEEXT

6. Connections between "led" and "ESP32"

FunctionledESP32
groundGNDGND

7. Connections between "button" and "ESP32"

FunctionbuttonESP32
digitalSIGNALGPIO 4
groundGNDGND

8. Connections between "buzz" and "ESP32"

FunctionbuzzESP32
powerSIG3V3
groundGND → NPN Transistor (2N2222 / BC547) COLLECTOREXT

9. Connections between "q" and "ESP32"

FunctionqESP32
groundEMITTERGND

10. Connections between "rb" and "ESP32"

FunctionrbESP32
digitalP1GPIO 16
digitalP2 → NPN Transistor (2N2222 / BC547) BASEEXT

11. Connections between "rpd" and "ESP32"

FunctionrpdESP32
digitalP1 → NPN Transistor (2N2222 / BC547) BASEEXT
groundP2GND

12. Connections between "panel" and "ESP32"

FunctionpanelESP32
powerPLUS → Voltaic BQ24650 LiFePO4 MPPT charger module IN+EXT
groundMINUS → Voltaic BQ24650 LiFePO4 MPPT charger module IN-EXT

13. Connections between "charger" and "ESP32"

FunctionchargerESP32
groundIN-GND
groundBAT-GND

14. Connections between "battery" and "ESP32"

FunctionbatteryESP32
powerPLUS → Voltaic BQ24650 LiFePO4 MPPT charger module BAT+EXT
groundMINUS → Voltaic BQ24650 LiFePO4 MPPT charger module BAT-EXT

15. Connections between "reg" and "ESP32"

FunctionregESP32
powerVIN → Protected 1S LiFePO4 32650 6000mAh pack PLUSEXT
groundGNDGND
powerVOUT3V3

16. Connections between "rt" and "ESP32"

FunctionrtESP32
digitalP1 → Protected 1S LiFePO4 32650 6000mAh pack PLUSEXT
digitalP2 → Resistor P1EXT

17. Connections between "rd" and "ESP32"

FunctionrdESP32
digitalP1GPIO 1
groundP2GND

18. Connections between "cb" and "ESP32"

FunctioncbESP32
power+3V3
ground-GND

19. Connections between "acc" and "ESP32"

FunctionaccESP32
powerVCC3V3
groundGNDGND
i2cSDAGPIO 8
i2cSCLGPIO 9
digitalINT1GPIO 5
powerCS3V3
groundSDOGND

Deploy the firmware

#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_MAX31856.h>
#include <Adafruit_ADXL345_U.h>
#include <RTClib.h>
#include <LittleFS.h>
#include <Preferences.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <Update.h>
#include <esp_sleep.h>
#include <esp_ds.h>
#include <mbedtls/sha256.h>

// BLE only at idle: button opens a 120-second window. Never format on error.
constexpr int TC_CS=10, BUTTON=4, MOTION=5, LED_PIN=17, BUZZER_PIN=16, BAT_ADC=1;
const char *VERSION="0.1.0-bench";
const char *SERVICE="854b0000-609b-4c19-8d78-345e25da6200";
Adafruit_MAX31856 tc(TC_CS,&SPI);
Adafruit_ADXL345_Unified acc(1);
RTC_DS3231 rtc;
Preferences prefs;
BLECharacteristic *reply;
bool rtcOK=false, accOK=false, storageOK=false, ble=false, ota=false;
String deviceID, kiln;
uint32_t nextSample=0, bleEnd=0;
volatile bool commandPending=false;
String command;
portMUX_TYPE mux=portMUX_INITIALIZER_UNLOCKED;
enum State:uint8_t {IDLE,RAMP_UP,PYROLYSIS,QUENCH,RUN_CLOSED};
struct Context {
 uint32_t magic,id,start,last,below,above350,above450,faults,heartbeat;
 float peak,previous,battery;
 uint8_t state;
 char kiln[33];
};
Context ctx{};
struct __attribute__((packed)) Sample {uint16_t dt,temperature;};
String path(uint32_t id,const char *suffix){return "/r"+String(id)+suffix;}
String hex(const uint8_t *b,size_t n){String s; const char *h="0123456789abcdef";for(size_t i=0;i<n;i++){s+=h[b[i]>>4];s+=h[b[i]&15];}return s;}
uint32_t now(){return rtcOK?rtc.now().unixtime():0;}
void persist(){prefs.putBytes("context",&ctx,sizeof(ctx));}
void alert(int pulses,int ms=80){for(int i=0;i<pulses;i++){digitalWrite(LED_PIN,HIGH);tone(BUZZER_PIN,4000);delay(ms);noTone(BUZZER_PIN);digitalWrite(LED_PIN,LOW);delay(ms);}}
void fail(const char *message){Serial.println(message);alert(4);delay(1000);}
float batteryVoltage(){uint32_t total=0;for(int i=0;i<16;i++){total+=analogReadMilliVolts(BAT_ADC);delay(1);}return total/16000.0f*2;}
bool saveText(String name,String text){File f=LittleFS.open(name+".tmp","w");if(!f)return false;bool ok=f.print(text)==text.length();f.flush();f.close();if(!ok)return false;return LittleFS.rename(name+".tmp",name);}
bool fileHash(String name,uint8_t out[32]){File f=LittleFS.open(name,"r");if(!f)return false;mbedtls_sha256_context h;mbedtls_sha256_init(&h);mbedtls_sha256_starts(&h,0);uint8_t b[256];while(f.available()){size_t n=f.read(b,sizeof(b));mbedtls_sha256_update(&h,b,n);}f.close();mbedtls_sha256_finish(&h,out);mbedtls_sha256_free(&h);return true;}
// Factory writes encrypted esp_ds_data_t into NVS namespace factory/key.
// eFuse HMAC_KEY0 must have DS downstream purpose. Firmware NEVER burns eFuses.
// RSA-2048 PKCS#1 v1.5 SHA256 encoding, reversed for DS little-endian operands.
bool signHash(const uint8_t hash[32],uint8_t signature[256]){
 Preferences factory;factory.begin("factory",true);
 esp_ds_data_t data;bool present=factory.getBytesLength("key")==sizeof(data);
 if(present)factory.getBytes("key",&data,sizeof(data));factory.end();
 if(!present || data.rsa_length!=63)return false;
 const uint8_t prefix[]={0x30,0x31,0x30,0x0d,0x06,0x09,0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x01,0x05,0x00,0x04,0x20};
 uint8_t encoded[256],little[256],raw[256];memset(encoded,0xff,256);encoded[0]=0;encoded[1]=1;encoded[204]=0;memcpy(encoded+205,prefix,19);memcpy(encoded+224,hash,32);
 for(int i=0;i<256;i++)little[i]=encoded[255-i];
 if(esp_ds_sign(little,&data,HMAC_KEY0,raw)!=ESP_OK)return false;
 for(int i=0;i<256;i++)signature[i]=raw[255-i];return true;
}
bool closeRun(){
 String raw=path(ctx.id,".bin"), meta=path(ctx.id,".json");
 if(LittleFS.exists(meta)){ctx.state=IDLE;persist();return true;}
 uint8_t rawHash[32];if(!fileHash(raw,rawHash))return false;
 String previous=prefs.getString("chain",String("0000000000000000000000000000000000000000000000000000000000000000"));
 String summary="{\"schema\":1,\"device\":\""+deviceID+"\",\"kiln\":\""+String(ctx.kiln)+"\",\"run\":"+String(ctx.id)+",\"start\":"+String(ctx.start)+",\"end\":"+String(ctx.last)+",\"peak\":"+String(ctx.peak,2)+",\"seconds350\":"+String(ctx.above350)+",\"seconds450\":"+String(ctx.above450)+",\"faults\":"+String(ctx.faults)+",\"battery\":"+String(ctx.battery,3)+",\"firmware\":\""+VERSION+"\",\"raw_sha256\":\""+hex(rawHash,32)+"\",\"previous\":\""+previous+"\"}";
 uint8_t digest[32],sig[256];mbedtls_sha256((const uint8_t*)summary.c_str(),summary.length(),digest,0);
 bool signedOK=signHash(digest,sig);
 String record="{\"summary\":"+summary+",\"record_hash\":\""+hex(digest,32)+"\",\"signature\":\""+(signedOK?hex(sig,256):String(""))+"\",\"security\":\""+(signedOK?"RSA2048-SHA256":"UNPROVISIONED")+"\"}";
 if(!saveText(meta,record))return false;
 prefs.putString("chain",hex(digest,32));ctx.state=IDLE;persist();alert(3,180);return true;
}
void sample(){
 if(ctx.state==RUN_CLOSED){if(!closeRun())fail("Close failure; raw data retained");return;}
 float t=tc.readThermocoupleTemperature();uint8_t fault=tc.readFault();
 if(!isfinite(t)||t<0||t>1100)fault|=MAX31856_FAULT_TCRANGE;
 uint32_t stamp=now();ctx.battery=batteryVoltage();
 if(fault)alert(4);else if(ctx.battery<3.05f)alert(2,200);
 if(!rtcOK || rtc.lostPower() || !storageOK){fail("Set valid RTC time / initialize storage on bench");return;}
 if(ctx.state==IDLE && !fault && t>150){
  // Reserve enough for a four-hour run plus signed metadata. Never reclaim raw.
  if(LittleFS.totalBytes()-LittleFS.usedBytes()<12000){fail("Storage full; sync required");return;}
  ctx={};ctx.magic=0x4b494c4e;ctx.id=prefs.getUInt("next",1);prefs.putUInt("next",ctx.id+1);
  ctx.start=stamp;ctx.last=stamp;ctx.heartbeat=stamp;ctx.state=RAMP_UP;ctx.previous=t;ctx.peak=t;ctx.battery=batteryVoltage();kiln.toCharArray(ctx.kiln,sizeof(ctx.kiln));
  persist();alert(1,200);
 }
 if(ctx.state==IDLE)return;
 uint32_t elapsed=stamp>=ctx.last?stamp-ctx.last:0;
 // Temperature bits: 0..4400 = quarter-degrees C; high bit = converter fault.
 Sample s={(uint16_t)min(elapsed,(uint32_t)65535),fault?(uint16_t)(0x8000|fault):(uint16_t)lroundf(t*4)};
 File f=LittleFS.open(path(ctx.id,".bin"),"a");if(!f || f.write((uint8_t*)&s,sizeof(s))!=sizeof(s)){if(f)f.close();fail("Flash write failed; no deletion performed");return;}f.flush();f.close();
 if(fault){ctx.faults++;ctx.below=0;ctx.previous=-1000;}else{
  ctx.peak=max(ctx.peak,t);
  // Count only intervals <=15s, and only if BOTH endpoints exceed threshold.
  if(elapsed<=15){if(ctx.previous>350&&t>350)ctx.above350+=elapsed;if(ctx.previous>450&&t>450)ctx.above450+=elapsed;}
  if(ctx.state==RAMP_UP&&t>=350)ctx.state=PYROLYSIS;
  if(elapsed>0&&elapsed<=15&&ctx.previous-t>=100)ctx.state=QUENCH;
  if(t<100){if(!ctx.below)ctx.below=stamp;if(stamp-ctx.below>=600)ctx.state=RUN_CLOSED;}else ctx.below=0;
  ctx.previous=t;
 }
 ctx.last=stamp;
 if(stamp-ctx.heartbeat>=300){alert(1);ctx.heartbeat=stamp;}
 persist();if(ctx.state==RUN_CLOSED)closeRun();
}
void respond(String text){reply->setValue(text.c_str());reply->notify();}
class Commands:public BLECharacteristicCallbacks {void onWrite(BLECharacteristic *c) override {
 String s=c->getValue();if(s.length()>128)return;
 // callbacks defer filesystem and cryptographic work to the main task
 if(!commandPending){command=String(s.c_str());commandPending=true;}
}};
class OTA:public BLECharacteristicCallbacks {void onWrite(BLECharacteristic *c) override{
 if(!ota)return;String s=c->getValue();if(Update.write((uint8_t*)s.c_str(),s.length())!=s.length()){Update.abort();ota=false;}
}};
String health(){return "id="+deviceID+";kiln="+kiln+";battery="+String(batteryVoltage(),3)+";free="+String(LittleFS.totalBytes()-LittleFS.usedBytes())+";state="+String(ctx.state)+";rtc="+String(rtcOK&&!rtc.lostPower())+";firmware="+VERSION+";security=factory-key-required";}
void execute(String s){
 if(s=="HEALTH"){respond(health());return;}
 if(s=="LIST" || s.startsWith("LIST ")){unsigned offset=s.length()>5?s.substring(5).toInt():0;String list;File root=LittleFS.open("/");File f=root.openNextFile();while(f){String n=f.name();if(n.endsWith(".json")){list+=n+":"+String(f.size())+";";}f=root.openNextFile();}respond(list.substring(offset,offset+480));return;}
 if(s.startsWith("TIME ")){uint32_t v=s.substring(5).toInt();if(v<1700000000){respond("ERR time");return;}rtc.adjust(DateTime(v));respond("OK time");return;}
 if(s.startsWith("BIND ")){String k=s.substring(5);bool ok=k.length()>0&&k.length()<=32;for(unsigned i=0;i<k.length();i++)if(!isalnum(k[i])&&k[i]!='-'&&k[i]!='_')ok=false;if(!ok){respond("ERR kiln ID");return;}kiln=k;prefs.putString("kiln",kiln);respond("OK bind");return;}
 // GET id bin|json offset : deterministic 128-byte chunks, read response repeatedly.
 if(s.startsWith("GET ")){unsigned id=0,offset=0;char ext[8]={};if(sscanf(s.c_str(),"GET %u %7s %u",&id,ext,&offset)!=3 || (strcmp(ext,"bin")&&strcmp(ext,"json"))){respond("ERR request");return;}File f=LittleFS.open(path(id,(String(".")+ext).c_str()),"r");if(!f){respond("ERR missing");return;}f.seek(offset);uint8_t b[128];size_t n=f.read(b,128);f.close();reply->setValue(b,n);reply->notify();return;}
 // ACK id rawHash uploadUnix: app must first verify full raw SHA256 and signature.
 if(s.startsWith("ACK ")){unsigned id=0,uploaded=0;char hash[65]={};if(sscanf(s.c_str(),"ACK %u %64s %u",&id,hash,&uploaded)!=3){respond("ERR ack");return;}uint8_t actual[32];if(!LittleFS.exists(path(id,".json"))||!fileHash(path(id,".bin"),actual)||hex(actual,32)!=hash||uploaded<1700000000){respond("ERR hash/time");return;}if(!saveText(path(id,".ack"),String(uploaded))){respond("ERR write");return;} // deliberately retain all raw, even acknowledged
 alert(2);respond("OK receipt stored; raw retained");return;}
 if(s.startsWith("OTA_BEGIN ")){uint32_t n=s.substring(10).toInt();ota=n>0&&Update.begin(n);respond(ota?"OK OTA":"ERR OTA");return;}
 if(s=="OTA_END"){if(ota&&Update.end(true)){respond("OK reboot");delay(500);ESP.restart();}ota=false;respond("ERR OTA");return;}
 respond("ERR command");
}
void startBLE(){
 BLEDevice::init(("Kiln-"+deviceID).c_str());BLEDevice::setMTU(185);
 // Physical presence is required; this bench protocol is NOT authenticated.
 BLEServer *server=BLEDevice::createServer();BLEService *svc=server->createService(SERVICE);
 BLECharacteristic *ctl=svc->createCharacteristic("854b0001-609b-4c19-8d78-345e25da6200",BLECharacteristic::PROPERTY_WRITE);ctl->setCallbacks(new Commands());
 reply=svc->createCharacteristic("854b0002-609b-4c19-8d78-345e25da6200",BLECharacteristic::PROPERTY_READ|BLECharacteristic::PROPERTY_NOTIFY);reply->addDescriptor(new BLE2902());reply->setValue(health().c_str());
 BLECharacteristic *fw=svc->createCharacteristic("854b0003-609b-4c19-8d78-345e25da6200",BLECharacteristic::PROPERTY_WRITE);fw->setCallbacks(new OTA());
 svc->start();BLEAdvertising *ad=BLEDevice::getAdvertising();ad->addServiceUUID(SERVICE);ad->start();ble=true;bleEnd=millis()+120000;
}
void setup(){
 Serial.begin(115200);pinMode(LED_PIN,OUTPUT);pinMode(BUZZER_PIN,OUTPUT);pinMode(BUTTON,INPUT_PULLUP);pinMode(MOTION,INPUT);analogReadResolution(12);analogSetPinAttenuation(BAT_ADC,ADC_11db);
 Wire.begin(8,9);SPI.begin(12,13,11,10);
 rtcOK=rtc.begin();if(rtcOK){rtc.disable32K();rtc.writeSqwPinMode(DS3231_OFF);}
 if(!tc.begin()){fail("MAX31856 missing");while(true)delay(1000);}tc.setThermocoupleType(MAX31856_TCTYPE_K);tc.setNoiseFilter(MAX31856_NOISE_FILTER_50HZ);tc.setConversionMode(MAX31856_ONESHOT);
 accOK=acc.begin();if(accOK){acc.setRange(ADXL345_RANGE_16_G);acc.setDataRate(ADXL345_DATARATE_25_HZ); // activity + free fall interrupt, active high
 acc.writeRegister(ADXL345_REG_THRESH_ACT,16);acc.writeRegister(ADXL345_REG_ACT_INACT_CTL,0xf0);acc.writeRegister(ADXL345_REG_THRESH_FF,7);acc.writeRegister(ADXL345_REG_TIME_FF,20);acc.writeRegister(ADXL345_REG_INT_MAP,0);acc.writeRegister(ADXL345_REG_INT_ENABLE,0x14);
 uint8_t events=acc.readRegister(ADXL345_REG_INT_SOURCE);if(events&0x14)Serial.printf("Motion flags %02x\n",events);}
 uint64_t mac=ESP.getEfuseMac();char id[13];snprintf(id,sizeof(id),"%012llX",(unsigned long long)mac);deviceID=id;
 prefs.begin("logger",false);kiln=prefs.getString("kiln","UNBOUND");prefs.getBytes("context",&ctx,sizeof(ctx));if(ctx.magic!=0x4b494c4e){ctx={};ctx.magic=0x4b494c4e;}
 storageOK=LittleFS.begin(false); // never erase existing runs on mount failure
 if(!storageOK){Serial.println("Storage uninitialized. On NEW bench unit only send FORMAT via USB.");uint32_t until=millis()+10000;while(millis()<until){if(Serial.available()&&Serial.readStringUntil('\n')=="FORMAT"){LittleFS.format();storageOK=LittleFS.begin(false);break;}}}
 if(esp_sleep_get_wakeup_cause()==ESP_SLEEP_WAKEUP_UNDEFINED){alert(1,250);alert(1+(mac&3),60);}
 sample();nextSample=millis()+(ctx.state==IDLE?60000:10000);
 if(ctx.state==IDLE&&(digitalRead(BUTTON)==LOW||esp_sleep_get_wakeup_cause()==ESP_SLEEP_WAKEUP_EXT1))startBLE();
}
void loop(){
 if(ble){if(commandPending){String s=command;commandPending=false;execute(s);}if((int32_t)(millis()-bleEnd)<0){delay(20);return;}if(ota){Update.abort();ota=false;}BLEDevice::deinit(true);ble=false;}
 digitalWrite(LED_PIN,LOW);noTone(BUZZER_PIN);digitalWrite(BUZZER_PIN,LOW);
 // No motion sleep wake: INT1 is latched and read at every timed sample, to prevent wake storms.
 esp_sleep_enable_ext1_wakeup(1ULL<<BUTTON,ESP_EXT1_WAKEUP_ALL_LOW);
 uint32_t period=ctx.state==IDLE?60:10;
 uint32_t remaining=period*1000 > millis()?period*1000-millis():100;
 esp_sleep_enable_timer_wakeup((uint64_t)remaining*1000ULL);
 esp_deep_sleep_start();
}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik