#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// --- Stepper Driver Pins (ESP32) ---
#define DIR_PIN 27
#define STEP_PIN 26
// --- DS18B20 setup ---
#define ONE_WIRE_BUS 25
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
// --- LCD I2C setup ---
LiquidCrystal_I2C lcd(0x27, 16, 2); // use 0x3F if display doesn't show
// --- Variables ---
int tempReadCount = 0;
bool systemDeactivated = false;
unsigned long deactivationTime = 0;
// --- Motor Position Tracker ---
int motorPosition = 0; // absolute steps (0, 3, 6, 50)
// --- Functions ---
void stepMotor(int steps) {
if (steps > 0) {
digitalWrite(DIR_PIN, HIGH); // forward
} else {
digitalWrite(DIR_PIN, LOW); // backward
steps = -steps;
}
for (int i = 0; i < steps; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(800);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(800);
}
}
void moveToPosition(int target) {
int delta = target - motorPosition;
stepMotor(delta);
motorPosition = target;
}
void setup() {
Serial.begin(115200); // ESP32 default baud
sensors.begin();
lcd.init();
lcd.backlight();
pinMode(DIR_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
// System loading
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("System Loading");
Serial.println("System Loading");
delay(2000);
// System activated
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("System Activated");
Serial.println("System Activated");
// Move motor to 50 steps initially
moveToPosition(50);
delay(500);
}
void loop() {
sensors.requestTemperatures();
float tempC = sensors.getTempCByIndex(0);
// Always display temperature
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(tempC);
lcd.print((char)223);
lcd.print("C");
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println("°C");
if (!systemDeactivated) {
// --- Control logic reordered from lowest → highest ---
if (tempC > 62 && tempC <= 71.9) {
moveToPosition(6);
lcd.setCursor(0, 1);
lcd.print("Motor at 10");
lcd.print((char)223);
}
else if (tempC >= 72 && tempC < 77) {
Serial.print("Alert: Temp at ");
Serial.print(tempC);
Serial.println("°C");
lcd.setCursor(0, 1);
lcd.print("Alert: T at ");
lcd.print(int(tempC));
lcd.print((char)223);
lcd.println("C");
}
else if (tempC >= 77) {
Serial.println("Alert: Temp > 77°C");
lcd.setCursor(0, 1);
lcd.print("ALERT: T > 77");
lcd.print((char)223);
lcd.print("C");
tempReadCount++;
if (tempReadCount >= 5) {
moveToPosition(0);
Serial.println("Alert: T > 77°C; system Deactivated");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("System Deactivated");
systemDeactivated = true;
deactivationTime = millis();
}
}
}
else {
if (tempC <= 60) { // Temperature falls below 60
systemDeactivated = false;
tempReadCount = 0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("System");
lcd.setCursor(0,1);
lcd.print("Reactivated");
Serial.println("System Reactivated");
moveToPosition(50);
delay(1000);
}
}
delay(2000);
}
NEMA 17 (Stepper Motor)
A4988 Motor Driver
DS18B20
LCD_I2C
ESP32