How to manage PID with two relay outputs?

Hello,
I am using the Arduino PID Library for temperature control.
There are two relays, one for activating a heater and the other for activating a cooler.

The library has a relay output example for dealing with binary output (https://playground.arduino.cc/Code/PIDLibraryRelayOutputExample/):

int WindowSize = 5000;
void setup() {
  windowStartTime = millis();
  //tell the PID to range between 0 and the full window size
  myPID.SetOutputLimits(0, WindowSize);
}

void loop() {
  Input = analogRead(0);
  myPID.Compute();
  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);
}

First of all I noticed a discrepancy in the comparison symbol between the previous code from the documentation and that on Github (https://github.com/br3ttb/Arduino-PID-Library/blob/master/examples/PID_RelayOutput/PID_RelayOutput.ino):
if (Output < millis() - windowStartTime) digitalWrite(RELAY_PIN, HIGH);

Which one is correct?

And how can I change the code to manage two relays instead of only one?:

Depends on if you want more HIGH or more LOW as Output increases.

Almost all relay modules seem to use LOW for ON and HIGH for OFF. Therefore you might want more LOW as Output goes up and therefore

  if (Output > now - windowStartTime) 
    digitalWrite(RelayPin, HIGH);  // Relay OFF
  else 
    digitalWrite(RelayPin, LOW); // Relay ON

or

  if (Output < now - windowStartTime) 
    digitalWrite(RelayPin, LOW); // Relay ON
  else
    digitalWrite(RelayPin, HIGH); // Relay OFF
1 Like