 // Spark variables for tracking humidity and temperature
 double humidity = 0;
 double temperature = 0;
+int faultCode = 0;
+int fanSpeed = 0; // percentage
+int fanOverrideSpeed = 0; // User requested fan speed. Overrides auto speed.
+int fanPulsesPerInterval = 0; // Non volatile int
+
+int setFanOnAt(String level);
+int fanOn(String command);
+int fanOff(String command);
+int reset(String command);
+
+int fanOnAtHumidityLevel = 20;
+
+// Count of fan pulses
+volatile int fanPulseCount = 0;
+
 
 void setup() {
     pinMode(ledSampling, OUTPUT);
+    pinMode(fanPulseIn, INPUT_PULLUP);
+    pinMode(fanControl, OUTPUT);
+    digitalWrite(ledSampling, LOW);
+    digitalWrite(fanControl, LOW);
+    
+    attachInterrupt(fanPulseIn, fanPulse, FALLING);
       
     Spark.variable("humidity", &humidity, DOUBLE);
     Spark.variable("temperature", &temperature, DOUBLE);
-    
+    Spark.variable("faultCode", &faultCode, INT);
+    Spark.variable("fanSpeed", &fanSpeed, INT);
+    Spark.variable("fanPulses", &fanPulsesPerInterval, INT);
+    //Spark.variable("fanOnAt", &fanOnAtHumidityLevel, INT);
+    
+    // register the cloud function
+    Spark.function("setFanOnAt", setFanOnAt);
+    Spark.function("fanOn", fanOn);
+    Spark.function("fanOff", fanOff);
+    Spark.function("reset", reset);
+
     // Take control of the spark LED and make it dimmer as it's very
     // bright by default.
     RGB.control(true);

        temperature = (double)t;
        Spark.publish("Temperature", "Measured temperature as: " + String(temperature));
    } else {
        Spark.publish("Error", "Error reading temperature. Reported: " + String(t));
        RGB.color(255, 0, 0);
        delay(1000);
    }
}
    // Initialize Temperature and humidity
    if (!humiditySensor.begin()) {
        RGB.color(255, 0, 00);
        Spark.publish("Status", "Humidity Sensor setup failed.");
    }
    
    //delay(1000);
    Spark.publish("Status", "Setup complete.");
    RGB.color(0, 0, 0);
    delay(2000);
}
