/********************************************************
* PID Simulation Example
* Reading analog input 0 to control analog PWM output 3
* simulate a heater in a partially insulated Al block
* Code modified from
https://github.com/br3ttb/Arduino-PID-Library/blob/master/examples/PID_Basic/PID_Basic.ino
********************************************************/
#include <PID_v1.h>
#define PIN_INPUT 0
#define PIN_OUTPUT 3
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
void setup()
{
Serial.begin(115200);
//initialize the variables we're linked to
Input = analogRead(PIN_INPUT);
Setpoint = 100;
//turn the PID on
myPID.SetMode(AUTOMATIC);
}
void loop()
{
float heaterWatts = ((int)Output)*20.0/255; // 20W heater
float blockTemp = simPlant(heaterWatts);
//Input = analogRead(PIN_INPUT);
Input = blockTemp;
myPID.Compute();
analogWrite(PIN_OUTPUT, Output);
report();
}
void report(void){
static uint32_t last = 0;
const int interval = 1000;
if (millis() - last > interval){
last += interval;
// Serial.print(millis()/1000.0);
Serial.print(Setpoint);
Serial.print(' ');
Serial.print(Input);
Serial.print(' ');
Serial.println(Output);
}
}
float simPlant(float Q){ // heat input in W (or J/s)
// simulate a 1x1x2cm aluminum block with a heater and passive ambient cooling
float C = 237; // W/mK thermal conduction coefficient for Al
float h = 5 ; // W/m2K thermal convection coefficient for Al passive
float Cps = 0.89; // J/g°C
float area = 1e-4; // m2 area for convection
float mass = 10 ; // g
float Tamb = 25; // °C
static float T = Tamb; // °C
static uint32_t last = 0;
uint32_t interval = 100; // ms
if(millis() - last >= interval){
last += interval;
T = T + Q*interval/1000/mass/Cps - (T-Tamb)*area*h;
}
return T;
}