Hey everyone, i want to control a ceramic heater with PID using the max6675 libary to get the temperatur and a IRLZ44N Mosfet to control the heater.
The heater is going always up with the temperature even the pwm signal to the gate is 0. why?
Here is my Code:
#include "max6675.h"
int PWM_pin = 9;
int max6675SO = 8;
int max6675CS = 10;
int max6675CLK = 13;
MAX6675 ktc(max6675CLK, max6675CS, max6675SO);
//Variables
float temperature_read = 0.0;
float set_temperature = 35;
float PID_error = 0;
float previous_error = 0;
float elapsedTime, Time, timePrev;
int PID_value = 0;
//PID constants
int kp = 9.1; int ki = 0.3; int kd = 1.8;
int PID_p = 0; int PID_i = 0; int PID_d = 0;
void setup() {
pinMode(PWM_pin,OUTPUT);
//TCCR2B = TCCR2B & B11111000 | 0x03; // pin 3 and 11 PWM frequency of 980.39 Hz
Time = millis();
Serial.begin(9600);
delay(500);
}
void loop() {
//READ TEMP VALUE
temperature_read = ktc.readCelsius();
//Calculate the error between the setpoint and the real value
PID_error = set_temperature - temperature_read;
//Calculate the P value
PID_p = kp * PID_error;
//Calculate the I value in a range on +-3
if(-3 < PID_error <3)
{
PID_i = PID_i + (ki * PID_error);
}
//For derivative real time to calculate speed change rate
timePrev = Time; // the previous time is stored before the actual time read
Time = millis(); // actual time read
elapsedTime = (Time - timePrev) / 1000;
//Now we can calculate the D calue
PID_d = kd*((PID_error - previous_error)/elapsedTime);
//Final total PID value is the sum of P + I + D
PID_value = PID_p + PID_i + PID_d;
//We define PWM range between 0 and 255
if(PID_value < 0)
{ PID_value = 0; }
if(PID_value > 255)
{ PID_value = 255; }
//Write PWM signal to Mosfet
analogWrite(PWM_pin,PID_value);
Serial.println(PID_value);
previous_error = PID_error; //To store the previous error for next loop.
//Ausgabe
Serial.print(ktc.readCelsius());
Serial.println("C");
delay(300);
}