#include <Arduino.h>
#include <Wire.h>
#include <hardware/gpio.h>
#include <hardware/watchdog.h>
#include <stdio.h>
#include <string.h>
// WeraCare Wokwi simulation. Use LEDs to represent the 12 V loads.
// The original sequence runs the heater for 60 s before the blower.
// This simulation has no airflow switch. Do not use it to power a real heater.
const uint8_t PROBE = 2;
const uint8_t OLED_SDA = 4, OLED_SCL = 5;
const uint8_t DHT = 6;
const uint8_t HELMET = 10, TANK = 11, LIQUID = 12;
const uint8_t PUMP = 14, HEATER = 15, BLOWER = 16;
const uint8_t RED = 17, YELLOW = 18, GREEN = 19;
const uint32_t SECOND = 1000UL;
const uint32_t MINUTE = 60UL * SECOND;
const float PROBE_HEATER_OFF_C = 60.0f;
const float PROBE_RESTART_C = 55.0f;
const float AIR_HEATER_OFF_C = 50.0f;
const float AIR_RESTART_C = 45.0f;
enum Stage {
RELEASE_HELMET, IDLE, WELCOME, SPRAY, REST, PREHEAT,
DRY, COOL, READY, FAULT_COOL, FAULT
};
const char *const stageName[] = {
"RELEASE HELMET", "PLACE HELMET", "WELCOME TO WERACARE",
"SPRAYING", "RESTING", "PREHEATING", "DRYING",
"COOLING", "HELMET READY", "FAULT COOLING", "FAULT"
};
Stage stage = RELEASE_HELMET;
const char *faultReason = "";
uint32_t stageStart, edgeStart, greenStart, lastDraw;
bool edgePending = false, greenOn = false, refreshScreen = true;
bool oledOK = false, haveReading = false, converting = false;
uint32_t conversionStart, lastReading, bootTime;
float probeC, airC, humidity;
bool probeHeatPaused = false;
bool airHeatPaused = false;
// Fixed RH reference for the current one-minute stability check.
// -1 means the next fresh drying sample will set the reference.
int lastDryRhTenths = -1;
uint32_t steadyRhSince = 0;
// Explicit declarations for the Arduino sketch preprocessor.
void enterStage(Stage next, uint32_t now);
void applyHeater(Stage target, uint32_t now);
bool helmetDown() { return digitalRead(HELMET) == LOW; }
bool tankFitted() { return digitalRead(TANK) == LOW; }
bool needsRefill() { return digitalRead(LIQUID) == LOW; }
// ---------- OLED on GP4 / GP5 ----------
const uint16_t letters[] = {
025755, 065656, 034443, 065556, 074647, 074644, 034553,
055755, 072227, 011152, 055655, 044447, 057755, 057775,
025552, 065644, 025573, 065655, 034216, 072222, 055557,
055552, 055775, 055255, 055222, 071247
};
const uint16_t digits[] = {
075557, 026227, 061247, 061216, 055711,
074616, 034652, 071222, 025252, 025316
};
uint16_t glyph(char c) {
if (c >= 'A' && c <= 'Z') return letters[c - 'A'];
if (c >= '0' && c <= '9') return digits[c - '0'];
if (c == '-') return 000700;
if (c == '.') return 000002;
if (c == '%') return 051245;
return 0;
}
bool oledCommand(const uint8_t *bytes, size_t n) {
Wire.beginTransmission(0x3C);
Wire.write((uint8_t)0);
Wire.write(bytes, n);
return Wire.endTransmission() == 0;
}
bool initOLED() {
const uint8_t init[] = {
0xAE, 0xD5, 0x80, 0xA8, 0x3F, 0xD3, 0, 0x40,
0x8D, 0x14, 0x20, 0x02, 0xA1, 0xC8, 0xDA, 0x12,
0x81, 0xAF, 0xD9, 0xF1, 0xDB, 0x40, 0xA4, 0xA6, 0xAF
};
return oledCommand(init, sizeof(init));
}
void oledLine(uint8_t page, const char *text) {
uint8_t address[] = {(uint8_t)(0xB0 | page), 0, 0x10};
oledCommand(address, sizeof(address));
uint8_t pixels[128] = {};
for (int i = 0; text[i] && i < 25; i++) {
uint16_t shape = glyph(text[i]);
for (int col = 0; col < 3; col++) {
for (int row = 0; row < 5; row++) {
if (shape & (1U << (14 - row * 3 - col))) {
pixels[i * 5 + col] |= 1U << (row + 1);
}
}
}
}
for (int x = 0; x < 128; x += 16) {
Wire.beginTransmission(0x3C);
Wire.write((uint8_t)0x40);
Wire.write(pixels + x, 16);
Wire.endTransmission();
}
}
// ---------- DS18B20 probe on GP2 ----------
void pullLow(uint8_t pin) {
gpio_put(pin, 0);
gpio_set_dir(pin, GPIO_OUT);
}
void releaseLine(uint8_t pin) {
gpio_set_dir(pin, GPIO_IN);
}
bool probeReset() {
gpio_init(PROBE);
gpio_pull_up(PROBE);
gpio_put(PROBE, 0);
gpio_set_dir(PROBE, GPIO_IN);
delayMicroseconds(10);
if (!gpio_get(PROBE)) {
Serial1.println("A: GP2 is already LOW before reset");
return false;
}
gpio_set_dir(PROBE, GPIO_OUT);
uint32_t start = micros();
while ((uint32_t)(micros() - start) < 500) {}
bool resetWasLow = !gpio_get(PROBE);
noInterrupts();
gpio_set_dir(PROBE, GPIO_IN);
start = micros();
while (!gpio_get(PROBE) && (uint32_t)(micros() - start) < 12) {}
bool roseAfterReset = gpio_get(PROBE);
while (gpio_get(PROBE) && (uint32_t)(micros() - start) < 120) {}
bool sawReply = !gpio_get(PROBE);
while (!gpio_get(PROBE) && (uint32_t)(micros() - start) < 400) {}
bool released = gpio_get(PROBE);
interrupts();
delayMicroseconds(480);
if (!resetWasLow) {
Serial1.println("B: Pico could not pull GP2 LOW");
} else if (!roseAfterReset) {
Serial1.println("C: GP2 did not rise after reset");
} else if (!sawReply) {
Serial1.println("D: Reset sent on GP2; no probe reply detected");
} else if (!released) {
Serial1.println("E: Probe replied but GP2 stayed LOW");
} else {
return true;
}
return false;
}
void probeWrite(uint8_t value) {
for (int bit = 0; bit < 8; bit++) {
const bool sendOne = (value & 1U) != 0;
const uint32_t lowTime = sendOne ? 6U : 65U;
noInterrupts();
gpio_put(PROBE, 0);
gpio_set_dir(PROBE, GPIO_OUT);
const uint32_t start = micros();
while ((uint32_t)(micros() - start) < lowTime) {}
gpio_set_dir(PROBE, GPIO_IN);
while ((uint32_t)(micros() - start) < 75U) {}
interrupts();
value >>= 1;
}
}
uint8_t probeRead() {
uint8_t value = 0;
for (int bit = 0; bit < 8; bit++) {
noInterrupts();
gpio_set_dir(PROBE, GPIO_OUT);
uint32_t start = micros();
while ((uint32_t)(micros() - start) < 3) {}
gpio_set_dir(PROBE, GPIO_IN);
while ((uint32_t)(micros() - start) < 12) {}
if (gpio_get(PROBE)) value |= (1U << bit);
interrupts();
while ((uint32_t)(micros() - start) < 70) {}
}
return value;
}
uint8_t probeCRC(const uint8_t *data, int size) {
uint8_t crc = 0;
for (int i = 0; i < size; i++) {
crc ^= data[i];
for (int bit = 0; bit < 8; bit++) {
crc = (crc >> 1) ^ ((crc & 1) ? 0x8C : 0);
}
}
return crc;
}
bool startProbe() {
if (!probeReset()) return false;
probeWrite(0xCC);
probeWrite(0x44);
return true;
}
bool readProbe(float &temperature) {
if (!probeReset()) {
Serial1.println("Probe reset failed before reading temperature");
return false;
}
probeWrite(0xCC);
probeWrite(0xBE);
uint8_t data[9];
bool allZero = true;
bool allFF = true;
for (int i = 0; i < 9; i++) {
data[i] = probeRead();
if (data[i] != 0x00) allZero = false;
if (data[i] != 0xFF) allFF = false;
}
Serial1.print("DS18B20 bytes:");
for (int i = 0; i < 9; i++) {
Serial1.print(' ');
if (data[i] < 16) Serial1.print('0');
Serial1.print(data[i], HEX);
}
Serial1.println();
if (allZero || allFF) {
Serial1.println(allFF ? "All bits read HIGH" : "All bits read LOW");
return false;
}
uint8_t expectedCRC = probeCRC(data, 8);
if (expectedCRC != data[8]) {
Serial1.print("Checksum mismatch. Calculated 0x");
Serial1.print(expectedCRC, HEX);
Serial1.print(", received 0x");
Serial1.println(data[8], HEX);
return false;
}
int16_t raw = (int16_t)((uint16_t(data[1]) << 8) | data[0]);
temperature = raw / 16.0f;
if (temperature < -55.0f || temperature > 125.0f) {
Serial1.println("Temperature outside DS18B20 range");
return false;
}
Serial1.print("Probe OK: ");
Serial1.print(temperature, 2);
Serial1.println(" C");
return true;
}
// ---------- DHT22 air temperature and humidity on GP6 ----------
bool waitWhileLevel(uint8_t pin, bool level, uint32_t timeoutUs) {
uint32_t start = micros();
while (gpio_get(pin) == level) {
if ((uint32_t)(micros() - start) >= timeoutUs) return false;
}
return true;
}
bool readDHT(float &temperature, float &rh) {
uint8_t bytes[5] = {};
pullLow(DHT);
delayMicroseconds(1200);
noInterrupts();
releaseLine(DHT);
bool ok = waitWhileLevel(DHT, HIGH, 150)
&& waitWhileLevel(DHT, LOW, 150)
&& waitWhileLevel(DHT, HIGH, 150);
for (int bit = 0; ok && bit < 40; bit++) {
ok = waitWhileLevel(DHT, LOW, 120);
if (!ok) break;
uint32_t rise = micros();
ok = waitWhileLevel(DHT, HIGH, 120);
uint8_t &b = bytes[bit / 8];
b = (b << 1) | ((uint32_t)(micros() - rise) > 48);
}
interrupts();
if (!ok) return false;
uint8_t sum = bytes[0] + bytes[1] + bytes[2] + bytes[3];
if (sum != bytes[4]) return false;
rh = ((bytes[0] << 8) | bytes[1]) / 10.0f;
temperature = (((bytes[2] & 0x7F) << 8) | bytes[3]) / 10.0f;
if (bytes[2] & 0x80) temperature = -temperature;
return rh >= 0 && rh <= 100 && temperature >= -40 && temperature <= 80;
}
// ---------- Heater temperature control ----------
void updateHeatLimits() {
if (probeC >= PROBE_HEATER_OFF_C) {
probeHeatPaused = true;
} else if (probeC <= PROBE_RESTART_C) {
probeHeatPaused = false;
}
if (airC >= AIR_HEATER_OFF_C) {
airHeatPaused = true;
} else if (airC <= AIR_RESTART_C) {
airHeatPaused = false;
}
}
void applyHeater(Stage target, uint32_t now) {
bool heatingStage = target == PREHEAT || target == DRY;
bool freshReading = haveReading && now - lastReading <= 3000;
bool heaterOn = heatingStage && freshReading && helmetDown()
&& !probeHeatPaused && !airHeatPaused;
digitalWrite(HEATER, heaterOn ? HIGH : LOW);
}
// ---------- Cycle control ----------
void enterStage(Stage next, uint32_t now) {
applyHeater(next, now);
digitalWrite(PUMP, next == SPRAY);
digitalWrite(BLOWER, next == DRY || next == COOL || next == FAULT_COOL);
digitalWrite(YELLOW, next == SPRAY || next == REST || next == PREHEAT ||
next == DRY || next == COOL);
if (next == DRY) {
lastDryRhTenths = -1;
}
if (next == READY) {
digitalWrite(GREEN, HIGH);
greenOn = true;
greenStart = now;
} else if (next == FAULT || next == FAULT_COOL) {
digitalWrite(GREEN, LOW);
greenOn = false;
}
stage = next;
stageStart = now;
edgePending = false;
refreshScreen = true;
Serial1.println(stageName[next]);
}
void fault(const char *why, uint32_t now) {
if (stage == FAULT || stage == FAULT_COOL) return;
faultReason = why;
bool wasHot = stage == PREHEAT || stage == DRY || stage == COOL;
enterStage(wasHot && helmetDown() ? FAULT_COOL : FAULT, now);
Serial1.println(why);
}
bool updateSensors(uint32_t now) {
if (stage == FAULT || stage == FAULT_COOL) return false;
if (!converting) {
if (now - bootTime < 1500) return false;
if (haveReading && now - lastReading < 1400) return false;
if (!startProbe()) {
haveReading = false;
fault("CHECK GP2 PROBE", now);
return false;
}
converting = true;
conversionStart = millis();
return false;
}
if (now - conversionStart < 800) return false;
converting = false;
if (!readProbe(probeC)) {
haveReading = false;
fault("PROBE DATA ERROR", millis());
return false;
}
if (!readDHT(airC, humidity)) {
haveReading = false;
fault("CHECK GP6 DHT22", millis());
return false;
}
lastReading = millis();
haveReading = true;
updateHeatLimits();
return true;
}
bool dryForOneMinute(uint32_t now) {
// Example: 90.0% RH is stored as 900. Its inclusive band is 870 to 930.
const int currentRhTenths = (int)(humidity * 10.0f + 0.5f);
const int toleranceTenths = 30;
if (lastDryRhTenths < 0 ||
currentRhTenths < lastDryRhTenths - toleranceTenths ||
currentRhTenths > lastDryRhTenths + toleranceTenths) {
lastDryRhTenths = currentRhTenths;
steadyRhSince = now;
return false;
}
return now - steadyRhSince >= MINUTE;
}
void updateCycle(uint32_t now, bool fresh) {
uint32_t age = now - stageStart;
if (greenOn && now - greenStart >= 10 * SECOND) {
greenOn = false;
digitalWrite(GREEN, LOW);
}
if (stage == FAULT) return;
if (stage == FAULT_COOL) {
if (!helmetDown() || age >= MINUTE) enterStage(FAULT, now);
return;
}
if (!haveReading) return;
if (stage == RELEASE_HELMET || stage == IDLE || stage == READY) {
bool waitingForPress = stage == IDLE;
bool correctPosition = helmetDown() == waitingForPress;
if (!correctPosition || (waitingForPress && needsRefill())) {
edgePending = false;
} else if (!edgePending) {
edgePending = true;
edgeStart = now;
} else if (now - edgeStart >= 100) {
enterStage(waitingForPress ? WELCOME : IDLE, now);
}
return;
}
if (!helmetDown()) {
fault("HELMET REMOVED", now);
return;
}
if (stage == WELCOME && needsRefill()) {
enterStage(RELEASE_HELMET, now);
return;
}
if (stage == SPRAY && needsRefill()) {
fault("SPRAY INCOMPLETE", now);
return;
}
if ((stage == WELCOME || stage == SPRAY) && !tankFitted()) {
fault("CHECK TANK", now);
return;
}
if (now - lastReading > 3000) {
fault("STALE SENSOR DATA", now);
return;
}
switch (stage) {
case WELCOME:
if (age >= 5 * SECOND) enterStage(SPRAY, now);
break;
case SPRAY:
if (age >= 12 * SECOND) enterStage(REST, now);
break;
case REST:
if (age >= MINUTE) enterStage(PREHEAT, now);
break;
case PREHEAT:
if (age >= MINUTE) enterStage(DRY, now);
break;
case DRY:
if (age >= 20 * MINUTE) {
fault("DRYING TIMEOUT", now);
} else if (fresh && dryForOneMinute(now)) {
enterStage(COOL, now);
}
break;
case COOL:
if (age >= 30 * SECOND) enterStage(READY, now);
break;
default:
break;
}
}
// ---------- OLED status ----------
void formatSensorLine(char *line, size_t size, const char *label,
float value, const char *unit) {
const int tenths = (int)(value * 10.0f + (value < 0 ? -0.5f : 0.5f));
const int magnitude = tenths < 0 ? -tenths : tenths;
snprintf(line, size, "%s %s%d.%d %s",
label, tenths < 0 ? "-" : "",
magnitude / 10, magnitude % 10, unit);
}
void drawScreen(uint32_t now) {
if (!oledOK || (!refreshScreen && now - lastDraw < 500)) return;
refreshScreen = false;
lastDraw = now;
char line[30];
bool heatingStage = stage == PREHEAT || stage == DRY;
oledLine(0, "WERACARE");
if (stage == READY) {
oledLine(1, "CYCLE COMPLETE");
oledLine(2, "");
oledLine(3, "YOU CAN NOW COLLECT");
oledLine(4, "YOUR HELMET");
oledLine(5, "");
oledLine(6, needsRefill() ? "REFILL TANK" : "");
oledLine(7, "");
return;
}
oledLine(1, stageName[stage]);
line[0] = 0;
if (stage == FAULT || stage == FAULT_COOL) {
snprintf(line, sizeof(line), "%s", faultReason);
} else if (heatingStage && probeHeatPaused) {
snprintf(line, sizeof(line), "TEMP EXCEEDED 60 C");
} else if (heatingStage && airHeatPaused) {
snprintf(line, sizeof(line), "AIR TEMP EXCEEDED 50 C");
} else if (stage == WELCOME) {
snprintf(line, sizeof(line), "START IN %lu S",
(unsigned long)(5 - (now - stageStart) / SECOND));
} else if (stage == SPRAY) {
snprintf(line, sizeof(line), "PUMP ON");
}
oledLine(2, line);
if (haveReading && stage != FAULT && stage != FAULT_COOL) {
formatSensorLine(line, sizeof(line), "PROBE", probeC, "C");
oledLine(3, line);
formatSensorLine(line, sizeof(line), "AIR", airC, "C");
oledLine(4, line);
formatSensorLine(line, sizeof(line), "RH", humidity, "%");
oledLine(5, line);
} else {
oledLine(3, "");
oledLine(4, "");
oledLine(5, "");
}
oledLine(6, needsRefill() ? "REFILL TANK" : "");
if (stage == FAULT) {
oledLine(7, "INSPECT AND RESET");
} else if (heatingStage && probeHeatPaused && airHeatPaused) {
oledLine(7, "AIR TEMP EXCEEDED 50 C");
} else if (heatingStage && (probeHeatPaused || airHeatPaused)) {
oledLine(7, "HEATER PAUSED");
} else {
oledLine(7, "");
}
}
void setup() {
const uint8_t outputs[] = {HEATER, PUMP, BLOWER, RED, YELLOW, GREEN};
for (uint8_t pin : outputs) {
digitalWrite(pin, LOW);
pinMode(pin, OUTPUT);
}
pinMode(HELMET, INPUT_PULLUP);
pinMode(TANK, INPUT_PULLUP);
pinMode(LIQUID, INPUT_PULLDOWN);
pinMode(PROBE, INPUT_PULLUP);
pinMode(DHT, INPUT_PULLUP);
Serial1.begin(115200);
Wire.setSDA(OLED_SDA);
Wire.setSCL(OLED_SCL);
Wire.begin();
Wire.setClock(400000);
delay(100);
oledOK = initOLED();
bootTime = millis();
enterStage(RELEASE_HELMET, bootTime);
if (!oledOK) fault("CHECK OLED GP4 GP5", millis());
watchdog_enable(4000, true);
}
void loop() {
digitalWrite(RED, needsRefill());
bool fresh = updateSensors(millis());
uint32_t now = millis();
updateCycle(now, fresh);
applyHeater(stage, now);
if (fresh) {
refreshScreen = true;
Serial1.print("PROBE ");
Serial1.print(probeC, 1);
Serial1.print(" C | AIR ");
Serial1.print(airC, 1);
Serial1.print(" C | RH ");
Serial1.print(humidity, 1);
Serial1.println(" %");
}
drawScreen(now);
watchdog_update();
delay(10);
}Loading
ssd1306
ssd1306