/******************************************************** PID RelayOutput Example Same as basic example, except that this time, the output is going to a digital pin which (we presume) is controlling a relay. The pid is designed to output an analog value, but the relay can only be On/Off. To connect them together we use "time proportioning control" Tt's essentially a really slow version of PWM. First we decide on a window size (5000mS say.) We then set the pid to adjust its output between 0 and that window size. Lastly, we add some logic that translates the PID output into "Relay On Time" with the remainder of the window being "Relay Off Time" ********************************************************/ #include #define RelayPin 12 //Define Variables we'll be connecting to double Setpoint, Input, Output; int Vo; float R1 = 10000; float logR2, R2, T, rawdata; float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07; float powervoltage=5;//define the power supply voltage. const int ThermistorPin = A1; //Specify the links and initial tuning parameters PID myPID(&Input, &Output, &Setpoint, 2, 5, 1, DIRECT); int WindowSize = 5000; unsigned long windowStartTime; void setup() { pinMode(RelayPin, OUTPUT); 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() { Vo = analogRead(ThermistorPin); R2 = R1 * (1023.0 / (float)Vo - 1.0); logR2 = log(R2); T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2)); T = T - 273.15; Input = T; myPID.Compute(); /************************************************ turn the output pin on/off based on pid output ************************************************/ unsigned long now = millis(); if (now - windowStartTime > WindowSize) { //time to shift the Relay Window windowStartTime += WindowSize; } if (Output > now - windowStartTime) digitalWrite(RelayPin, HIGH); else digitalWrite(RelayPin, LOW); delay(500); Serial.println(T); }