Fix Arduino IDE code for ESP32 PID heat controller.

Job ID: 35792934

Budget: $14 – $30 NZD

I've been trying to get a PID heat controller for an ESP32 working unsuccessfully. (I mustn't know what I'm doing!). The heater element keeps going at 100%.

Keen for someone to help me out.

Here's the code based on the AutoPID BasicTempControl Example Sketch but using an Adafruit MAX31865 for the temp sensor:

#include <AutoPID.h>
#include <Adafruit_MAX31865.h>
#include <Arduino.h>

#define TEMP_READ_DELAY 800 //can only read digital temp sensor every ~750ms

//pid settings and gains
#define OUTPUT_MIN 0
#define OUTPUT_MAX 255
#define KP .12
#define KI .0003
#define KD 0

double temperature, setPoint, outputVal;
const byte OUTPUT_PIN = 32;

// Use software SPI: CS, DI, DO, CLK
Adafruit_MAX31865 thermo = Adafruit_MAX31865(5, 23, 19, 18);
// use hardware SPI, just pass in the CS pin

// The value of the Rref resistor. Use 430.0 for PT100 and 4300.0 for PT1000
#define RREF 430.0
// The 'nominal' 0-degrees-C resistance of the sensor
// 100.0 for PT100, 1000.0 for PT1000
#define RNOMINAL 100.0

//input/output variables passed by reference, so they are updated automatically
AutoPID myPID(&temperature, &setPoint, &outputVal, OUTPUT_MIN, OUTPUT_MAX, KP, KI, KD);

unsigned long lastTempUpdate; //tracks clock time of last temp update

//call repeatedly in loop, only updates after a certain time interval
//returns true if update happened
bool updateTemperature() {
if ((millis() - lastTempUpdate) > TEMP_READ_DELAY) {
uint16_t rtd = thermo.readRTD();
temperature = thermo.temperature(RNOMINAL, RREF); //get temp reading
lastTempUpdate = millis();
//temperatureSensors.requestTemperatures(); //request reading for next time
return true;
}
return false;
}//void updateTemperature

void setup() {
Serial.begin(115200);

//pinMode(POT_PIN, INPUT);
ledcAttachPin(OUTPUT_PIN, 0);
ledcSetup(0, 4000, 8);

//pinMode(LED_PIN, OUTPUT);

thermo.begin(MAX31865_2WIRE); // set to 2WIRE or 4WIRE as necessary

//temperatureSensors.requestTemperatures();
//while (!updateTemperature()) {} //wait until temp sensor updated
//if temperature is more than 4 degrees below or above setpoint, OUTPUT will be set to min or max respectively
myPID.setBangBang(4);
//set PID update interval to 800ms
myPID.setTimeStep(800);

}//void setup

void loop() {
updateTemperature();
setPoint = 35;
myPID.run(); //call every loop, updates automatically at certain time interval
ledcWrite(0, outputVal);
//Print temperature on serial monitor
Serial.print("Temperature = "); Serial.print(temperature); Serial.print(", Output = "); Serial.println(outputVal);
} //void loop