#include <OneWire.h>
#include <DallasTemperature.h>
#include <QuickPID.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temperature = 100;
float temperatureTarget = 180;
float fanSpeed = 0;
QuickPID pid(&temperature, &fanSpeed, &temperatureTarget);
//For DEBUG use only
float systemHeatGeneration = 180.0 / (5.0*60.0);
float fanMaxCoolingPerformance = -1.0 * (190.0-180.0) / (1.0*5.0) - systemHeatGeneration;
void setup(void) {
Serial.begin(9600);
sensors.begin(); // IC Default 9 bit. If you have troubles consider upping it 12. Ups the delay giving the IC more time to process the temperature measurement
pid.SetOutputLimits(0, 255);
pid.SetSampleTimeUs(100000);
pid.SetTunings(2, 2, 0);
pid.SetMode(pid.Control::automatic);
pid.SetControllerDirection(pid.Action::reverse); //Reverse controller direction to get outputs (fan speed) for cooling instead of heating system
}
void loop(void) {
sensors.requestTemperatures();
//temperature = sensors.getTempFByIndex(0);
temperature = temperature + systemHeatGeneration + random(systemHeatGeneration) + fanMaxCoolingPerformance*(fanSpeed/255.0); //DEBUG - fake increasing system temperature cooled by a variable-speed fan
if((int)random(6) == 0) {
temperature = temperature + 2 * systemHeatGeneration * (random(2) - 1);
}
if((int)random(64) == 0) {
temperature = temperature + 10 * systemHeatGeneration;
}
pid.Compute();
Serial.println("Current temp is " + String(temperature) + " °F. Target temp is " + String(temperatureTarget) + " °F. Fan duty cycle is " + String(fanSpeed) + ".");
delay(250);
}