 // This #include statement was automatically added by the Spark IDE.
 #include "HTU21D/HTU21D.h"
 
-int ledSampling = D2; // use led for now, but this is RS232 comms LED.
-//int clockSpeed = CLOCK_SPEED_400KHZ;
-
-// Loop counter 
-int loopCounter = 0;
+int ledSampling = D2; 
+int fanPulseIn = D4; // Max pin for Core intterupt
+int fanControl  = D7; 
 
 // Temperature and humidity
 HTU21D humiditySensor;

    
    digitalWrite(ledSampling, HIGH);
    RGB.color(0, 0, 125);
    Spark.publish("Reading", "Reading...");
    delay(100);
    
    readHumidity();
    readTemperature();
    
    delay(100);
    RGB.color(0, 0, 0);
    digitalWrite(ledSampling, LOW);
    loopCounter = 0;
    
    delay(2000);
     
     // Do not use Sleep as it breaks Photon WiFi!
    // Can we put the Core into low power mode?
    // Photon:
    //System.sleep(2);
    // Core:
    // Spark.sleep(1);
    delay(2000);
} 

void readHumidity() {

// 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);
