Ticker.h

Ticker.h

--- _66-slack-bot/_66-slack-bot.ino
+++ _66-slack-bot/_66-slack-bot.ino
@@ -1,4 +1,4 @@
-// 80MHZ NODEMCU V.1
+// 80MHZ NODEMCU V.1, use git version of esp8266/Arduino
 // slackbot testing using https://github.com/urish/arduino-slack-bot
 /**
    Arduino Real-Time Slack Bot
@@ -30,6 +30,9 @@
 #include <ArduinoOTA.h>
 #include <WiFiUdp.h>
 #include <Average.h>
+//for LED status
+#include <Ticker.h>
+Ticker ticker;

 extern "C" {
 #include "user_interface.h"
@@ -81,7 +84,7 @@
 } ir_data;

 // mqtt
-void callback(char* intopic, byte* inpayload, unsigned int length);
+void ICACHE_RAM_ATTR callback(char* intopic, byte* inpayload, unsigned int length);

 const char* hellotopic  = "HELLO";
 const char* willTopic   = "clients/nodemcu";
@@ -102,6 +105,17 @@
 // ir
 IRrecv irrecv(IR_RX_PIN);
 lgWhisen lgWhisen;
+
+unsigned long lastPing = 0;
+long lastReconnectAttempt = 0;
+time_t prevDisplay = 0;
+
+void tick()
+{
+  //toggle state
+  int state = digitalRead(BUILTIN_LED);  // get the current state of GPIO1 pin
+  digitalWrite(BUILTIN_LED, !state);     // set pin to the opposite state
+}

 boolean reconnect() {
   if (!mqttclient.connected())
@@ -119,23 +133,7 @@
   return mqttclient.connected();
 }

-void ICACHE_RAM_ATTR callback(char* intopic, byte* inpayload, unsigned int length)
-{
-  String receivedtopic = intopic;
-  String receivedpayload ;
-
-  for (int i = 0; i < length; i++) {
-    receivedpayload += (char)inpayload[i];
-  }
-
-  Serial.printf("[MQTT] payload: %s\n", receivedpayload.c_str());
-  if (length <= 200)
-  {
-    parseMqttMsg(receivedpayload, receivedtopic);
-  }
-}
-
-void parseMqttMsg(String receivedpayload, String receivedtopic)
+void ICACHE_RAM_ATTR parseMqttMsg(String receivedpayload, String receivedtopic)
 {
   char json[] = "{\"DS18B20\":28.00,\"FreeHeap\":32384,\"RSSI\":-74,\"millis\":2413775}";

@@ -150,6 +148,22 @@
   if (root.containsKey("DS18B20"))
   {
     ave.push(root["DS18B20"]);
+  }
+}
+
+void ICACHE_RAM_ATTR callback(char* intopic, byte* inpayload, unsigned int length)
+{
+  String receivedtopic = intopic;
+  String receivedpayload ;
+
+  for (int i = 0; i < length; i++) {
+    receivedpayload += (char)inpayload[i];
+  }
+
+  Serial.printf("[MQTT] payload: %s\n", receivedpayload.c_str());
+  if (length <= 200)
+  {
+    parseMqttMsg(receivedpayload, receivedtopic);
   }
 }

@@ -272,7 +286,7 @@
   webSocket.sendTXT(json);
 }

-void ICACHE_RAM_ATTR processSlackMessage(String receivedpayload)
+void processSlackMessage(String receivedpayload)
 {
   char json[] = "{\"type\":\"message\",\"user\":\"XX0990XX\",\"text\":\"XX0990XX\",\"team\":\"XX0990XX\",\"user_team\":\"XX0990XX\",\"user_profile\":{\"avatar_hash\":\"g9c0531af70a\",\"image_72\":\"https://secure.gravatar.com/avatar/9c0531af70ad0dbed618e9f4c2198145.jpg?s=72&d=https%3A%2F%2Fa.slack-edge.com%2F66f9%2Fimg%2Favatars%2Fava_0019-72.png\",\"first_name\":null,\"real_name\":\"\",\"name\":\"XX0990XX\"},\"channel\":\"XX0990XX\",\"ts\":\"1466954463.000275\"}";
   receivedpayload.toCharArray(json, 1024);
@@ -381,6 +395,7 @@
     case WStype_DISCONNECTED:
       Serial.printf("[WebSocket] Disconnected :-( \n");
       connected = false;
+      ticker.attach(0.3, tick);
       break;

     case WStype_CONNECTED:
@@ -388,6 +403,8 @@
       sendPing();
       webSocket.loop();
       sendHello();
+      webSocket.loop();
+      ticker.attach(0.6, tick);
       break;

     case WStype_TEXT:
@@ -478,13 +495,49 @@
   Serial.println(WiFi.localIP());
 }

+void ArduinoOTA_config()
+{
+  //OTA
+  // Port defaults to 8266
+  ArduinoOTA.setPort(8266);
+  ArduinoOTA.setHostname("esp-slackbot");
+  ArduinoOTA.setPassword(OTA_PASSWORD);
+  ArduinoOTA.onStart([]()
+  {
+    //sendUdpSyslog("ArduinoOTA Start");
+  });
+  ArduinoOTA.onEnd([]()
+  {
+    //sendUdpSyslog("ArduinoOTA End");
+  });
+  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
+  {
+    //syslogPayload = "Progress: ";
+    //syslogPayload += (progress / (total / 100));
+    //sendUdpSyslog(syslogPayload);
+  });
+  ArduinoOTA.onError([](ota_error_t error)
+  {
+    //ESP.restart();
+    if (error == OTA_AUTH_ERROR) abort();
+    else if (error == OTA_BEGIN_ERROR) abort();
+    else if (error == OTA_CONNECT_ERROR) abort();
+    else if (error == OTA_RECEIVE_ERROR) abort();
+    else if (error == OTA_END_ERROR) abort();
+  });
+
+  ArduinoOTA.begin();
+}
+
 void setup()
 {
   Serial.begin(115200);
   Serial.println();
   Serial.println("Starting....... ");
-  //Serial.setDebugOutput(true);
+
+  Serial.setDebugOutput(false);
   pinMode(LED_BUILTIN, OUTPUT);
+  ticker.attach(0.5, tick);

   // ac
   ir_data.ac_mode     = 0;
@@ -508,6 +561,7 @@

   // wifi connect
   wifi_connect();
+  ticker.attach(0.2, tick);

   clientName = "esp8266-";
   uint8_t mac[6];
@@ -518,53 +572,138 @@

   // ntp update
   udp.begin(localPort);
-  setSyncProvider(getNtpTime);
-
   if (timeStatus() == timeNotSet)
   {
     Serial.println("get ntp time");
     setSyncProvider(getNtpTime);
     delay(500);
   }
-
+  configTime(9 * 3600, 0, "pool.ntp.org", "time.nist.gov");
+
+  // OTA
+  ArduinoOTA_config();
   // mqtt connect
-  reconnect();
-
-  //OTA
-  // Port defaults to 8266
-  ArduinoOTA.setPort(8266);
-  ArduinoOTA.setHostname("esp-slackbot");
-  ArduinoOTA.setPassword(OTA_PASSWORD);
-  ArduinoOTA.onStart([]()
-  {
-    //sendUdpSyslog("ArduinoOTA Start");
-  });
-  ArduinoOTA.onEnd([]()
-  {
-    //sendUdpSyslog("ArduinoOTA End");
-  });
-  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
-  {
-    //syslogPayload = "Progress: ";
-    //syslogPayload += (progress / (total / 100));
-    //sendUdpSyslog(syslogPayload);
-  });
-  ArduinoOTA.onError([](ota_error_t error)
-  {
-    //ESP.restart();
-    if (error == OTA_AUTH_ERROR) abort();
-    else if (error == OTA_BEGIN_ERROR) abort();
-    else if (error == OTA_CONNECT_ERROR) abort();
-    else if (error == OTA_RECEIVE_ERROR) abort();
-    else if (error == OTA_END_ERROR) abort();
-  });
-
-  ArduinoOTA.begin();
-}
-
-unsigned long lastPing = 0;
-long lastReconnectAttempt = 0;
-time_t prevDisplay = 0;
+  reconnect();
+}
+
+void irrecv_config()
+{
+  // ac ir rx
+  decode_results results;
+
+  if (irrecv.decode(&results))
+  {
+    if (lgWhisen.decode(&results))
+    {
+      if (lgWhisen.get_ir_mode() != 0)
+      {
+        ir_data.ac_mode = 1;
+        ir_data.timermode = false;
+      }
+      else
+      {
+        ir_data.ac_mode = 0;
+        ir_data.timermode = false;
+      }
+
+      if (lgWhisen.get_ir_temperature() != 255)
+      {
+        ir_data.ac_temp = lgWhisen.get_ir_temperature();
+      }
+
+      if (lgWhisen.get_ir_flow() != 255)
+      {
+        ir_data.ac_flow = lgWhisen.get_ir_flow();
+      }
+
+      sendCheck();
+    }
+    irrecv.enableIRIn();
+  }
+}
+
+void webSocket_config()
+{
+  // slack
+  webSocket.loop();
+
+  if (connected) {
+    // Send ping every 5 seconds, to keep the connection alive
+    if (millis() - lastPing > 5000)
+    {
+      sendPing();
+      webSocket.loop();
+      lastPing = millis();
+    }
+  }
+  else
+  { // Try to connect / reconnect to slack
+    connected = connectToSlack();
+    if (!connected)
+    {
+      delay(500);
+    }
+  }
+}
+
+void irtxchange_config()
+{
+  // ac change, ir tx
+  if (ir_data.haveData)
+  {
+    lgWhisen.setTemp(ir_data.ac_temp);
+    lgWhisen.setFlow(ir_data.ac_flow);
+
+    switch (ir_data.ac_mode)
+    { // ac power down
+      case 0:
+        Serial.println("IR -----> AC Power Down");
+        irrecv.disableIRIn();
+        lgWhisen.power_down();
+        delay(5);
+        irrecv.enableIRIn();
+        break;
+
+      // ac on
+      case 1:
+        Serial.println("IR -----> AC Power On");
+        irrecv.disableIRIn();
+        lgWhisen.activate();
+        delay(5);
+        irrecv.enableIRIn();
+        break;
+
+      default:
+        break;
+    }
+    sendCheck();
+    ir_data.haveData = false;
+  }
+}
+
+void irtxtimer_config()
+{
+  // ac timer
+  if (ir_data.timermode)
+  {
+    if (((millis() - ir_data.timerMillis) > ir_data.nextTimercheck) || !ir_data.timerfirst)
+    {
+      if (ir_data.ac_mode == 0)
+      {
+        ir_data.ac_mode = 1;
+        ir_data.nextTimercheck = ir_data.intervalon;
+      }
+      else
+      {
+        ir_data.ac_mode = 0;
+        ir_data.nextTimercheck = ir_data.intervaloff;
+      }
+      ir_data.haveData = true;
+      ir_data.timerfirst  = true;
+      ir_data.timerMillis = millis();
+    }
+  }
+}

 /**
   Sends a ping every 5 seconds, and handles reconnections
@@ -596,121 +735,11 @@
     }
     else
     {
-      // ac ir rx
-      decode_results results;
-
-      if (irrecv.decode(&results))
-      {
-        if (lgWhisen.decode(&results))
-        {
-          if (lgWhisen.get_ir_mode() != 0)
-          {
-            ir_data.ac_mode = 1;
-            ir_data.timermode = false;
-          }
-          else
-          {
-            ir_data.ac_mode = 0;
-            ir_data.timermode = false;
-          }
-
-          if (lgWhisen.get_ir_temperature() != 255)
-          {
-            ir_data.ac_temp = lgWhisen.get_ir_temperature();
-          }
-
-          if (lgWhisen.get_ir_flow() != 255)
-          {
-            ir_data.ac_flow = lgWhisen.get_ir_flow();
-          }
-
-          sendCheck();
-        }
-        irrecv.enableIRIn();
-      }
-
-      // slack
-      webSocket.loop();
-
-      if (connected) {
-        // Send ping every 5 seconds, to keep the connection alive
-        if (millis() - lastPing > 5000)
-        {
-          sendPing();
-          lastPing = millis();
-        }
-      }
-      else
-      { // Try to connect / reconnect to slack
-        connected = connectToSlack();
-        if (!connected)
-        {
-          delay(500);
-        }
-      }
-
-      // ac change, ir tx
-      if (ir_data.haveData)
-      {
-        lgWhisen.setTemp(ir_data.ac_temp);
-        lgWhisen.setFlow(ir_data.ac_flow);
-
-        switch (ir_data.ac_mode)
-        { // ac power down
-          case 0:
-            Serial.println("IR -----> AC Power Down");
-            irrecv.disableIRIn();
-            lgWhisen.power_down();
-            delay(5);
-            irrecv.enableIRIn();
-            break;
-
-          // ac on
-          case 1:
-            Serial.println("IR -----> AC Power On");
-            irrecv.disableIRIn();
-            lgWhisen.activate();
-            delay(5);
-            irrecv.enableIRIn();
-            break;
-
-          default:
-            break;
-        }
-        sendCheck();
-        ir_data.haveData = false;
-      }
-
-      // ac timer
-      if (ir_data.timermode)
-      {
-        if (((millis() - ir_data.timerMillis) > ir_data.nextTimercheck) || !ir_data.timerfirst)
-        {
-          if (ir_data.ac_mode == 0)
-          {
-            ir_data.ac_mode = 1;
-            ir_data.nextTimercheck = ir_data.intervalon;
-          }
-          else
-          {
-            ir_data.ac_mode = 0;
-            ir_data.nextTimercheck = ir_data.intervaloff;
-          }
-          ir_data.haveData = true;
-          ir_data.timerfirst  = true;
-          ir_data.timerMillis = millis();
-        }
-      }
+      irrecv_config();
+      webSocket_config();
+      irtxchange_config();
+      irtxtimer_config();
       mqttclient.loop();
-    }
-
-    if (nextCmdId %2 == 0)
-    {
-      digitalWrite(LED_BUILTIN, HIGH);
-    }
-    else
-    {
-      digitalWrite(LED_BUILTIN, LOW);
     }
     ArduinoOTA.handle();
   }
@@ -793,7 +822,6 @@
   Serial.print(ave.mean());
   Serial.print(" ave.stddev(): ");
   Serial.println(ave.stddev());
-
 }

 void printDigits(int digits)


commit

commit

--- watermeter/wifi.ino
+++ watermeter/wifi.ino
@@ -38,6 +38,20 @@
   WiFi.mode(WIFI_STA);

   delay(1000);
+
+  String mac = WiFi.macAddress();
+  String macAddr = "";
+
+  for (int i = 0; i < mac.length(); i++) {
+    if (mac[i] != ':') macAddr += mac[i];
+  }
+
+  String hostName = WEB_WATERMETER_FIRST_NAME;
+  hostName += WEB_WATERMETER_LAST_NAME;
+  hostName += "_";
+  hostName += macAddr;
+
+  WiFi.hostname(hostName);

   WiFi.begin(wmConfig.staSsid, wmConfig.staPassword);


this is the code that is currently on the leo

--- pi_interrupt_mouse/pi_interrupt_mouse.ino
+++ pi_interrupt_mouse/pi_interrupt_mouse.ino
@@ -38,11 +38,11 @@

 void setup() {
   mySerial.begin(9600);
-  Serial.begin(115200);    // serial / USB port
-  while (!Serial);
+  // Serial.begin(115200);
+  // while (!Serial);
   AbsoluteMouse.begin();
   attachInterrupt(digitalPinToInterrupt(2), interrupt, RISING); //interrupt pin from Mega
-  Serial.println("Ready");
+  // Serial.println("Ready");
 }

 void clickMouse(){
@@ -86,11 +86,11 @@
     String cmdStr2 = String(cmd2);

     if (cmdStr.equals(cmdStr2)) {
-      //mySerial.println(cmd);
-      //Serial.println("cmd: " + cmdStr);
+      // mySerial.println(cmd);
+      // Serial.println("cmd: " + cmdStr);
       String dx = cmdStr.substring(0,5);
       String dy = cmdStr.substring(5,10);
-      //Serial.println("goto " + dx + " " + dy);
+      // Serial.println("goto " + dx + " " + dy);
       int x = dx.toInt();
       int y = dy.toInt();
       AbsoluteMouse.moveTo(x,y);
@@ -101,7 +101,7 @@
         mySerial.readBytesUntil('.', cmd, 11);
         loop();
       }
-      //Serial.println("Packet miss");
+      // Serial.println("Packet miss");
     }
   }


attach/detach the servo

attach/detach the servo

--- tracker/tracker.ino
+++ tracker/tracker.ino
@@ -134,12 +134,10 @@

     pinMode(LED_DEBUG, OUTPUT);
     pinMode(PIN_TX, OUTPUT);
+    pinMode(SERVO_PIN_HORZ_POWER, OUTPUT);

     pinMode(PIN_PERIF_POWER, OUTPUT);
     digitalWrite(PIN_PERIF_POWER, LOW); // low = 0n (PNP)
-
-    pinMode(SERVO_PIN_HORZ_POWER, OUTPUT);
-    digitalWrite(SERVO_PIN_HORZ_POWER, LOW); // low = 0n (PNP)

     digitalWrite(LED_DEBUG, HIGH);

@@ -148,7 +146,7 @@
     vw_setup(2000);      // Bits per sec
     vw_set_tx_pin(PIN_TX);

-    servo_horz.attach(SERVO_PIN_HORZ, SERVO_HORZ_MIN, SERVO_HORZ_MAX);
+    servoOn();
     servo_horz.writeMicroseconds(servo_horz_pos);

 }
@@ -256,6 +254,7 @@
  */
 void servoOn()
 {
+  servo_horz.attach(SERVO_PIN_HORZ, SERVO_HORZ_MIN, SERVO_HORZ_MAX);
   digitalWrite(SERVO_PIN_HORZ_POWER, LOW); // low = 0n (PNP)
 }

@@ -264,6 +263,7 @@
  */
 void servoOff()
 {
+  servo_horz.detach();
   digitalWrite(SERVO_PIN_HORZ_POWER, HIGH); // low = 0n (PNP)
 }


Probationary Xtal sanity check

Probationary Xtal sanity check

--- Arduino/V0p2_Main/V0p2_Main.ino
+++ Arduino/V0p2_Main/V0p2_Main.ino
@@ -384,6 +384,42 @@
       }
     }
 //  posPOST(2, F("slow RTC clock OK"));
+#if 1 // Probationary Xtal sanity check
+  // Test low frequency oscillator vs main clock oscillator.
+  // Tests clock frequency with 15 ms nap in between for up to 30 cycles and panics if not within bounds.
+  // As of 2016-02-16, all working REV7s give count >= 120 and that fail to program via bootloader give count <= 119
+  // REV10 gives 119-120 (only one tested though)
+  {
+    static const uint8_t optimalLFClock = 122; // might be optimal...
+    static const uint8_t errorLFClock = 4; // max drift from allowed value
+    uint8_t count = 0;
+    for(uint8_t i = 0; ; i++) {
+      ::OTV0P2BASE::nap(WDTO_15MS);
+      ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
+      // wait for edge on xtal counter
+      // start counting cycles
+      // on next edge, stop
+          const uint8_t t0 = TCNT2;
+          while(t0 == TCNT2) {}
+          const uint8_t t01 = TCNT0;
+          const uint8_t t1 = TCNT2;
+          while(t1 == TCNT2) {}
+          const uint8_t t02 = TCNT0;
+          count = t02-t01;
+      }
+      // Check end conditions
+      if((count < optimalLFClock+errorLFClock) & (count > optimalLFClock-errorLFClock)) break;
+      if(i > 30) panic();
+    }
+    // optionally print value to debug
+#if 0 && defined(DEBUG)
+    DEBUG_SERIAL_PRINT_FLASHSTRING("Xtal cntr check: ");
+    DEBUG_SERIAL_PRINT(count);
+    DEBUG_SERIAL_PRINTLN();
+#endif
+  }
+#endif // Probationary Xtal sanity check
+
 #else
   DEBUG_SERIAL_PRINTLN_FLASHSTRING("(No xtal.)");
 #endif


Minor comment text modification

Minor comment text modification

--- Arduino-Cottage-Monitoring-System.ino
+++ Arduino-Cottage-Monitoring-System.ino
@@ -52,7 +52,7 @@
 #define  DEVICE_ID  "Uno"
 #define MQTT_SERVER "192.168.1.2" // IP address of MQTT server. CHANGE THIS TO CORRECT ONE!

-// Callback function header
+// MQTT callback function header
 void mqttCallback(char* topic, byte* payload, unsigned int length);

 //MQTT initialization


블링커 모듈 수정

블링커 모듈 수정

디지털포텐셔미터의 범위 설정, 중복된 코드 정리

--- BlinkerModule/BlinkerModule.ino
+++ BlinkerModule/BlinkerModule.ino
@@ -18,17 +18,18 @@
 #define MICROSECONDS  1000000L

 const bool isMicrosecond  = true;
+const bool isFiltering    = true;
 const bool isDebugging    = true;
-const bool isFiltering    = true;
+
+const float inputResolution   = 1024;
+const float maxBlinkFrequency = 30;
+const float minDigipotLevel   = 115;
+const float maxDigipotLevel   = 255;
+const float ledDutyCycle      = 0.5;

 const double samplingFrequency = 1000;
 const double minCutoff  = 1.0;
 const double beta       = 0.007;
-
-const float maxBlinkFrequency = 30;
-const float maxDigipotLevel   = 256;
-const float ledDutyCycle      = 0.5;
-
 OneEuroFilter channel1(samplingFrequency, minCutoff, beta);
 OneEuroFilter channel2(samplingFrequency, minCutoff, beta);
 OneEuroFilter channel3(samplingFrequency, minCutoff, beta);
@@ -79,51 +80,39 @@
     short filter1;
     short filter2;
     short filter3;
+    short digipotLevel;

     if (isFiltering) {
       filter1 = round(channel1.filter(input1));
       filter2 = round(channel2.filter(input2));
       filter3 = round(channel3.filter(input3));
-
-      volume1 = round(filter1 * (maxBlinkFrequency / 1024.0));
-      volume2 = round(filter2 * (maxBlinkFrequency / 1024.0));
-      segment[0] = volume1 / 10;
-      segment[1] = volume1 % 10;
-      segment[2] = volume2 / 10;
-      segment[3] = volume2 % 10;
-
-      short digipotLevel = round(filter3 * (maxDigipotLevel / 1024.0));
-      if (volume3 != digipotLevel) {
-        volume3 = digipotLevel;
-        digitalWrite(POT_SELECT, LOW);
-        shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, B00000000);
-        shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, volume3);
-        digitalWrite(POT_SELECT, HIGH);
-        digitalWrite(POT_SELECT, LOW);
-        shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, B00010000);
-        shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, volume3);
-        digitalWrite(POT_SELECT, HIGH);
-      }
+      volume1 = round(filter1 * (maxBlinkFrequency / inputResolution));
+      volume2 = round(filter2 * (maxBlinkFrequency / inputResolution));
+      digipotLevel = round(filter3 * ((maxDigipotLevel - minDigipotLevel) / inputResolution) + minDigipotLevel);
     } else {
-      volume1 = round(input1 * (maxBlinkFrequency / 1024.0));
-      volume2 = round(input2 * (maxBlinkFrequency / 1024.0));
-      segment[0] = volume1 / 10;
-      segment[1] = volume1 % 10;
-      segment[2] = volume2 / 10;
-      segment[3] = volume2 % 10;
-
-      short digipotLevel = round(input3 * (maxDigipotLevel / 1024.0));
-      if (volume3 != digipotLevel) {
-        volume3 = digipotLevel;
-        digitalWrite(POT_SELECT, LOW);
-        shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, B00000000);
-        shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, volume3);
-        digitalWrite(POT_SELECT, HIGH);
-        digitalWrite(POT_SELECT, LOW);
-        shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, B00010000);
-        shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, volume3);
-        digitalWrite(POT_SELECT, HIGH);
-      }
+      volume1 = round(input1 * (maxBlinkFrequency / inputResolution));
+      volume2 = round(input2 * (maxBlinkFrequency / inputResolution));
+      digipotLevel = round(input3 * ((maxDigipotLevel - minDigipotLevel) / inputResolution) + minDigipotLevel);
+    }
+
+    segment[0] = volume1 / 10;
+    segment[1] = volume1 % 10;
+    segment[2] = volume2 / 10;
+    segment[3] = volume2 % 10;
+
+    if (digipotLevel == minDigipotLevel) {
+      digipotLevel = 0;
+    }
+    if (digipotLevel != volume3) {
+      volume3 = digipotLevel;
+      digitalWrite(POT_SELECT, LOW);
+      shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, B00000000);
+      shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, volume3);
+      digitalWrite(POT_SELECT, HIGH);
+      digitalWrite(POT_SELECT, LOW);
+      shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, B00010000);
+      shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, volume3);
+      digitalWrite(POT_SELECT, HIGH);
     }

     if (isDebugging) {


updated Sat 09/02/2017 14:59:50.33

updated Sat 09/02/2017 14:59:50.33

--- rtc-relay-static.ino
+++ rtc-relay-static.ino
@@ -41,7 +41,7 @@
 const int buttonPin = A2;

 //Set the time zone using the time zones listed in constants.h.
-//You'll have to manually switch the device from standard time to daylight
+//You'll have to manually switch the device from standard time to daylight
 //time during the summer if you live in an area that observes daylight time.
 const int timeZone = EST;

@@ -62,10 +62,10 @@
 // Turn the relay on at 5:30 AM, turn the relay off at 7:00 AM.
 // {530, 700}
 int slots[NUMSLOTS][2] = {
-  { 600, 800 },
-  {2000, 2300}
-  //BE SURE TO UPDATE THE NUMSLOTS CONSTANT IF YOU ADD/REMOVE
-  //ROWS FROM THIS ARRAY
+    {600, 800},
+    {2000, 2300}
+    //BE SURE TO UPDATE THE NUMSLOTS CONSTANT IF YOU ADD/REMOVE
+    //ROWS FROM THIS ARRAY
 };
 //============================================================

@@ -114,9 +114,10 @@
 // NTP time stamp is in the first 48 bytes of the message
 const int NTP_PACKET_SIZE = 48;
 //buffer to hold incoming and outgoing packets
-byte packetBuffer[ NTP_PACKET_SIZE];
-
-void setup() {
+byte packetBuffer[NTP_PACKET_SIZE];
+
+void setup()
+{

   //Initialize serial
   Serial.begin(9600);
@@ -142,44 +143,53 @@
   Serial.println("\nChecking software configuration");

   // Make sure our slot array is populated with valid times
-  for (int i = 0; i < NUMSLOTS; i++) {
+  for (int i = 0; i < NUMSLOTS; i++)
+  {
     //Get our time values
     int onTime = slots[i][0];
     int offTime = slots[i][1];

     // Is onTime valid?
-    if (!isValidTime(onTime)) {
+    if (!isValidTime(onTime))
+    {
       //That won't work, so display an error
       Serial.print(SLOTERRORSTR);
       Serial.println(onTime);
-      while (true);
+      while (true)
+        ;
     }

     // Is offTime valid?
-    if (!isValidTime(offTime)) {
+    if (!isValidTime(offTime))
+    {
       //That won't work, so display an error
       Serial.print(SLOTERRORSTR);
       Serial.println(offTime);
-      while (true);
+      while (true)
+        ;
     }

     //Are onTime and offTime the same?
-    if (onTime == offTime) {
+    if (onTime == offTime)
+    {
       //That won't work, so display an error
       Serial.print(SLOTERRORSTR);
       Serial.print("OnTime and OffTime cannot have the same value; slot #");
       Serial.println(i);
-      while (true);
+      while (true)
+        ;
     }

     // Is onTime AFTER offTime?
-    if ( onTime > offTime) {
+    if (onTime > offTime)
+    {
       //That won't work, so display an error
       Serial.print(SLOTERRORSTR);
       Serial.print("offTime preceeds onTime in slot #");
       Serial.println(i);
       // and hop into an infinite loop
-      while (true);
+      while (true)
+        ;
     }
   }

@@ -187,11 +197,13 @@
   //Assumes your SSID has a password
   //Change to the following if you don't have/need a SSID password
   //if (wifi_ssid == blankStr) {
-  if (wifi_ssid == BLANKSTR || wifi_pass == BLANKSTR) {
+  if (wifi_ssid == BLANKSTR || wifi_pass == BLANKSTR)
+  {
     //No? then there's nothing we can do
     Serial.println("One or more required Wi-Fi settings are empty, check the wifi-config.h file.");
     //loop forever
-    while (true);
+    while (true)
+      ;
   }

   //==================================================
@@ -199,27 +211,34 @@
   //==================================================
   Serial.println("Checking hardware");
   // check for the presence of the shield:
-  if (WiFi.status() == WL_NO_SHIELD) {
+  if (WiFi.status() == WL_NO_SHIELD)
+  {
     Serial.println("Wi-Fi shield not found");
     //loop forever
-    while (true);
-  }
-
-  if (! rtc.begin()) {
+    while (true)
+      ;
+  }
+
+  if (!rtc.begin())
+  {
     Serial.println("RTC board not found");
     //loop forever
-    while (true);
+    while (true)
+      ;
   }

   //Has the RTC board been initialized?
-  if (! rtc.initialized()) {
+  if (!rtc.initialized())
+  {
     //RTC hasn't been initialized, so it has no time/date value
     Serial.println("RTC is not initialized");
     //The following line sets the RTC to the date & time this sketch was compiled
     //This assumes initializing the RTC immediately after compile, which you would
     //do when you flash the firmware on the device.
     rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
-  } else {
+  }
+  else
+  {
     Serial.println("RTC is initialized");
   }

@@ -227,7 +246,8 @@
   // Connect to the network
   //==================================================
   // attempt to connect to the Wi-Fi network:
-  while (status != WL_CONNECTED) {
+  while (status != WL_CONNECTED)
+  {
     Serial.print("Connecting to ");
     Serial.println(ssid);
     // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
@@ -248,7 +268,8 @@
   //Set the lastMin variable to one minute before now
   lastMin = rtc.now().minute() - 1;
   //if we went into negative numbers (because the minute was 0)
-  if (lastMin < 0) {
+  if (lastMin < 0)
+  {
     lastMin = 59;
   }

@@ -256,15 +277,16 @@
   flashxTimes(2);

   //we just started, are we supposed to have the relay on at this time?
-  if (isInOnPeriod()) {
+  if (isInOnPeriod())
+  {
     //turn on the relay
     Serial.println("\nWhoops, we're supposed to be on!");
     setRelay(true);
   }
-
-}
-
-void loop() {
+}
+
+void loop()
+{

   //Variable used to store button status as its read
   int buttonState;
@@ -272,19 +294,25 @@
   //Read button state (pressed or not pressed?)
   buttonState = digitalRead(buttonPin);
   //If button pressed...
-  if (buttonState == LOW) {
+  if (buttonState == LOW)
+  {
     //Serial.println("Detected button press");
-    if (!buttonPushed) {
+    if (!buttonPushed)
+    {
       //Serial.println("Unique button press");
       //toggle the relay
       toggleRelay();
-    } else {
+    }
+    else
+    {
       //Serial.println("Skipping, button is still pushed");
     }
     //then reset our flag so it doesn't execute again
     //until the program reads that the button ISN'T pushed
     buttonPushed = true;
-  } else {
+  }
+  else
+  {
     //the button isn't pressed...
     //first, reset the buttonPushed flag, indicating that the button isn't pushed
     //this time through the loop
@@ -295,32 +323,40 @@
     //Get the current minute
     currentMin = currentTime.minute();
     //Has the minute changed?
-    if (currentMin != lastMin) {
+    if (currentMin != lastMin)
+    {
       Serial.println("Minute mark");
       //Yes? Then do something, or at least check to see if
       //we're supposed to do something.
       //Get the current time in 24 hour format
       int theTime = getTime24();
       //Loop through our array
-      for (int i = 0; i < NUMSLOTS; i++) {
+      for (int i = 0; i < NUMSLOTS; i++)
+      {
         //Get the on and off times
         int onTime = slots[i][0];
         int offTime = slots[i][1];
         //Should we be turning the relay on?
-        if (theTime == onTime) {
+        if (theTime == onTime)
+        {
           //Then turn it on
           setRelay(true);
-        } else {
+        }
+        else
+        {
           //Should we be turning the relay off?
-          if (theTime == offTime) {
+          if (theTime == offTime)
+          {
             //Then turn it off
             setRelay(false);
           }
         } //if
-      } //for
+      }   //for
       //Set the last minute pointer to the current minute.
       lastMin = currentMin;
-    } else {
+    }
+    else
+    {
       // The minute hasn't changed, so skip
       //Serial.println("Skipping");
     }
@@ -328,29 +364,32 @@

   //Wait approximately for interLoopDelay miliseconds before doing it all again
   delay(INTERLOOPDELAY);
-
-}
-
-int getTime24() {
+}
+
+int getTime24()
+{
   // Return the current time as an integer value in 24 hour format
   DateTime theTime = rtc.now();
   return (theTime.hour() * 100) + theTime.minute();
 }

-bool isValidTime(int timeVal) {
+bool isValidTime(int timeVal)
+{
   //Make sure the time value is between 0 and 2359 with
   // no minute value greater than 59
   return ((timeVal > -1) && (timeVal < 2360) && (timeVal % 100 < 60));
 }

-
-bool isInOnPeriod() {
+bool isInOnPeriod()
+{
   //Loop through the active slots array to see if the relay is
   //supposed to be on. This assumes the device just powered on
   //and it doesn't know whether it's supposed to be on or not.
   int timeVal = getTime24();
-  for (int i = 0; i < NUMSLOTS; i++) {
-    if ((timeVal > slots[i][0] ) && (timeVal < slots[i][1])) {
+  for (int i = 0; i < NUMSLOTS; i++)
+  {
+    if ((timeVal > slots[i][0]) && (timeVal < slots[i][1]))
+    {
       //yep, we're supposed to be on
       return true;
     }
@@ -358,29 +397,36 @@
   return false;
 }

-void flashxTimes(int numTimes) {
+void flashxTimes(int numTimes)
+{
   //Cycle the relay numtimes times.
   //Assumes we're starting with the relay off
   //Do it twice for each loop, on, and off.
   int loopEnd = numTimes * 2;
-  for (int i = 1; i <= loopEnd; i++) {
+  for (int i = 1; i <= loopEnd; i++)
+  {
     toggleRelay();
     delay(250);
   }
 }

-void toggleRelay() {
+void toggleRelay()
+{
   //Flips the relay from on to off or off to on
   setRelay(!relayStatus);
 }

-void setRelay(bool status) {
+void setRelay(bool status)
+{
   //Set the relay to a specific status (on=true/off=false)
   Serial.print("Relay: ");
-  if (status) {
+  if (status)
+  {
     Serial.println("ON");
     analogWrite(outputPin, MAXOUTPUT);
-  } else {
+  }
+  else
+  {
     Serial.println("OFF");
     analogWrite(outputPin, MINOUTPUT);
   }
@@ -389,7 +435,8 @@
   relayStatus = status;
 }

-void printWifiStatus() {
+void printWifiStatus()
+{
   // print the SSID of the network you're attached to:
   Serial.print("SSID: ");
   Serial.println(WiFi.SSID());
@@ -407,20 +454,21 @@
 }

 // send an NTP request to the time server
-void sendNTPpacket(char* address) {
+void sendNTPpacket(char *address)
+{
   // set all bytes in the buffer to 0
   memset(packetBuffer, 0, NTP_PACKET_SIZE);
   // Initialize values needed to form NTP request
   // (see URL above for details on the packets)
-  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
-  packetBuffer[1] = 0;     // Stratum, or type of clock
-  packetBuffer[2] = 6;     // Polling Interval
-  packetBuffer[3] = 0xEC;  // Peer Clock Precision
+  packetBuffer[0] = 0b11100011; // LI, Version, Mode
+  packetBuffer[1] = 0;          // Stratum, or type of clock
+  packetBuffer[2] = 6;          // Polling Interval
+  packetBuffer[3] = 0xEC;       // Peer Clock Precision
   // 8 bytes of zero for Root Delay & Root Dispersion
-  packetBuffer[12]  = 49;
-  packetBuffer[13]  = 0x4E;
-  packetBuffer[14]  = 49;
-  packetBuffer[15]  = 52;
+  packetBuffer[12] = 49;
+  packetBuffer[13] = 0x4E;
+  packetBuffer[14] = 49;
+  packetBuffer[15] = 52;
   // all NTP fields have been given values, now
   // you can send a packet requesting a timestamp:
   Udp.beginPacket(address, 123); //NTP requests are to port 123
@@ -428,19 +476,23 @@
   Udp.endPacket();
 }

-time_t getNTPTime() {
-  while (Udp.parsePacket() > 0) ; // discard any previously received packets
+time_t getNTPTime()
+{
+  while (Udp.parsePacket() > 0)
+    ; // discard any previously received packets
   Serial.println("Sending NTP Request");
   sendNTPpacket(timeServer);
   uint32_t beginWait = millis();
-  while (millis() - beginWait < 1500) {
+  while (millis() - beginWait < 1500)
+  {
     int size = Udp.parsePacket();
-    if (size >= NTP_PACKET_SIZE) {
+    if (size >= NTP_PACKET_SIZE)
+    {
       //We got a response
-      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
+      Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
       unsigned long secsSince1900, adjustedTime;
       // convert four bytes starting at location 40 to a long integer
-      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
+      secsSince1900 = (unsigned long)packetBuffer[40] << 24;
       secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
       secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
       secsSince1900 |= (unsigned long)packetBuffer[43];
@@ -459,4 +511,3 @@
   Serial.println("No NTP Response\n");
   return 0; // return 0 if unable to get the time
 }
-


Changed LED messages parser.

Changed LED messages parser.

--- TUGAB/examples/SerialComunication/SerialComunication.ino
+++ TUGAB/examples/SerialComunication/SerialComunication.ino
@@ -26,9 +26,9 @@
   pinMode(DISPLAY_DIGIT2, OUTPUT);

   // LEDs
-  pinMode(LED_GREEN, OUTPUT);
+  pinMode(LED_GREEN,  OUTPUT);
   pinMode(LED_YELLOW, OUTPUT);
-  pinMode(LED_RED, OUTPUT);
+  pinMode(LED_RED,    OUTPUT);

   // Buzzer
   pinMode(AUDIO_OUT_BUZZER, OUTPUT);
@@ -206,17 +206,15 @@
   {
     if(strstr(command.c_str(), "LED")) //Comparing word entered with word stored in program
     {
-      // If is valid.
-      state = true;
-    }
-    if(command[4] == '0' || command[4] == '1' || command[4] == '2')
-    {
-      if(command[5] == '0' || command[5] == '1')
-      {
-        // If is valid.
-        state = true;
-      }
-    }
+      if(command[4] == '1' || command[4] == '2' || command[4] == '3')
+      {
+        if(command[5] == '0' || command[5] == '1')
+        {
+          // If is valid.
+          state = true;
+        }
+      }
+    }
   }

   // Turn the buzzer OFF.
@@ -313,56 +311,56 @@
       int displayValue = command.substring(8, 10).toInt();
       SetIndicator(displayValue);
     }
-
+  }
+
   // LED command
-    if(strstr(command.c_str(), "LED")) //Comparing word entered with word stored in program
-    {
-      if(command[4] == '1')
-      {
-        if(command[5] == '0')
-        {
-          digitalWrite(LED_GREEN, LOW);
-        }
-        if(command[5] == '1')
-        {
-          digitalWrite(LED_GREEN, HIGH);
-        }
-      }
-      if(command[4] == '2')
-      {
-        if(command[5] == '0')
-        {
-          digitalWrite(LED_YELLOW, LOW);
-        }
-        if(command[5] == '1')
-        {
-          digitalWrite(LED_YELLOW, HIGH);
-        }
-      }
-      if(command[4] == '3')
-      {
-        if(command[5] == '0')
-        {
-          digitalWrite(LED_RED, LOW);
-        }
-        if(command[5] == '1')
-        {
-          digitalWrite(LED_RED, HIGH);
-        }
-      }
-    }
-
-    // Turn the buzzer OFF.
-    if(command == "?BUZZER0\n")
-    {
-      Serial.println("Buzzer 0");
-    }
-
-    // Turn the buzzer ON.
-    if(command == "?BUZZER1\n")
-    {
-      Serial.println("Buzzer 1");
-    }
+  if(strstr(command.c_str(), "LED")) //Comparing word entered with word stored in program
+  {
+    if(command[4] == '1')
+    {
+      if(command[5] == '0')
+      {
+        digitalWrite(LED_GREEN, LOW);
+      }
+      if(command[5] == '1')
+      {
+        digitalWrite(LED_GREEN, HIGH);
+      }
+    }
+    if(command[4] == '2')
+    {
+      if(command[5] == '0')
+      {
+        digitalWrite(LED_YELLOW, LOW);
+      }
+      if(command[5] == '1')
+      {
+        digitalWrite(LED_YELLOW, HIGH);
+      }
+    }
+    if(command[4] == '3')
+    {
+      if(command[5] == '0')
+      {
+        digitalWrite(LED_RED, LOW);
+      }
+      if(command[5] == '1')
+      {
+        digitalWrite(LED_RED, HIGH);
+      }
+    }
+  }
+
+  // Turn the buzzer OFF.
+  if(command == "?BUZZER0\n")
+  {
+    Serial.println("#BUZ:0");
+  }
+
+  // Turn the buzzer ON.
+  if(command == "?BUZZER1\n")
+  {
+    Serial.println("#BUZ:1");
   }

   // Microphone sensor command
@@ -444,4 +442,4 @@
   Serial.println("DEP : AIUT");
   Serial.println("NAME: Arduino AIUTshield v0.1");
   Serial.println("DATE: 02.12.2014y.");
-}
+}


Whitespace corrections

Whitespace corrections

--- Receiver_test/Receiver_test.ino
+++ Receiver_test/Receiver_test.ino
@@ -1,4 +1,3 @@
-
 #include <SPI.h>
 #include "nRF24L01.h"
 #include "RF24.h"
@@ -35,17 +34,17 @@
 void setup(void){

   Serial.begin(57600);
-//  printf_begin();
-
+  //  printf_begin();
+
   radio.begin();
   radio.setAutoAck(0);
-//  radio.printDetails();
+  //  radio.printDetails();
   radio.openReadingPipe(1,pipe);
   radio.startListening();

   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
-
+
   timeout = millis() + 10000;

 }
@@ -54,91 +53,91 @@
   bool done;
   byte n;
   byte i;
-
+
   strip.setPixelColor(0, strip.Color(255,0,0));
   strip.setPixelColor(1, strip.Color(0,255,0));
   strip.setPixelColor(2, strip.Color(0,0,255));
   strip.setPixelColor(3, strip.Color(0,255,255));
   strip.show();
-
+
   while(1){
     done = false;
     switch (pattern){

       case 0:  // display r, g and b from master
-      while(!done){
-        red = msg[14];
-        green = msg[15];
-        blue = msg[16];
-        strip.setPixelColor(0, strip.Color(red, green, blue));
-        strip.setPixelColor(1, strip.Color(red, green, blue));
-        strip.setPixelColor(2, strip.Color(red, green, blue));
-        strip.setPixelColor(3, strip.Color(red, green, blue));
-        strip.show();
-        //delay(rate);
-        if(check_radio()){done = process_msg();}
-        if (millis() > timeout){
-          timeout = millis()+60000;
-          pattern = 2;
-          done = true;
-        }
-      }
-      break;
-
-     case 1:  // color rotating around circle
-      n = (addr-1) * 16;
-      while (!done){
-        if (n<16){
-          strip.setPixelColor(0, strip.Color(255,0,0));
-          strip.setPixelColor(1, strip.Color(255,0,0));
-          strip.setPixelColor(2, strip.Color(255,0,0));
-          strip.setPixelColor(3, strip.Color(255,0,0));
-          strip.show();
+        while(!done){
+          red = msg[14];
+          green = msg[15];
+          blue = msg[16];
+          strip.setPixelColor(0, strip.Color(red, green, blue));
+          strip.setPixelColor(1, strip.Color(red, green, blue));
+          strip.setPixelColor(2, strip.Color(red, green, blue));
+          strip.setPixelColor(3, strip.Color(red, green, blue));
+          strip.show();
+          //delay(rate);
+          if(check_radio()){done = process_msg();}
+          if (millis() > timeout){
+            timeout = millis()+60000;
+            pattern = 2;
+            done = true;
+          }
         }
-        else
-        {
-          strip.setPixelColor(0, strip.Color(0,0,255));
-          strip.setPixelColor(1, strip.Color(0,0,255));
-          strip.setPixelColor(2, strip.Color(0,0,255));
-          strip.setPixelColor(3, strip.Color(0,0,255));
-          strip.show();
+        break;
+
+      case 1:  // color rotating around circle
+        n = (addr-1) * 16;
+        while (!done){
+          if (n<16){
+            strip.setPixelColor(0, strip.Color(255,0,0));
+            strip.setPixelColor(1, strip.Color(255,0,0));
+            strip.setPixelColor(2, strip.Color(255,0,0));
+            strip.setPixelColor(3, strip.Color(255,0,0));
+            strip.show();
+          }
+          else
+          {
+            strip.setPixelColor(0, strip.Color(0,0,255));
+            strip.setPixelColor(1, strip.Color(0,0,255));
+            strip.setPixelColor(2, strip.Color(0,0,255));
+            strip.setPixelColor(3, strip.Color(0,0,255));
+            strip.show();
+          }
+          n++;
+          if(check_radio()){done = process_msg();}
+          if (millis() > timeout){
+            timeout = millis()+60000;
+            pattern = 2;
+            done = true;
+          }
+          delay(rate);
         }
-        n++;
-        if(check_radio()){done = process_msg();}
-        if (millis() > timeout){
-          timeout = millis()+60000;
-          pattern = 2;
-          done = true;
-        }
-        delay(rate);
-      }
-      break;
-
-     case 2:  // rainbow rotating around
-      n = (addr-1) * 16;
-      while (!done){
+        break;
+
+      case 2:  // rainbow rotating around
+        n = (addr-1) * 16;
+        while (!done){
           for(i=0; i< strip.numPixels(); i++) {
             strip.setPixelColor(i, Wheel((64 + n) & 255));
           }
           strip.show();
           delay(rate);
-        n++;
-        if(check_radio()){done = process_msg();}
-        if (millis() > timeout){
-          timeout = millis()+60000;
-          pattern = 2;
-          done = true;
-        }
-        delay(rate);
-      }
-      break;
-
-     default:
-      pattern = 2;
-    }
-
-  }
-
+          n++;
+          if(check_radio()){done = process_msg();}
+          if (millis() > timeout){
+            timeout = millis()+60000;
+            pattern = 2;
+            done = true;
+          }
+          delay(rate);
+        }
+        break;
+
+      default:
+        pattern = 2;
+    }
+
+  }
+
 }

 // Input a value 0 to 255 to get a color value.
@@ -146,33 +145,33 @@
 uint32_t Wheel(byte WheelPos) {
   WheelPos = 255 - WheelPos;
   if(WheelPos < 85) {
-   return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
+    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
   } else if(WheelPos < 170) {
     WheelPos -= 85;
-   return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
+    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
   } else {
-   WheelPos -= 170;
-   return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
+    WheelPos -= 170;
+    return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
   }
 }

 bool check_radio(void){
   if (radio.available()){
-   timeout = millis() + 10000;
-   if (msg[1] == 0){
-     return true;
-   }
-   else if (msg[1] == addr){
-     return true;
-   }
-   else
-   {
-     return false;
-   }
+    timeout = millis() + 10000;
+    if (msg[1] == 0){
+      return true;
+    }
+    else if (msg[1] == addr){
+      return true;
+    }
+    else
+    {
+      return false;
+    }
   }
   else
   {
-    return false;
+    return false;
   }
 }

@@ -182,17 +181,17 @@
   switch (cmnd){
     case 'P':    // set pattern number
       if (msg[3] != pattern){  // new pattern
-       pattern = msg[3];
-       return true;
+        pattern = msg[3];
+        return true;
       }
       else{
         return false;
       }
-    break;
+      break;
     case 'S':    // set speed of the pattern
       rate = msg[3];
       return false;
-    break;
+      break;
     default:
       return false;
   }


Filter out erroneous static-related rain triggers

--- roof_sensor_serial/roof_sensor_serial.ino
+++ roof_sensor_serial/roof_sensor_serial.ino
@@ -40,7 +40,7 @@

 DHT dht(TEMP_PIN_1, TEMP_PIN_1_TYPE);    // Declare the DHT sensor

-// setup code, runs once upon boot:
+// Setup code, runs once upon boot:
 void setup() {
   pinMode(LED_PIN, OUTPUT);        // set led pin as output
   pinMode(WIND_PIN, INPUT_PULLUP); // enable pullup for wind sensor
@@ -53,20 +53,20 @@
   attachInterrupt(digitalPinToInterrupt(RAIN_PIN), rainInterrupt, FALLING); // attach interrupt handler
 }

-// main code, runs forever:
+// Main code, runs forever:
 void loop() {
   if (millis() - lastmillis >= 1000) {    // if it's been more than 1000ms:
     noInterrupts();                         // disable interrupts when calculating
     Serial.print(TEXT_WIND_UPDATE);         // print header
     Serial.println(getWind(), DEC);         // print the rpm to serial

-    if (tempCounter > TEMP_PIN_1_DELAY) { // if we've ran this loop 10 times
+    if (tempCounter > TEMP_PIN_1_DELAY) { // if we've ran this loop 30 times
       updateTemp();                         // then get us temp data
     } else {
       tempCounter++;                        // otherwise, increment loop count
     }

-    if (batteryCounter > BATTERY_DELAY) { // if we've ran this loop 10 times
+    if (batteryCounter > BATTERY_DELAY) { // if we've ran this loop 120 times
       updateVoltage();                      // then get us temp data
     } else {
       batteryCounter++;                     // otherwise, increment loop count
@@ -77,7 +77,7 @@
   }
 }

-// when wind gauge is triggered
+// When wind gauge is triggered
 void windInterrupt() {
   if (micros() - windDebounce > WIND_DEBOUNCE_TIME) { // if we're not within the debounce time
     half_revolutions++;              // increment the half revolutions
@@ -85,11 +85,22 @@
   }
 }

-// when rain gauge is triggered
+// When rain gauge is triggered
+// This also checks for and rules out strange static flip readings
 void rainInterrupt() {
-  if (millis() - rainDebounce > RAIN_DEBOUNCE_TIME) { // if we're not within the debounce time
-    Serial.println(TEXT_RAIN_FLIP);     // then output that we flipped.
-    rainDebounce = millis();            // update the last debounce time
+  int triggers = 0;
+  for (int i=0;i<10;i++) {
+    if (digitalRead(RAIN_PIN) == 0)
+      triggers++;
+    delay(10);
+  }
+
+  //Only consider it as tripped if at least 90% of the 100ms after trip is also tripped
+  if (triggers > 8) {
+    if (millis() - rainDebounce > RAIN_DEBOUNCE_TIME) { // if we're not within the debounce time
+      Serial.println(TEXT_RAIN_FLIP);     // then output that we flipped.
+      rainDebounce = millis();            // update the last debounce time
+    }
   }
 }


added offset handling for reading depending on dormitory

--- Margoulineur2000.ino
+++ Margoulineur2000.ino
@@ -295,16 +295,9 @@
             nfc.PrintHexChar(nfc_handler.data, 16);
             if (!mode)
             {
-                if (dormitory == 3)
-                {
-                    if (nfc_handler.currentblock == 24)
-                        nfc_handler.currentBalance = (nfc_handler.data[6] * 256) + nfc_handler.data[7];
-                }
-                else if (dormitory == 4)
-                {
-                    if (nfc_handler.currentblock == 24)
-                        nfc_handler.currentBalance = (nfc_handler.data[0] * 256) + nfc_handler.data[1];
-                }
+                nfc_handler.offset = dormitory == 4 ? 1 : 7;
+                if (nfc_handler.currentblock == 24)
+                    nfc_handler.currentBalance = (nfc_handler.data[nfc_handler.offset - 1] * 256) + nfc_handler.data[nfc_handler.offset];
             }
             else
             {


## minimum.ino * Add #define to enable setting the time from a Time String and Date String

--- examples/minimum/minimum.ino
+++ examples/minimum/minimum.ino
@@ -8,6 +8,7 @@
                   GND 4|    |5 PB0
                        +----+
 */
+#define REQUIRE_TIMEDATESTRING 1
 #include <TimeDateTools.h> // include before wwvb.h AND/OR ATtinyGPS.h
 #include <wwvb.h> // include before ATtinyGPS.h
 wwvb wwvb_tx;


Cure double interrupt on PIR

Cure double interrupt on PIR

--- examples/RF12/roomNode/roomNode.ino
+++ examples/RF12/roomNode/roomNode.ino
@@ -101,7 +101,7 @@
             byte f = value;
             if (lastOn > 0)
                 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
-                    if (millis() - lastOn < 1000 * PIR_HOLD_TIME)
+                    if (millis() - lastOn < (uint32_t)(1000 * PIR_HOLD_TIME))
                         f = 1;
                 }
             return f;


Some function comment consistency.

Some function comment consistency.

--- src/homie-sonoff-touch.ino
+++ src/homie-sonoff-touch.ino
@@ -35,8 +35,8 @@
 // Milliseconds to wait per cycle for a held command.
 const int waitInterval = 100;

-// EEPROM structure
 struct EEpromDataStruct {
+  // EEPROM structure
   int keepAliveTimeOut; // 0 - disabled, keepalive time - seconds
   bool initialState;  // Initial state (just after boot - homie independet)
   int watchDogTimeOut; // 0 - disabled, watchdog time limit - seconds
@@ -53,11 +53,8 @@
 HomieNode keepAliveNode("keepalive", "keepalive");
 HomieNode watchDogNode("watchdog", "Watchdog mode");

-/*
- * Recevied tick message for watchdog
- */
-bool watchdogTickHandler(const HomieRange& range, const String& value)
-{
+bool watchdogTickHandler(const HomieRange& range, const String& value) {
+  // Recevied tick message for watchdog
   if (value == "0")
   {
     watchDogCounterStart = 0;
@@ -66,11 +63,9 @@
   }
   return true;
 }
-/*
- * Received watchdog timeout value
- */
-bool watchdogTimeOutHandler(const HomieRange& range, const String& value)
-{
+
+bool watchdogTimeOutHandler(const HomieRange& range, const String& value) {
+  // Received watchdog timeout value
   int oldValue = EEpromData.watchDogTimeOut;
   if (value.toInt() > 15)
   {
@@ -89,11 +84,9 @@
     EEPROM.commit();
   }
 }
-/*
- * Initial mode handler
- */
-bool relayInitModeHandler(HomieRange range, String value)
-{
+
+bool relayInitModeHandler(HomieRange range, String value) {
+  // Initial mode handler
   int oldValue = EEpromData.initialState;
   if (value.toInt() == 1 or value=="ON")
   {
@@ -111,11 +104,8 @@
   return true;
 }

-/*
- * Homie setup handler
- */
-void setupHandler()
-{
+void setupHandler() {
+  // Homie setup handler
   HomieRange emptyRange;
   if (EEpromData.initialState) {
     RelayHandler(emptyRange, "ON");
@@ -136,11 +126,9 @@
 }

 bool RelayHandler(const HomieRange& range, const String& value) {
-  /*
-  Here we handle incoming requests to set the state of the relay
-  Set the RELAY_PIN to the appropriate level, and additionally set the
-  state on the relayState topic.
-  */
+  // Here we handle incoming requests to set the state of the relay
+  // Set the RELAY_PIN to the appropriate level, and additionally set the
+  // state on the relayState topic.
   if (value == "ON") {
     digitalWrite(PIN_RELAY, HIGH);
     relayNode.setProperty("relayState").send("ON");
@@ -157,20 +145,14 @@
   return true;
 }

-/*
- * Keepliave tick handler
- */
-bool keepAliveTickHandler(HomieRange range, String value)
-{
+bool keepAliveTickHandler(HomieRange range, String value) {
+  // Keepalive tick handler
   keepAliveReceived=millis();
   return true;
 }

-/*
- * Keepalive message handler
- */
-bool keepAliveTimeOutHandler(HomieRange range, String value)
-{
+bool keepAliveTimeOutHandler(HomieRange range, String value) {
+  // Keepalive message handler
   int oldValue = EEpromData.keepAliveTimeOut;
   if (value.toInt() > 0)
   {
@@ -271,10 +253,8 @@

   }

-/*
- * Homie event handler
- */
 void onHomieEvent(const HomieEvent& event) {
+  // Homie event handler
   switch(event.type) {
     case HomieEventType::CONFIGURATION_MODE: // Default eeprom data in configuration mode
       digitalWrite(PIN_RELAY, LOW);


More references

More references

--- arduino/src/stolenmeeting.ino
+++ arduino/src/stolenmeeting.ino
@@ -1,4 +1,8 @@
 // http://archive.wired.com/geekdad/2012/09/using-motion-detectors-with-an-arduino/
+// https://github.com/prampec/arduino-softtimer/blob/wiki/WhyHow.md
+// https://nurdspace.nl/ESP8266
+// http://contractorwolf.com/esp8266-wifi-arduino-micro
+// http://www.instructables.com/id/ESP8266-Wifi-Temperature-Logger/

 #include <AltSoftSerial.h>
 #include <SoftTimer.h>
@@ -30,7 +34,7 @@
     while(!connectWiFi()) {
       Serial.println("Retrying connect to network");
     }
-
+
     digitalWrite(light, HIGH);

     SoftTimer.add(&blinkTask);


fixed merge issue of private memember compass

--- arduino_motor/mains/mains.ino
+++ arduino_motor/mains/mains.ino
@@ -17,7 +17,6 @@
   motorShield.init();

   //PololuWheelEncoders::init(Pin::M1_ENCODER_A, Pin::M1_ENCODER_B, Pin::M2_ENCODER_A, Pin::M2_ENCODER_B); // 4 pins required
-  errorCumulator->compass->compassSetup();
   //servo_ir->init();
   errorCumulator->init();


turn off debug ifdef

turn off debug ifdef

--- esp8266_160220_BYOP.ino
+++ esp8266_160220_BYOP.ino
@@ -7,6 +7,7 @@

 /*
  * v0.20 2016 Feb. 23
+ *  - turn off debug ifdef
  *  - impl proc_post()
  *  - add [POST_IDX_e]
  *  - impl proc_post()
@@ -132,13 +133,13 @@
     return false;
   }

-#if 1
+#if 0
   int len = nickname.length();
   String msg130 = String(len);
   debug_outputDebugString("proc_hello", "line131 > " + msg130);
 #endif

-#if 1
+#if 0
   Test_MsgServer_setupDummyMessages();
 #endif


Tweaks to temp control and safeties

Tweaks to temp control and safeties

Safety is not allowing the HVAC to run if the setpoint or controlling temp is 0 (for whatever reason).

--- hvacMonitor.ino
+++ hvacMonitor.ino
@@ -114,9 +114,6 @@
   digitalWrite(heatingRelay, HIGH);
   digitalWrite(fanRelay, HIGH);
   digitalWrite(bypassRelay, HIGH);
-  Blynk.setProperty(V39, "label", "Setpoint");
-  Blynk.setProperty(V39, "color", "#27292D");  // Gray that blends into Blynk tool background rending invisible.
-  Blynk.setProperty(V40, "color", "#696969");

   // START OTA ROUTINE
   ArduinoOTA.setHostname("HVAC-WeMosD1mini");     // Name that is displayed in the Arduino IDE.
@@ -160,8 +157,10 @@
   timer.setTimeout(100, vsync1);              // Syncs back vPins to survive hardware reset.
   timer.setTimeout(2000, vsync2);             // Syncs back vPins to survive hardware reset.
   timer.setTimeout(4000, vsync3);             // Syncs back vPins to survive hardware reset.
+  timer.setTimeout(8000, controlReset);
   timer.setInterval(30000L, tempUpdater);      // When bypass on, this evaluates controlling space against setpoint.
   timer.setInterval(30000L, tempControl);     // Temps (controlling space) that can control HVAC are synced.
+  timer.setInterval(1000L, tempControlSafety);

 }

@@ -179,57 +178,72 @@
     // **************************************** IN ALL CASES BELOW: LOW == ON/CLOSED, HIGH == OFF/OPEN
     case 1: {                         // House t-stat controlling (bypass off)
         controlMode = 0;
+        controllingSpace = "";
         Blynk.setProperty(V39, "label", "Setpoint");
-        Blynk.setProperty(V39, "color", "#27292D");   // Blynk widget background gray
-        Blynk.setProperty(V40, "color", "#696969");   // DimGray
         digitalWrite(fanRelay, HIGH);
         digitalWrite(coolingRelay, HIGH);
         digitalWrite(heatingRelay, HIGH);
         digitalWrite(bypassRelay, HIGH);
+
+        terminal.println((millis() / 1000) + String(" House in Ctrl mode."));
+        terminal.flush();
+
         break;
       }
     case 2: {                         // House t-stat bypass (Blynk-controlling, but nothing running)
         controlMode = 0;
+        controllingSpace = "";
         Blynk.setProperty(V39, "label", "Setpoint");
-        Blynk.setProperty(V39, "color", "#27292D");   // Blynk widget background gray
-        Blynk.setProperty(V40, "color", "#FFFFFF");   // White
         digitalWrite(fanRelay, HIGH);
         digitalWrite(coolingRelay, HIGH);
         digitalWrite(heatingRelay, HIGH);
         digitalWrite(bypassRelay, LOW);
+
+        terminal.println((millis() / 1000) + String(" Bypass only mode."));
+        terminal.flush();
+
         break;
       }
     case 3: {                         // Manual fan (blower only)
         controlMode = 0;
+        controllingSpace = "";
         Blynk.setProperty(V39, "label", "Setpoint");
-        Blynk.setProperty(V39, "color", "#27292D");   // Blynk widget background gray
-        Blynk.setProperty(V40, "color", "#23C48E");   // Blynk green
         digitalWrite(fanRelay, LOW);
         digitalWrite(coolingRelay, HIGH);
         digitalWrite(heatingRelay, HIGH);
         digitalWrite(bypassRelay, LOW);
+
+        terminal.println((millis() / 1000) + String(" Manual fan mode."));
+        terminal.flush();
+
         break;
       }
     case 4: {                         // Manual cooling
         controlMode = 0;
+        controllingSpace = "";
         Blynk.setProperty(V39, "label", "Setpoint");
-        Blynk.setProperty(V39, "color", "#27292D");   // Blynk widget background gray
-        Blynk.setProperty(V40, "color", "#04C0F8");   // Blynk blue
         digitalWrite(fanRelay, HIGH);
         digitalWrite(coolingRelay, LOW);
         digitalWrite(heatingRelay, HIGH);
         digitalWrite(bypassRelay, LOW);
+
+        terminal.println((millis() / 1000) + String(" Manual cooling mode."));
+        terminal.flush();
+
         break;
       }
     case 5: {                         // Manual heating
         controlMode = 0;
+        controllingSpace = "";
         Blynk.setProperty(V39, "label", "Setpoint");
-        Blynk.setProperty(V39, "color", "#27292D");   // Blynk widget background gray
-        Blynk.setProperty(V40, "color", "#D3435C");   // Blynk red
         digitalWrite(fanRelay, HIGH);
         digitalWrite(coolingRelay, HIGH);
         digitalWrite(heatingRelay, LOW);
         digitalWrite(bypassRelay, LOW);
+
+        terminal.println((millis() / 1000) + String(" Manual heat mode."));
+        terminal.flush();
+
         break;
       }
     case 6: {                                         // Keaton-controlled cooling
@@ -237,27 +251,32 @@
         controllingSpace = "KK";                      // Here's the room that we're watching
         coolingMode = 1;                              // This sets the HVAC in correct mode and decides tstat logic
         controllingTemp = tempKK;
-        Blynk.setProperty(V39, "label", String("Setpoint - Controlled by KK (currently ") + tempKK + "F).");
-        Blynk.setProperty(V39, "color", "#04C0F8");   // Blynk blue
-        Blynk.setProperty(V40, "color", "#04C0F8");   // Blynk blue
+        Blynk.setProperty(V39, "label", String("Setpoint: ") + setpointTemp + ". Controlled by KK (currently " + tempKK + "F).");
         digitalWrite(fanRelay, HIGH);
         digitalWrite(coolingRelay, HIGH);
         digitalWrite(heatingRelay, HIGH);
         digitalWrite(bypassRelay, LOW);
+
+        terminal.println((millis() / 1000) + String(" KK cool mode."));
+        terminal.flush();
+
         break;
       }
     case 7: {                             // Keaton-controlled heating
+        Blynk.syncVirtual(V39);
         controlMode = 1;
         controllingSpace = "KK";
         coolingMode = 0;
         controllingTemp = tempKK;
-        Blynk.setProperty(V39, "label", String("Setpoint - Controlled by KK (currently ") + tempKK + "F).");
-        Blynk.setProperty(V39, "color", "#D3435C");
-        Blynk.setProperty(V40, "color", "#D3435C");
+        Blynk.setProperty(V39, "label", String("Setpoint: ") + setpointTemp + "F. Controlled by KK (currently " + tempKK + "F).");
         digitalWrite(fanRelay, HIGH);
         digitalWrite(coolingRelay, HIGH);
         digitalWrite(heatingRelay, HIGH);
         digitalWrite(bypassRelay, LOW);
+
+        terminal.println((millis() / 1000) + String(" KK heat mode."));
+        terminal.flush();
+
         break;
       }
     case 8: {                             // Liv-controlled cooling
@@ -265,13 +284,15 @@
         controllingSpace = "LK";
         coolingMode = 1;
         controllingTemp = tempLK;
-        Blynk.setProperty(V39, "label", String("Setpoint - Controlled by LK (currently ") + tempLK + "F).");
-        Blynk.setProperty(V39, "color", "#04C0F8");
-        Blynk.setProperty(V40, "color", "#04C0F8");
+        Blynk.setProperty(V39, "label", String("Setpoint: ") + setpointTemp + ". Controlled by LK (currently " + tempLK + "F).");
         digitalWrite(fanRelay, HIGH);
         digitalWrite(coolingRelay, HIGH);
         digitalWrite(heatingRelay, HIGH);
         digitalWrite(bypassRelay, LOW);
+
+        terminal.println((millis() / 1000) + String(" LK cool mode."));
+        terminal.flush();
+
         break;
       }
     case 9: {                             // Liv-controlled heating
@@ -279,24 +300,18 @@
         controllingSpace = "LK";
         coolingMode = 0;
         controllingTemp = tempLK;
-        Blynk.setProperty(V39, "label", String("Setpoint - Controlled by LK (currently ") + tempLK + "F).");
-        Blynk.setProperty(V39, "color", "#D3435C");
-        Blynk.setProperty(V40, "color", "#D3435C");
+        Blynk.setProperty(V39, "label", String("Setpoint: ") + setpointTemp + ". Controlled by LK (currently " + tempLK + "F).");
         digitalWrite(fanRelay, HIGH);
         digitalWrite(coolingRelay, HIGH);
         digitalWrite(heatingRelay, HIGH);
         digitalWrite(bypassRelay, LOW);
+
+        terminal.println((millis() / 1000) + String(" LK heat mode."));
+        terminal.flush();
+
         break;
       }
     default: {
-        controlMode = 0;
-        Blynk.setProperty(V39, "label", "Setpoint");
-        Blynk.setProperty(V39, "color", "#27292D");   // Blynk widget background gray
-        Blynk.setProperty(V40, "color", "#696969");   // DimGray
-        digitalWrite(fanRelay, HIGH);
-        digitalWrite(coolingRelay, HIGH);
-        digitalWrite(heatingRelay, HIGH);
-        digitalWrite(bypassRelay, HIGH);
         break;
       }
   }
@@ -304,26 +319,48 @@

 void tempControl() {

-  if (controlMode == 1)                            // If we're in bypass mode, proceed:
-  {
-
-    if (coolingMode == 0 && controllingTemp != 0 && controllingTemp < setpointTemp)       // If mode is heat and room falls equal or below the target temp...
+  if (controlMode == 1 && setpointTemp != 0 && controllingTemp != 0)     // If we're in bypass mode, and established setpoint and control temps, then proceed:
+  {
+
+    if (coolingMode == 0 && controllingTemp < setpointTemp)       // If mode is heat and room falls equal or below the target temp...
     {
       digitalWrite(heatingRelay, LOW);                            // turn on the heat. But when
-    }
-    else if (coolingMode == 0 && controllingTemp != 0 && controllingTemp >= (setpointTemp + controlSplit))   // If mode is heat and room is warmer then target temp...
+      terminal.println((millis() / 1000) + String(" SETPOINT: Heat relay closed."));
+      terminal.println(String("   SP:") + setpointTemp + " Ctrl:" + controllingTemp);
+      terminal.flush();
+    }
+    else if (coolingMode == 0 && controllingTemp >= (setpointTemp + controlSplit))   // If mode is heat and room is warmer then target temp...
     {
       digitalWrite(heatingRelay, HIGH);                           // everything is turned off.
-    }
-    else if (coolingMode == 1 && controllingTemp != 0 && controllingTemp > setpointTemp)  // If mode is cool and room rises equal or above the target temp...
+      terminal.println((millis() / 1000) + String(" SETPOINT: Heat relay open."));
+      terminal.println(String("   SP:") + setpointTemp + " Ctrl:" + controllingTemp);
+      terminal.flush();
+    }
+    else if (coolingMode == 1 && controllingTemp > setpointTemp)  // If mode is cool and room rises equal or above the target temp...
     {
       digitalWrite(coolingRelay, LOW);                            // turn on cooling. Then,
-    }
-    else if (coolingMode == 1 && controllingTemp != 0 && controllingTemp <= (setpointTemp - controlSplit))   // when mode is cool and room is cooler then target temp...
+      terminal.println((millis() / 1000) + String(" SETPOINT: Cool relay closed."));
+      terminal.println(String("   SP:") + setpointTemp + " Ctrl:" + controllingTemp);
+      terminal.flush();
+    }
+    else if (coolingMode == 1 && controllingTemp <= (setpointTemp - controlSplit))   // when mode is cool and room is cooler then target temp...
     {
       digitalWrite(coolingRelay, HIGH);                           // turn everything off.
-    }
-
+      terminal.println((millis() / 1000) + String(" SETPOINT: Heat relay opem."));
+      terminal.println(String("   SP:") + setpointTemp + " Ctrl:" + controllingTemp);
+      terminal.flush();
+    }
+
+  }
+}
+
+void tempControlSafety() {      // Safeties running every second
+  if  (digitalRead(blowerPin) == LOW && (setpointTemp == 0 || controllingTemp  == 0) )  // If HVAC is running and the setpoint or controlling temp are 0, then open relays. Control will be locked out until those temps are != 0.
+  {
+    digitalWrite(coolingRelay, HIGH);
+    digitalWrite(heatingRelay, HIGH);
+
+    Blynk.notify(hour() + String(":") + minute() + ":" + second() + " " + month() + "/" + day() + " ERROR: Ctrl attempted with no setpointTemp or controllingTemp");
   }
 }

@@ -334,12 +371,12 @@
   if (controllingSpace == "KK")
   {
     controllingTemp = tempKK;
-    Blynk.setProperty(V39, "label", String("Setpoint - Controlled by KK (currently ") + tempKK + "F)");
+    Blynk.setProperty(V39, "label", String("Setpoint: ") + setpointTemp + "F. Controlled by KK (currently " + tempKK + "F).");
   }
   else if (controllingSpace == "LK")
   {
     controllingTemp = tempLK;
-    Blynk.setProperty(V39, "label", String("Setpoint - Controlled by LK (currently ") + tempLK + "F)");
+    Blynk.setProperty(V39, "label", String("Setpoint: ") + setpointTemp + "F. Controlled by LK (currently " + tempLK + "F).");
   }
 }

@@ -355,7 +392,27 @@
 {
   setpointTemp = param.asInt();
 }
+
+void controlReset() {
+  controlMode = 0;
+  controllingSpace = "";
+  Blynk.setProperty(V39, "label", "Setpoint");
+  digitalWrite(fanRelay, HIGH);
+  digitalWrite(coolingRelay, HIGH);
+  digitalWrite(heatingRelay, HIGH);
+  digitalWrite(bypassRelay, HIGH);
+  Blynk.virtualWrite(V40, 1);
+
+  terminal.println((millis() / 1000) + String(" House in Ctrl mode."));
+  terminal.flush();
+}
 // ******************************************************** HVAC CTRL END **********************************************
+
+void vsync1()
+{
+  Blynk.syncVirtual(V16);    // currentStatus
+  Blynk.syncVirtual(V39);    // setpointTemp
+}

 void vsync2()
 {
@@ -369,12 +426,6 @@
   Blynk.syncVirtual(V11);     // currentFilterSec
 }

-void vsync1()
-{
-  Blynk.syncVirtual(V16);    // currentStatus
-  Blynk.syncVirtual(V38);    // heatingMode (kind of)
-}
-
 BLYNK_WRITE(V110)
 {
   hvacTodaysStartCount = param.asInt();
@@ -398,20 +449,6 @@
 BLYNK_WRITE(V16)
 {
   currentStatus = param.asStr();
-}
-
-BLYNK_WRITE(V38)
-{
-  String blah = param.asStr();
-
-  if (blah == "COOL")
-  {
-    heatingMode = FALSE;
-  }
-  else if (blah == "HEAT")
-  {
-    heatingMode = TRUE;
-  }
 }

 void phantSend() {
@@ -684,7 +721,6 @@
     resetTimeDate = currentTimeDate;
     Blynk.virtualWrite(16, currentStatus);
     Blynk.setProperty(V16, "label", String("Current Status:                    SYSTEM RESET at ") + resetTimeDate);
-    Blynk.setProperty(V16, "color", "#808080");
   }

   // Purpose: To keep the display showing a system reset state until the HVAC has turned on or off.
@@ -704,7 +740,6 @@
     currentStatus = String("HVAC OFF since ") + stopTimeDate;
     Blynk.setProperty(V0, "color", "#808080");
     Blynk.setProperty(V1, "color", "#808080");
-    Blynk.setProperty(V16, "color", "#808080");

     if ( (filterChangeHours - currentFilterHours ) <= 0 && changeFilterAlarm == FALSE) {
       Blynk.email(myEmail, "CHANGE A/C FILTER", "Change the A/C filter (20x25x1 1085 microparticle/MERV 11) and reset the timer.");
@@ -732,8 +767,6 @@
       Blynk.setProperty(V0, "color", "#ff0000");    // Return is RED
       hvacMode = TRUE;                              // FALSE = cooling, TRUE =  heating. Logic swapped on purpose.
     }
-
-    Blynk.setProperty(V16, "color", "#23C48E");

     startFlag = TRUE;
     stopFlag = FALSE;


código parcialmente funcional, com bugs

código parcialmente funcional, com bugs

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -78,9 +78,9 @@
     boolean produzindo = FALSO;
   // Tempos do Ciclo
     // Ciclo
-    unsigned long ciclo_padrao = 1500;
+    unsigned long ciclo_padrao = 2000;
     unsigned long ciclo_minimo = 900;
-    unsigned long ciclo_maximo = 2200;
+    unsigned long ciclo_maximo = 2000;
     unsigned long primeiro_ciclo = 0;
     // Mandibula
     unsigned long inicio_mandibula = 550;
@@ -225,18 +225,18 @@
     unsigned long novo_ciclo = tempo_atual - inicio_ciclo;
     unsigned long minimo = inicio_ciclo + ciclo_minimo;
     unsigned long maximo = inicio_ciclo + ciclo_maximo;
-    if ((ativo(sensor_reset) || (tempo_atual >= maximo))) {
-      if ((novo_ciclo > minimo && novo_ciclo < maximo) || (tempo_atual >= maximo)) {
-        ciclo_padrao = (tempo_atual - primeiro_ciclo) / (long) conta_ciclos;
+    if ((tempo_atual >= maximo) || (ativo(sensor_reset))) {
+      if (minimo < novo_ciclo < maximo) { //  || (tempo_atual >= maximo)
+        conta_ciclos++;
         ciclo_resetado = VERDADEIRO;
-        conta_ciclos++;
-        escreveSerial((String) conta_ciclos + ": " + (String) (tempo_atual - inicio_ciclo));
+        escreveSerial((String) conta_ciclos + ": " + (String) (tempo_atual - inicio_ciclo) + " / R:" + (String) tempo_atual + "-" + (String) primeiro_ciclo + "/" + (String) conta_ciclos + "=" + (String) ciclo_padrao);
         reiniciaCiclo();
+        ciclo_padrao = ((tempo_atual - primeiro_ciclo) / (unsigned long) conta_ciclos);
       } else if (novo_ciclo >= maximo) {
-        escreveSerial("Erro, reset maior que o maximo: " + (String) novo_ciclo);
+        escreveSerial("Erro, reset maior que o maximo: " + (String) novo_ciclo + " / R:" + (String) maximo);
         reset_falso = VERDADEIRO;
       } else if (novo_ciclo <= minimo) {
-        escreveSerial("Erro, reset menor que o minimo: " + (String) novo_ciclo);
+        escreveSerial("Erro, reset menor que o minimo: " + (String) novo_ciclo + " / R:" + (String) minimo);
         reset_falso = VERDADEIRO;
       }
     }


Added MQTT support and initial data reset from Blynk.

--- thermometer01.ino
+++ thermometer01.ino
@@ -13,7 +13,7 @@
   CREDENTIALS:
   Author: Libor Gabaj
 */
-#define PARTICLE_CLOUD              // Comment to totally ignore Particle Cloud
+// #define PARTICLE_CLOUD              // Comment to totally ignore Particle Cloud
 // #define PHOTON_PUBLISH_DEBUG        // Uncomment to publish debug events to Particle Cloud
 #define PHOTON_PUBLISH_VALUE        // Uncomment to publish regular events to Particle Cloud

@@ -22,6 +22,11 @@
 #define BLYNK_CLOUD                 // Comment to totally ignore Blynk Cloud
 // #define BLYNK_NOTIFY_TEMP           // Uncomment to send Blynk push notifications
 #define BLYNK_SIGNAL_TEMP           // Uncomment to use Blynk LED signalling
+
+#define MQTT_CLOUD                  // Comment to totally ignore MQTT broker
+#define MQTT_PUBLISH                // Uncomment to enable publishing to MQTT topics
+#define MQTT_SUBSCRIBE              // Uncomment to enable subscribing to MQTT topics
+

 // Libraries
 #include "watchdogs/watchdogs.h"
@@ -37,6 +42,9 @@
 #include "blynk/blynk.h"
 #endif

+#ifdef MQTT_CLOUD
+#include "MQTT/MQTT.h"
+#endif

 //-------------------------------------------------------------------------
 // Boot setup
@@ -52,7 +60,7 @@
 //-------------------------------------------------------------------------
 // Temperature sensing and publishing to Particle, ThinkSpeak, and Blynk
 //-------------------------------------------------------------------------
-#define SKETCH "THERMOMETER01 1.4.0"
+#define SKETCH "THERMOMETER01 1.5.0"
 #include "credentials.h"

@@ -110,19 +118,19 @@
 retained float tempValueMin = 150.0, tempValueMax = -50.0;

+#ifdef PARTICLE_CLOUD
 //-------------------------------------------------------------------------
 // Particle configuration
 //-------------------------------------------------------------------------
-#ifdef PARTICLE_CLOUD
 const unsigned int PERIOD_PUBLISH_PARTICLE = 15000;
 const byte PARTICLE_BATCH_LIMIT = 4;    // Don't change it - platform dependent
 #endif

+#ifdef THINGSPEAK_CLOUD
 //-------------------------------------------------------------------------
 // ThinkSpeak configuration
 //-------------------------------------------------------------------------
-#ifdef THINGSPEAK_CLOUD
 const unsigned int PERIOD_PUBLISH_THINGSPEAK = 60000;
 const char* THINGSPEAK_TOKEN = CREDENTIALS_THINGSPEAK_TOKEN;
 const unsigned long THINGSPEAK_CHANNEL_NUMBER = CREDENTIALS_THINGSPEAK_CHANNEL;
@@ -134,18 +142,19 @@
 #endif

+#ifdef BLYNK_CLOUD
 //-------------------------------------------------------------------------
 // Blynk configuration
 //-------------------------------------------------------------------------
-#ifdef BLYNK_CLOUD
 const unsigned int PERIOD_PUBLISH_BLYNK = 30000;
 char BLYNK_TOKEN[] = CREDENTIALS_BLYNK_TOKEN;
 #define BLYNK_VPIN_LCD_STATUS           V0
 #define BLYNK_VPIN_BUTTON_STATUS        V1
-#define BLYNK_VPIN_BUTTON_RESET         V2
+#define BLYNK_VPIN_BUTTON_RESET_INIT    V2
 #define BLYNK_VPIN_VALUE_RSSI           V3
 #define BLYNK_VPIN_VALUE_TEMP           V4
 #define BLYNK_VPIN_VALUE_TEMP_GAUGE     V4
+#define BLYNK_VPIN_BUTTON_RESET_TEMP    V5
 // #define BLYNK_VPIN_VALUE_TEMP_DIFF      V5
 #define BLYNK_VPIN_VALUE_TEMP_MIN       V6
 #define BLYNK_VPIN_VALUE_TEMP_MAX       V7
@@ -157,12 +166,12 @@
 #endif

 #ifdef BLYNK_SIGNAL_TEMP
-#ifdef BLYNK_VPIN_LED_TEMP_INC
+    #ifdef BLYNK_VPIN_LED_TEMP_INC
 WidgetLED ledTempInc(BLYNK_VPIN_LED_TEMP_INC);
-#endif
-#ifdef BLYNK_VPIN_LED_TEMP_DEC
+    #endif
+    #ifdef BLYNK_VPIN_LED_TEMP_DEC
 WidgetLED ledTempDec(BLYNK_VPIN_LED_TEMP_DEC);
-#endif
+    #endif
 #endif

 #if defined(BLYNK_NOTIFY_TEMP)
@@ -173,6 +182,49 @@
 #endif

+#ifdef MQTT_CLOUD
+//-------------------------------------------------------------------------
+// MQTT configuration
+//-------------------------------------------------------------------------
+const unsigned int PERIOD_PUBLISH_MQTT = 2000;
+byte MQTT_BROKER_IP[] = {192, 168, 0, 9};
+const unsigned int MQTT_BROKER_PORT = 1883;
+
+const String MQTT_PREFIX_DEVICE = String("Chalupa/Interior/");
+
+const String MQTT_VAR_RESET = String("Reset");
+const String MQTT_VAR_GET = String("Get");
+const String MQTT_VAR_INITIALS = String("Initials");
+const String MQTT_VAR_STATISTICS = String("Statistics");
+
+const String MQTT_VAR_VALUE = String("Value");
+const String MQTT_VAR_MINIMUM = String("Minimum");
+const String MQTT_VAR_MAXIMUM = String("Maximum");
+const String MQTT_VAR_DIFF = String("Diff");
+const String MQTT_VAR_STATUS = String("Status");
+
+#ifdef MQTT_PUBLISH
+const String MQTT_TOPIC_PUB_STATUS = String(MQTT_PREFIX_DEVICE + MQTT_VAR_STATUS);
+
+const String MQTT_TOPIC_PUB_RSSI = String(MQTT_PREFIX_DEVICE + "RSSI");
+
+const String MQTT_TOPIC_PUB_TEMP = String(MQTT_PREFIX_DEVICE + "Temperature/");
+const String MQTT_TOPIC_PUB_TEMP_VALUE   = String(MQTT_TOPIC_PUB_TEMP + MQTT_VAR_VALUE);
+const String MQTT_TOPIC_PUB_TEMP_STATUS  = String(MQTT_TOPIC_PUB_TEMP + MQTT_VAR_STATUS);
+const String MQTT_TOPIC_PUB_TEMP_DIFF    = String(MQTT_TOPIC_PUB_TEMP + MQTT_VAR_DIFF);
+const String MQTT_TOPIC_PUB_TEMP_MINIMUM = String(MQTT_TOPIC_PUB_TEMP + MQTT_VAR_MINIMUM);
+const String MQTT_TOPIC_PUB_TEMP_MAXIMUM = String(MQTT_TOPIC_PUB_TEMP + MQTT_VAR_MAXIMUM);
+#endif
+
+#ifdef MQTT_SUBSCRIBE
+const String MQTT_TOPIC_SUB_RESET = String(MQTT_PREFIX_DEVICE + MQTT_VAR_RESET);
+const String MQTT_TOPIC_SUB_GET = String(MQTT_PREFIX_DEVICE + MQTT_VAR_GET);
+#endif
+
+MQTT MqttClient(MQTT_BROKER_IP, MQTT_BROKER_PORT, subscriptionMqtt);
+#endif
+
+
 //-------------------------------------------------------------------------
 // SETUP
 //-------------------------------------------------------------------------
@@ -190,6 +242,17 @@
 #ifdef BLYNK_CLOUD
     Blynk.begin(BLYNK_TOKEN);
 #endif
+
+#ifdef MQTT_CLOUD
+    MqttClient.connect(System.deviceID());
+    #ifdef MQTT_SUBSCRIBE
+    if (MqttClient.isConnected())
+    {
+        MqttClient.subscribe(MQTT_TOPIC_SUB_RESET);
+        MqttClient.subscribe(MQTT_TOPIC_SUB_GET);
+    }
+    #endif
+#endif
 }

@@ -205,6 +268,10 @@
     Blynk.run();
 #endif

+#ifdef MQTT_CLOUD
+    if (MqttClient.isConnected()) MqttClient.loop();
+#endif
+
     measure();
     publish();
 }
@@ -237,6 +304,10 @@
     }
 }

+
+//-------------------------------------------------------------------------
+// Publishing
+//-------------------------------------------------------------------------
 void publish()
 {
 #ifdef PARTICLE_CLOUD
@@ -249,6 +320,10 @@

 #ifdef BLYNK_CLOUD
     publishBlynk();
+#endif
+
+#if defined(MQTT_CLOUD) && defined(MQTT_PUBLISH)
+    publishMqtt();
 #endif
 }

@@ -284,10 +359,10 @@
     }
 }

+#ifdef PARTICLE_CLOUD
 //-------------------------------------------------------------------------
 // Publishing to Particle
 //-------------------------------------------------------------------------
-#ifdef PARTICLE_CLOUD
 void publishParticle()
 {
     static unsigned long timeStamp;
@@ -368,18 +443,18 @@
                 publishSuccess = Particle.publish("Status", String(TEMP_STATUS_NAME[tempStatus]));
                 break;

-#ifdef PHOTON_PUBLISH_DEBUG
+    #ifdef PHOTON_PUBLISH_DEBUG
             case 3:
                 publishSuccess = Particle.publish("Reconnects", String(reconnects));
                 break;

-#ifdef THINGSPEAK_CLOUD
+        #ifdef THINGSPEAK_CLOUD
             case 4:
                 publishSuccess = Particle.publish("ThingSpeakResult", String(thingspeakResult));
                 break;
-#endif
-
-#endif
+        #endif
+
+    #endif
             default:
                 sendMsgNo = 0;
                 if (startMsgNo > 0) continue;   // Rotate messages from the first one
@@ -396,13 +471,13 @@
 #endif

+#ifdef THINGSPEAK_CLOUD
 //-------------------------------------------------------------------------
 // Publishing to ThingSpeak
 //-------------------------------------------------------------------------
-#ifdef THINGSPEAK_CLOUD
 void publishThingspeak()
 {
-    static float tempValueOld = TEMP_VALUE_NAN;
+    static float tempValueOld = tempValue;
     static unsigned long timeStamp;
     if (millis() - timeStamp >= PERIOD_PUBLISH_THINGSPEAK)
     {
@@ -421,7 +496,6 @@

 #ifdef THINGSPEAK_FIELD_TEMP_DIFF
         isField = true;
-        if (tempValueOld == TEMP_VALUE_NAN) tempValueOld = tempValue;
         float tempDiff = tempValue - tempValueOld;
         tempValueOld = tempValue;
         ThingSpeak.setField(THINGSPEAK_FIELD_TEMP_DIFF, (float)tempDiff);
@@ -437,16 +511,16 @@
 #endif

+#ifdef BLYNK_CLOUD
 //-------------------------------------------------------------------------
 // Publishing to Blynk
 //-------------------------------------------------------------------------
-#ifdef BLYNK_CLOUD
 void publishBlynk()
 {
 #if defined(BLYNK_NOTIFY_TEMP) || defined(BLYNK_SIGNAL_TEMP)
-#ifdef BLYNK_NOTIFY_TEMP
+    #ifdef BLYNK_NOTIFY_TEMP
     static byte tempStatusOld = tempStatus;
-#endif
+    #endif
     static float tempValueOld = tempValue;
     static unsigned long timeStamp;
     if (millis() - timeStamp >= PERIOD_PUBLISH_BLYNK)
@@ -454,60 +528,60 @@
         timeStamp = millis();
         float tempDiff = tempValue - tempValueOld;

-#ifdef BLYNK_VPIN_VALUE_TEMP
+    #ifdef BLYNK_VPIN_VALUE_TEMP
         // Pushing temperature value to the cloud for gauge
         Blynk.virtualWrite(BLYNK_VPIN_VALUE_TEMP, tempValue);
         Blynk.setProperty(BLYNK_VPIN_VALUE_TEMP, "label", String(TEMP_STATUS_NAME[tempStatus]));
         Blynk.setProperty(BLYNK_VPIN_VALUE_TEMP, "color", String(TEMP_STATUS_COLOR[tempStatus]));
-#endif
-
-#ifdef BLYNK_VPIN_VALUE_TEMP_DIFF
+    #endif
+
+    #ifdef BLYNK_VPIN_VALUE_TEMP_DIFF
         // Pushing temperature change to the cloud
-        Blynk.virtualWrite(BLYNK_VPIN_VALUE_TEMP_DIFF, String::format("%4.1f", tempDiff));
-#endif
-
-#ifdef BLYNK_SIGNAL_TEMP
+        Blynk.virtualWrite(BLYNK_VPIN_VALUE_TEMP_DIFF, tempDiff);
+    #endif
+
+    #ifdef BLYNK_SIGNAL_TEMP
         // Temperature change signalling
         if (tempDiff > 0)
         {
-#ifdef BLYNK_VPIN_LED_TEMP_INC
+        #ifdef BLYNK_VPIN_LED_TEMP_INC
             ledTempInc.on();
-#endif
-#ifdef BLYNK_VPIN_LED_TEMP_INC
+        #endif
+        #ifdef BLYNK_VPIN_LED_TEMP_INC
             ledTempDec.off();
-#endif
+        #endif
         }
         else if (tempDiff < 0)
         {
-#ifdef BLYNK_VPIN_LED_TEMP_INC
+        #ifdef BLYNK_VPIN_LED_TEMP_INC
             ledTempInc.off();
-#endif
-#ifdef BLYNK_VPIN_LED_TEMP_INC
+        #endif
+        #ifdef BLYNK_VPIN_LED_TEMP_INC
             ledTempDec.on();
-#endif
+        #endif
         }
         else
         {
-#ifdef BLYNK_VPIN_LED_TEMP_INC
+        #ifdef BLYNK_VPIN_LED_TEMP_INC
             ledTempInc.off();
-#endif
-#ifdef BLYNK_VPIN_LED_TEMP_INC
+        #endif
+        #ifdef BLYNK_VPIN_LED_TEMP_INC
             ledTempDec.off();
-#endif
-        }
-#endif
+        #endif
+        }
+    #endif

         // Publishing only at relevant temperature change
         if (fabs(tempDiff) > TEMP_VALUE_MARGIN)
         {
-#ifdef BLYNK_NOTIFY_TEMP
+    #ifdef BLYNK_NOTIFY_TEMP
             // Temperature status push notification
             if (tempStatus != tempStatusOld)
             {
                 Blynk.notify(BLYNK_LABEL_PREFIX + BLYNK_LABEL_GLUE + String::format("%4.1f C", tempValue) + BLYNK_LABEL_GLUE + TEMP_STATUS_NAME[tempStatus]);
                 tempStatusOld = tempStatus;
             }
-#endif
+    #endif
         }
         tempValueOld = tempValue;
     }
@@ -527,14 +601,14 @@
 #ifdef BLYNK_VPIN_VALUE_TEMP_MIN
 BLYNK_READ(BLYNK_VPIN_VALUE_TEMP_MIN)
 {
-    Blynk.virtualWrite(BLYNK_VPIN_VALUE_TEMP_MIN, String::format("%4.1f", tempValueMin));
+    Blynk.virtualWrite(BLYNK_VPIN_VALUE_TEMP_MIN, tempValueMin);
 }
 #endif

 #ifdef BLYNK_VPIN_VALUE_TEMP_MAX
 BLYNK_READ(BLYNK_VPIN_VALUE_TEMP_MAX)
 {
-    Blynk.virtualWrite(BLYNK_VPIN_VALUE_TEMP_MAX, String::format("%4.1f", tempValueMax));
+    Blynk.virtualWrite(BLYNK_VPIN_VALUE_TEMP_MAX, tempValueMax);
 }
 #endif

@@ -551,13 +625,22 @@
 //-------------------------------------------------------------------------
 // Blynk actions
 //-------------------------------------------------------------------------
-#ifdef BLYNK_VPIN_BUTTON_RESET
-BLYNK_WRITE(BLYNK_VPIN_BUTTON_RESET)
+#ifdef BLYNK_VPIN_BUTTON_RESET_INIT
+BLYNK_WRITE(BLYNK_VPIN_BUTTON_RESET_INIT)
 {
     if (param.asInt() == HIGH)
     {
+        boots = bootRunPeriod = bootTimeLast = reconnects = 0;
+    }
+}
+#endif
+
+#ifdef BLYNK_VPIN_BUTTON_RESET_TEMP
+BLYNK_WRITE(BLYNK_VPIN_BUTTON_RESET_TEMP)
+{
+    if (param.asInt() == HIGH)
+    {
         tempValueMin = tempValueMax = tempValue;
-        reconnects = 0;
     }
 }
 #endif
@@ -572,7 +655,7 @@
     static byte lcdMode;
     if (param.asInt() == HIGH)
     {
-#ifdef BLYNK_VPIN_LCD_STATUS
+    #ifdef BLYNK_VPIN_LCD_STATUS
         lcd:
         lcdMode++;
         lcdStatus.clear();
@@ -601,9 +684,77 @@
                 goto lcd;
                 break;
         }
-#endif
-    }
-}
-#endif
-
-#endif
+    #endif
+    }
+}
+#endif
+
+#endif
+
+#ifdef MQTT_CLOUD
+//-------------------------------------------------------------------------
+// Publishing to MQTT
+//-------------------------------------------------------------------------
+#ifdef MQTT_PUBLISH
+void publishMqtt()
+{
+    static float tempValueOld = tempValue;
+    static unsigned long timeStamp;
+    if (millis() - timeStamp >= PERIOD_PUBLISH_MQTT)
+    {
+        timeStamp = millis();
+        float tempDiff = tempValue - tempValueOld;
+        if (MqttClient.isConnected())
+        {
+            MqttClient.publish(MQTT_TOPIC_PUB_RSSI, String(rssiValue));
+            MqttClient.publish(MQTT_TOPIC_PUB_TEMP_STATUS, String(TEMP_STATUS_NAME[tempStatus]));
+            MqttClient.publish(MQTT_TOPIC_PUB_TEMP_VALUE, String(tempValue));
+            MqttClient.publish(MQTT_TOPIC_PUB_TEMP_MINIMUM, String(tempValueMin));
+            MqttClient.publish(MQTT_TOPIC_PUB_TEMP_MAXIMUM, String(tempValueMax));
+            MqttClient.publish(MQTT_TOPIC_PUB_TEMP_DIFF, String(tempDiff));
+        }
+        tempValueOld = tempValue;
+    }
+}
+#endif
+
+
+//-------------------------------------------------------------------------
+// Subscriptions to MQTT
+//-------------------------------------------------------------------------
+#ifdef MQTT_SUBSCRIBE
+void subscriptionMqtt(char* topic, byte* payload, unsigned int length)
+{
+    String msgTopic = String(topic);
+    // Message content
+    char p[length + 1];
+    memcpy(p, payload, length);
+    p[length] = NULL;
+    String msgPayload(p);
+
+    // Request for action
+    if (msgTopic.equals(MQTT_TOPIC_SUB_RESET))
+    {
+        if (msgPayload.equals(MQTT_VAR_INITIALS))
+        {
+            boots = bootRunPeriod = bootTimeLast = reconnects = 0;
+        }
+        if (msgPayload.equals(MQTT_VAR_STATISTICS))
+        {
+            tempValueMin = tempValueMax = tempValue;
+        }
+    }
+    // Request for value
+    if (msgTopic.equals(MQTT_TOPIC_SUB_GET))
+    {
+        if (msgPayload.equals(MQTT_VAR_INITIALS))
+        {
+    #ifdef MQTT_PUBLISH
+        MqttClient.publish(MQTT_TOPIC_PUB_STATUS, String::format("%s = %d/%d/%s/%d", MQTT_VAR_INITIALS.c_str(), boots, bootRunPeriod, System.version().c_str(), reconnects));
+    #endif
+        }
+    }
+}
+#endif
+
+#endif


Comment out reporting on ds18b20

Comment out reporting on ds18b20

--- computer_box/computer_box.ino
+++ computer_box/computer_box.ino
@@ -44,20 +44,22 @@
     if (sensor_bus.search(sensors_address[x]))
       c++;
   }
-  if (c > 0) {
-    Serial.println("Found this sensors : ");
-    for (x = 0; x < num_ds18; x++) {
-      Serial.print("\tSensor ");
-      Serial.print(x + 1);
-      Serial.print(" at address : ");
-      for (y = 0; y < 8; y++) {
-        Serial.print(sensors_address[x][y], HEX);
-        Serial.print(" ");
-      }
-      Serial.println();
-    }
-  } else
-    Serial.println("Didn't find any sensors");
+  // Report on which sensors were found
+  // if (c > 0) {
+  //   Serial.println("Found this sensors : ");
+  //   for (x = 0; x < num_ds18; x++) {
+  //     Serial.print("\tSensor ");
+  //     Serial.print(x + 1);
+  //     Serial.print(" at address : ");
+  //     for (y = 0; y < 8; y++) {
+  //       Serial.print(sensors_address[x][y], HEX);
+  //       Serial.print(" ");
+  //     }
+  //     Serial.println();
+  //   }
+  // } else {
+  //   Serial.println("Didn't find any sensors");
+  // }
 }

 void loop() {


a new version of code that is tested, updates include: - change camel case to underscore - added a new message type called H, for hovering event - changed how the client reacts to IR, it tracks the previous largest value, and report that through XBee


Apply stashed changes

Apply stashed changes

--- src/teensy_sketch/teensy_sketch.ino
+++ src/teensy_sketch/teensy_sketch.ino
@@ -106,16 +106,15 @@

 void setup() {
   dataModule.setDebugMode(serialDebugMode); // set debug flag in library instance
+  initializeSPI();
+
   dataModule.initialize();                  // setup data module

   // begin I2C for MPU IMU
   Wire1.begin(I2C_MASTER, 0x000, I2C_PINS_29_30, I2C_PULLUP_EXT, I2C_RATE_400);
-
+
   // begin serial used for GPS data
   gpsSerial.begin(gpsSerialBaud);
-
-  // begin SPI for high-accuracy gyro
-  SPI.begin();

   // Sensor setup
   delay(500);
@@ -141,6 +140,16 @@
 //                   Function definitions
 // ------------------------------------------------------------

+// Function to handle SPI initialisation
+void initializeSPI() {
+  // start chipselects
+  pinMode(gyroChipSelect, OUTPUT);
+  pinMode(radioChipSelect, OUTPUT);
+  pinMode(sdChipSelect, OUTPUT);
+
+  // start SPI
+  SPI.begin();
+}
 // Function to set up all sensors on IMU board
 void setupIMU() {
   // TODO: Check return of each to ensure success


Updated library requirement comments

Updated library requirement comments

--- starsynctrackers.ino
+++ starsynctrackers.ino
@@ -1,8 +1,8 @@
 //
-// If using Motorshield requires the Adafruit_Motorshield v2 library
+// Need AccelStepper fork with AFMotor support with library
+//   https://github.com/adafruit/AccelStepper
+// If using Adafruit v2 Motorshield requires the Adafruit_Motorshield v2 library
 //   https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library
-// And you need AccelStepper fork with AFMotor support with library
-//   https://github.com/adafruit/AccelStepper
 // if using adafruit motor shield v1 then you need v1 library
 //' https://github.com/adafruit/Adafruit-Motor-Shield-library


'Fixes' systemStart not set.

'Fixes' systemStart not set.

--- ntptask.ino
+++ ntptask.ino
@@ -20,11 +20,13 @@
   time_t now;
   struct tm timeinfo;

-  while ( timeinfo.tm_year < ( 2016 - 1900 ) ) {
+  while ( timeinfo.tm_year < ( 2016 - 1900 ) )
+  {
     vTaskDelay( 50 / portTICK_PERIOD_MS );
     time( &now );
     localtime_r( &now, &timeinfo );
   }
+  delay(100);
   gettimeofday( &systemStart, NULL );

   ESP_LOGI( TAG, "NTP sync @ %s", asctime( localtime( &systemStart.tv_sec ) ) );


Removes formatted doublequote

Removes formatted doublequote

--- smart_bathroom.ino
+++ smart_bathroom.ino
@@ -12,7 +12,7 @@
 void setup() {
   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
-  Spark.variable(“doorStatus", &doorStatus, INT);
+  Spark.variable("doorStatus", &doorStatus, INT);
 }

 void loop() {
@@ -167,4 +167,3 @@
     strip.setBrightness(30);
     strip.show();
 }
-