   thresholdLow = avg + deviation / 3.0f;
   thresholdHigh = avg + 2.0f * deviation / 3.0f;
 
-  // print out the values for debugging/plotting
+  on_off = avg;
+  // switch the relays!
+  if (humidity < thresholdLow) {
+    // because we don't know the status of the 3-way switch, we switch both
+    // relays at the same time and hope there is no short circuit. This should
+    // not be an issue, but anyway...
+    digitalWrite(K1, NormallyConnected);
+    digitalWrite(K2, NormallyConnected);
+    on_off -= 20;
+  } else if (humidity > thresholdHigh) {
+    digitalWrite(K2, NormallyOpen);
+    // since we don't know how the switch is switched, we first switch K2 to
+    // non-connected, then wait a while for it to settle, before we switch
+    // K1 to connected L. This should prevent any shorts (don't know if that
+    // is actually an issue, but better safe than sorry).
+    delay(milliseconds_switch_delay);
+    digitalWrite(K1, NormallyOpen);
+    on_off -= 10;
+  } else {
+    on_off -= 15;
+  }
+   // print out the values for debugging/plotting
   Serial.print("humidity = ");
   Serial.print(humidity);
   Serial.print(", tlow = ");
   Serial.print(thresholdLow);
   Serial.print(", thi = ");
   Serial.print(thresholdHigh);
-  Serial.print(", dmin = ");
+  Serial.print(", avg = ");
   Serial.print((int)(avg));
-  Serial.print(", dmax = ");
-  Serial.println((int)(avg + deviation));
-
-  // switch the relays!
-  if (humidity < thresholdLow) {
-    // HIGH means setting the relay to NC
-    digitalWrite(relayPin, HIGH);
-  } else if (humidity > thresholdHigh) {
-    // LOW means setting the relay to NO
-    digitalWrite(relayPin, LOW); 
-  }
+  Serial.print(", deviation = ");
+  Serial.print((int)(avg + deviation));
+  Serial.print(", on_off = ");
+  Serial.println((int)(on_off));
+  
   delay(milliseconds_sleep);
 }

#include <Time.h>

const int relayPin =  11;
const int sensorPin = A0;    // select the input pin for the potentiometer
const int MINHUMIDITY = 0;
const int MAXHUMIDITY = 1023;
const int milliseconds_sleep = 5000;
const float avg_decay = 0.00001;
const float deviation_decay = 0.01;
int thresholdLow = 0;
int thresholdHigh = 0;
float avg = 0;
float deviation = 20;
int humidity = 0;
int startup_seconds = 900; // sensor needs to settle for 15 minutes

int get_humidity() {
  int sensorValue = analogRead(sensorPin);

}

void setup() {
  Serial.begin(9600);
  
  // set relays to normally connected
  pinMode(K1, OUTPUT);
  pinMode(K2, OUTPUT);
  digitalWrite(K1, NormallyConnected);
  digitalWrite(K2, NormallyConnected);

  // initialize sensor
  pinMode(sensorPin, INPUT);
  avg = get_humidity();
}

