#include <ESP32Servo.h>
// Pin definitions
const int ntcPin = 34; // Analog pin for the NTC sensor (OUT pin)
const int servoPin = 5; // PWM pin for servo control
const int dialPin = 32; // Analog pin for the user temperature dial (potentiometer)
// Constants
const float maxVoltage = 3.3; // Reference voltage for ESP32 ADC
const int adcMaxValue = 4095; // Maximum ADC value for ESP32
const float maxTemp = 50.0; // Maximum temperature for the NTC sensor
const float minTemp = 0.0; // Minimum temperature for the NTC sensor
const float dialMaxTemp = 40.0; // Maximum user-adjustable temperature
const float dialMinTemp = 15.0; // Minimum user-adjustable temperature
// Servo object
Servo tempServo;
void setup() {
Serial.begin(115200);
tempServo.attach(servoPin, 500, 2400); // Attach servo with min and max pulse widths
tempServo.write(90); // Start at neutral position
}
void loop() {
// Read user-set temperature from the potentiometer
int dialValue = analogRead(dialPin);
float setPoint = map(dialValue, 0, adcMaxValue, dialMinTemp * 100, dialMaxTemp * 100) / 100.0;
// Read the current temperature from the NTC sensor
int rawValue = analogRead(ntcPin);
float currentTemp = map(rawValue, 0, adcMaxValue, minTemp * 100, maxTemp * 100) / 100.0;
// Calculate the servo position based on current temperature and user setpoint
int servoPosition = calculateServoPosition(currentTemp, setPoint);
tempServo.write(servoPosition);
// Debugging feedback
Serial.print("User Set Temp: ");
Serial.print(setPoint, 1);
Serial.print(" °C | Current Temp: ");
Serial.print(currentTemp, 1);
Serial.print(" °C | Servo Position: ");
Serial.println(servoPosition);
delay(500); // Short delay for stability
}
// Function to calculate servo position based on current temperature and target temperature
int calculateServoPosition(float currentTemp, float targetTemp) {
if (currentTemp < targetTemp - 2) {
// Too cold, increase heating
return map(currentTemp, minTemp, targetTemp, 180, 90); // Heating from max to neutral
} else if (currentTemp > targetTemp + 2) {
// Too hot, increase cooling
return map(currentTemp, targetTemp, maxTemp, 90, 0); // Cooling from neutral to max
} else {
// Within acceptable range, neutral position
return 90;
}
}