#include <PID_v2.h> // include the PID library
// define constants for the PID control loop
#define PID_KP 30.0
#define PID_KI 0.7
#define PID_KD 200
#define PID_SAMPLE_TIME 250 // update the PID control loop every 0.25 second
// define constants for the temperature sensor
#define TEMP_SENSOR_PIN A0 // analog input pin for the temperature sensor
#define TEMP_SENSOR_RESISTANCE 10000 // resistance of the NTC temperature sensor in ohms
#define TEMP_SENSOR_B_CONSTANT 3950 // B constant for the NTC temperature sensor
#define TEMP_SENSOR_NOMINAL_RESISTANCE 10000 // nominal resistance of the NTC temperature sensor at 25C
// define constants for the heating element
#define HEATER_PIN 9 // digital output pin for the heating element
// define variables for the PID control loop
double setpoint; // the target temperature
double input; // the current temperature
double output; // the output of the PID control loop, used to control the heating element
// create a PID object
PID pid(&input, &output, &setpoint, PID_KP, PID_KI, PID_KD, DIRECT);
void setup() {
// initialize the serial communication
Serial.begin(9600);
// set the initial setpoint
setpoint = 25.0; // set the initial setpoint to 25C
// initialize the PID control loop
pid.SetSampleTime(PID_SAMPLE_TIME);
pid.SetOutputLimits(0, 255); // limit the output of the PID control loop to a value between 0 and 255
pid.SetMode(AUTOMATIC);
// initialize the heating element
pinMode(HEATER_PIN, OUTPUT);
}
void loop() {
// read the current temperature from the temperature sensor
input = getTemperature();
// run the PID control loop
pid.Compute();
// control the heating element based on the output of the PID control loop
analogWrite(HEATER_PIN, output);
// wait for the specified sample time before updating the control loop again
delay(PID_SAMPLE_TIME);
}
// function to read the temperature from the NTC temperature sensor
double getTemperature() {
// read the raw analog value from the temperature sensor
int raw = analogRead(TEMP_SENSOR_PIN);
// convert the raw value to resistance
double resistance = TEMP_SENSOR_RESISTANCE / ((1024.0 / raw) - 1.0);
// calculate the temperature based on the resistance of the temperature sensor
double temperature = 1.0 / (log(resistance / TEMP_SENSOR_NOMINAL_RESISTANCE) / TEMP_SENSOR_B_CONSTANT + 1.0 / 298.15) - 273.15;
return temperature;
}