How to manage PID with two relay outputs?

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 (

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);
  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 (
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
    digitalWrite(RelayPin, LOW); // Relay ON


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