#include "PID_v1.h"
// Libraries for the DS18B20 sensor
#include <OneWire.h>
#include <DallasTemperature.h>
// DS18B20 on PIN 6 on the Arduino
#define ONE_WIRE_BUS 12
//Solid state relay on PIN 5 on the Arduino
#define RELAY_PIN 9
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp = 1.5, Ki = 0.3, Kd = 0.003;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
int WindowSize = 10000;
unsigned long windowStartTime;
// heater startup
const word heaterStartMs = 5000;
bool heaterStartup = false;
double prevOutput = 0;
unsigned long prevMs = 0;
unsigned long currentMs, elapsedMs;
void setup()
{
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);
Serial.begin(115200);
Serial.println("Starting");
windowStartTime = millis();
//initialize the variables we're linked to
Setpoint = 30;
//tell the PID to range between 0 and the full window size
myPID.SetOutputLimits(0, WindowSize);
//turn the PID on
myPID.SetMode(AUTOMATIC);
}
void loop()
{
currentMs = millis();
elapsedMs = (currentMs - prevMs);
if (Output == 0) heaterStartup = false;
if (prevOutput == 0 && Output) {
heaterStartup = true;
prevMs = currentMs;
}
sensors.requestTemperatures();
Input = sensors.getTempCByIndex(0);
Serial.print("Temperature: ");
Serial.println(Input);
prevOutput = Output;
myPID.Compute();
if (elapsedMs >= heaterStartMs) {
/************************************************
turn the output pin on/off based on pid output
************************************************/
if (millis() - windowStartTime > WindowSize)
{
//time to shift the Relay Window
windowStartTime += WindowSize;
}
if (Output < millis() - windowStartTime)
digitalWrite(RELAY_PIN, HIGH);
else
digitalWrite(RELAY_PIN, LOW);
}
}