#include <SPI.h>
#include "Adafruit_MAX31855.h"
// Define the pins for SPI communication
#define MAXDO 3
#define MAXCS 4
#define MAXCLK 5
Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);
#define SSR_PIN 10
// Variables
float real_temp;
float Setpoint = 20; // In degrees C
float SetpointDiff = 3; // In degrees C
float elapsedTime, prev_time;
float refresh_rate = 500; // PID loop time in ms
float now_pid_error, prev_pid_error;
// PID constants
float kp = 2.5;
float ki = 0.06;
float kd = 0.8;
float PID_p, PID_i, PID_d, PID_total;
void setup() {
// Initialization
Serial.begin(9600); // Adjust baud rate if needed
pinMode(SSR_PIN, OUTPUT);
digitalWrite(SSR_PIN, HIGH);
// Initialize SPI communication for MAX31855
SPI.begin();
thermocouple.begin();
}
void loop() {
// Perform PID control
PID_control();
}
void PID_control() {
// Calculate PID control
elapsedTime = millis() - prev_time;
if (elapsedTime > refresh_rate) {
// Get temperature reading
real_temp = thermocouple.readCelsius();
// Calculate error
now_pid_error = Setpoint - real_temp;
// Calculate PID terms
PID_p = kp * now_pid_error;
PID_d = kd * ((now_pid_error - prev_pid_error) / refresh_rate);
// Integral term (apply only when error is small)
if (-3 < now_pid_error && now_pid_error < 3) {
PID_i = PID_i + (ki * now_pid_error);
} else {
PID_i = 0;
}
// Calculate total PID output
PID_total = PID_p + PID_i + PID_d;
// Apply limits
if (PID_total < 0) {
PID_total = 0;
}
if (PID_total > 255) {
PID_total = 255;
}
// Control the SSR using PID output
analogWrite(SSR_PIN, 255 - PID_total);
// Check if temperature is within a range of the setpoint
if (real_temp >= Setpoint - SetpointDiff && real_temp <= Setpoint + SetpointDiff) {
// Turn off the power source
digitalWrite(SSR_PIN, LOW);
} else {
// If temperature is not within range, ensure power is on
digitalWrite(SSR_PIN, HIGH);
}
// Print values for debugging
Serial.print("Setpoint: ");
Serial.println(Setpoint);
Serial.print("Temperature: ");
Serial.println(real_temp);
Serial.print("PID output: ");
Serial.println(PID_total);
// Update variables for next iteration
prev_time = millis();
prev_pid_error = now_pid_error;
}
}
`Why when the setpoint is reached Arduino keeps sending signal to the powerswitch and does not switch off. The temperature over heats. What is wrong with the code