Working on HMAC

Working on HMAC

--- src/CAN_receive_v2/CAN_receive_v2.ino
+++ src/CAN_receive_v2/CAN_receive_v2.ino
@@ -4,6 +4,7 @@
 // Use http://www.seeedstudio.com/wiki/CAN-BUS_Shield if need help

 #include <SPI.h>
+#include <SpritzCipher.h>
 #include "mcp_can.h"
 #include "can_constants.h"

@@ -14,9 +15,9 @@

 MCP_CAN CAN(SPI_CS_PIN);                                    // Set CS pin

-unsigned char dlc = 0; // dlc
-unsigned char data[8]; // data buffer
-unsigned char id = 0; // CAN ID
+uint8_t dlc = 0; // dlc
+uint8_t data[8]; // data buffer
+uint32_t id = 0; // CAN ID

 // "Control Units" -- LED Lights to be controlled
@@ -30,6 +31,13 @@
 int redValue = 255;
 int blueValue = 0;
 int greenValue = 0;
+
+// For authentication
+const uint8_t HASH_LEN = 20; // 160-bit hash
+uint8_t correct_hash[HASH_LEN];
+uint8_t msg1[8];
+uint8_t msg2[8];
+uint8_t msg3[4];

 void setup()
 {
@@ -61,12 +69,84 @@
 {
     if(CAN_MSGAVAIL == CAN.checkReceive())            // check if data coming
     {
+        // Read the actual message first
         id = CAN.getCanId(); // get CAN ID
-        CAN.readMsgBuf(&dlc, data);    // read data,  len: data length, buf: data buf
-
-        PrintMessage();
-        TakeAction();
-    }
+        CAN.readMsgBuf(&dlc, data);    // read data,  len: data length, buf: data buf
+
+        // Store the correct hash according to the received data
+        GetCorrectHash();
+
+        // Read in the Authentication messages and check if valid
+        if (Authenticate())
+        {
+            // It's valid, so take action
+            PrintMessage();
+            TakeAction();
+        }
+        else
+        {
+            // Invalid!
+            Serial.println("\n**UNAUTHORIZED MESSAGE**\n");
+        }
+    }
+}
+
+
+// Reads three CAN messages as authenticator messages
+bool Authenticate()
+{
+    // Fill the 3 msg buffers and check them as they are read in for efficiency
+    CAN.readMsgBuf(&dlc, msg1);
+    //if (!CheckAuthMessage(&msg1[0], 0, 8)) return false;
+    CAN.readMsgBuf(&dlc, msg2);
+    //if (!CheckAuthMessage(&msg2[0], 8, 8)) return false;
+    CAN.readMsgBuf(&dlc, msg3);
+    //if (!CheckAuthMessage(&msg3[0], 16, 4)) return false;
+    for(int i = 0; i < 8; i++)
+    {
+      Serial.print(msg1[i]);
+      Serial.print(".");
+    }
+    for(int i = 0; i < 8; i++)
+    {
+      Serial.print(msg2[i]);
+      Serial.print(".");
+    }
+    for(int i = 0; i < 4; i++)
+    {
+      Serial.print(msg3[i]);
+      Serial.print(".");
+    }
+    Serial.print('\n');
+    for(int i = 0; i < 20; i++)
+    {
+      Serial.print(correct_hash[i]);
+      Serial.print('.');
+    }
+    Serial.println('---------------------');
+    return true;
+}
+
+
+// Stores the correct hash in correcct_hash
+void GetCorrectHash()
+{
+    uint8_t keyLen;
+    uint8_t key[100];
+    GetKey(id, &key[0], keyLen); // get key and key length for this is
+    spritz_mac(&correct_hash[0], HASH_LEN, &data[0], dlc, key, keyLen); // create correct hash
+}
+
+
+// Checks an auth message against correct_hash
+bool CheckAuthMessage(uint8_t *buf, int start, int bufLen)
+{
+    for (int i = 0; i < bufLen; i++)
+    {
+      if (buf[i] != correct_hash[i + start])
+          return false;
+    }
+    return true;
 }

@@ -145,15 +225,6 @@
 }

-//---------------------------------------------------------------------------------------
-// Check/Authenticate the message received
-//---------------------------------------------------------------------------------------
-bool Authenticate(int id, int dlc, unsigned char *data)
-{
-    // TODO
-    return true;
-}
-
 /*********************************************************************************************************
   END FILE
 *********************************************************************************************************/


overlooked duplicate name

overlooked duplicate name

--- hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
+++ hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
@@ -100,7 +100,7 @@
   return false;
 }

-void loadFromSdCard(){
+void tryLoadFromSdCard(){
   String message = "FileNotFound\n\n";
   if(hasSD){
     //try to load the URL from SD Card
@@ -142,7 +142,7 @@
   }

   //Attach handler
-  server.onNotFound(loadFromSdCard);
+  server.onNotFound(tryLoadFromSdCard);

   //start server
   server.begin();


Modified two function declarations to remove the "warning: deprecated conversion from string constant to 'char*'" warnings I was getting from the Arduino IDE, probably due to recent changes to the compiler toolchain, and showing warnings it never used to.

Ammended some of the comments to better reflect the purpose of the code - just for the helper function calls in the setup block.

--- libraries/_Oak_Examples/examples/OLED_minimal/OLED_minimal.ino
+++ libraries/_Oak_Examples/examples/OLED_minimal/OLED_minimal.ino
@@ -9,28 +9,29 @@

 #include <Wire.h>
 #include "font.h"
+
 #define OLED_address  0x3c                           // all the OLED's I have seen have this address

 uint8_t offset = 0;

-void setup(void) {
-
-  Wire.begin();                                // Initialize I2C and OLED Display
-  init_OLED();                                    //
-  reset_display();
-                                // Start the server
-  clear_display();
-
-  delay(3000);
-
-
-  sendStrXY("OLED ready!",4,0);              // OLED first message
-
-}
-
-
-void loop(void) {
-                       // checks for incoming messages
+void setup(void)
+{
+  Wire.begin();                                // Initialise I2C
+
+  init_OLED();                                 // Initailise the OLED Display
+  reset_display();                             // Make sure the display is blank
+
+  //clear_display();                           // Reset does this, so no need to do twice
+
+  delay(3000);                                 // Give things time to settle
+
+  sendStrXY("OLED ready!",4,0);                // Display a message on the OLED!
+}
+
+// empty loop function as everything is done in setup
+// normally we would have our continously running stuff here
+void loop(void)
+{
 }

 //==========================================================//
@@ -126,7 +127,7 @@

 //==========================================================//
 // Prints a string regardless the cursor position.
-static void sendStr(char *string)
+static void sendStr(char const* string)
 {
   unsigned char i=0;
   while(*string)
@@ -142,7 +143,7 @@
 //==========================================================//
 // Prints a string in coordinates X Y, being multiples of 8.
 // This means we have 16 COLS (0-15) and 8 ROWS (0-7).
-static void sendStrXY( char *string, int X, int Y)
+static void sendStrXY(char const* string, int X, int Y)
 {
   setXY(X,Y);
   unsigned char i=0;
@@ -208,5 +209,4 @@
   sendcommand(0x00);            //Set Memory Addressing Mode ab Horizontal addressing mode
   //  sendcommand(0x02);         // Set Memory Addressing Mode ab Page addressing mode(RESET)
 }
-
-
+


s/Spark/Particle

s/Spark/Particle

--- firmware/wateralarm.ino
+++ firmware/wateralarm.ino
@@ -38,19 +38,20 @@
 // Functions
 //

-// Spark setup
+// Particle setup
 void setup() {
     // initialize our pins I/O
-    pins_init();
-
+    pinMode(LED, OUTPUT);
+    pinMode(WATER_SENSOR, INPUT);
+
     // tell the world we're online
-    Spark.publish("online");
-
+    Particle.publish("online");
+
     // publish the water variable
-    Spark.variable("water", &water, INT);
-
+    Particle.variable("water", &water, INT);
+
     // publish the alarm state variable
-    Spark.variable("alarmState", &alarmState, INT);
+    Particle.variable("alarmState", &alarmState, INT);
 }

 // Spark loop
@@ -68,7 +69,7 @@
             if (now - lastStateSwitchTime > DEBOUNCE_SECONDS) {
                 alarmState = 1;
                 lastStateSwitchTime = now;
-                Spark.publish("water_alarm", "on", 60, PRIVATE);
+                Particle.publish("water_alarm", "on", 60, PRIVATE);
             }
         }
     } else {
@@ -81,18 +82,12 @@
             // only alarm if we're past the debounce interval
             int now = Time.now();
             if (now - lastStateSwitchTime > DEBOUNCE_SECONDS) {
-                alarmState = 0;
+                alarmState = 0;
                 lastStateSwitchTime = now;
-                Spark.publish("water_alarm", "off", 60, PRIVATE);
+                Particle.publish("water_alarm", "off", 60, PRIVATE);
             }
         }
     }
-}
-
-// initialize our pins
-void pins_init() {
-    pinMode(LED, OUTPUT);
-    pinMode(WATER_SENSOR, INPUT);
 }

 // determine if we're exposed to water or not


Simplify header includes, commentary

Simplify header includes, commentary

--- examples/rwccert-otaa-halconfig-us915/rwccert-otaa-halconfig-us915.ino
+++ examples/rwccert-otaa-halconfig-us915/rwccert-otaa-halconfig-us915.ino
@@ -1,23 +1,30 @@
-/*******************************************************************************
- * Copyright (c) 2019 Terry Moore, MCCI
- *
- * Permission is hereby granted, free of charge, to anyone
- * obtaining a copy of this document and accompanying files,
- * to do whatever they want with them without any restriction,
- * including, but not limited to, copying, modification and redistribution.
- * NO WARRANTY OF ANY KIND IS PROVIDED.
- *
- *******************************************************************************/
+/*
+
+Module: rwccert-otaa-halconfig.ino
+
+Function:
+    Test program for developing and checking LMIC compliance test support.
+
+Copyright and License:
+    Please see accompanying LICENSE file.
+
+Author:
+    Terry Moore, MCCI Corporation   March 2019
+
+*/
+
+#include <Arduino.h>

 #include <arduino_lmic.h>
-#include <hal/hal.h>
-#include <SPI.h>
 #include <arduino_lmic_hal_boards.h>
 #include <arduino_lmic_lorawan_compliance.h>

+#include <SPI.h>
+
 //
 // For compliance tests with the RWC5020A, we use the default addresses
-// from the tester.
+// from the tester; except that we use APPKEY 0,..., 0, 2, to avoid
+// collisions with a registered app on TTN.
 //

 // This EUI must be in little-endian format, so least-significant-byte
@@ -271,7 +278,7 @@
     Serial.print(F("Received message on port "));
     Serial.print(port);
     Serial.print(F(": "));
-    Serial.print(nMessage);
+    Serial.print(unsigned(nMessage));
     Serial.println(F(" bytes"));
     }

@@ -332,7 +339,7 @@
     Serial.println(F("Starting"));

     // LMIC init using the computed target
-    const lmic_pinmap *pPinMap = Arduino_LMIC::GetPinmap_ThisBoard();
+    const auto pPinMap = Arduino_LMIC::GetPinmap_ThisBoard();

     // don't die mysteriously; die noisily.
     if (pPinMap == nullptr) {


IR sensor, Bumper sensor, and Servo. Some experiments

--- SOURCE/sumobot/sumobot.ino
+++ SOURCE/sumobot/sumobot.ino
@@ -1,18 +1,53 @@
 #include <Servo.h>
-
-Servo m_left;
-Servo m_right;
+
+// Scorpion XL PPM Signal
+int left_motor_pin = 3;
+int right_motor_pin = 10;
+Servo left_motor;
+Servo right_motor;
+
+//
+int left_bumper = 4;
+int right_bumper = 12;
+int monitor_ired = 11;
+int center_ired = A0;
+

 void setup()
 {
-  m_left.attach(9);
-  m_right.attach(10);
+  Serial.begin(9600);
+  pinMode(monitor_ired, OUTPUT);
+  pinMode(center_ired, INPUT);
+  pinMode(left_bumper, INPUT);
+  pinMode(right_bumper, INPUT);
+  left_motor.attach(left_motor_pin);
+  right_motor.attach(right_motor_pin);
 }
-
-
+
+void search()
+{
+  int ir_val = analogRead(center_ired);
+  Serial.println(ir_val);
+  analogWrite(monitor_ired, map(ir_val, 0, 1023, 0 , 255));
+
+}
+
+void push(){
+  if(digitalRead(left_bumper)){
+    left_motor.write(180);
+  }else{
+    left_motor.write(0);
+  }
+
+  if(digitalRead(right_bumper)){
+    right_motor.write(180);
+  }else{
+    right_motor.write(0);
+  }
+}
+
 void loop()
 {
-  // Spin !!!
-  m_right.write(180);
-  m_left.write(0);
+  search();
+  push();
 }


removed debug code

removed debug code

--- reciever/reciever.ino
+++ reciever/reciever.ino
@@ -97,10 +97,12 @@
             fillDataArray(bitNumber, matchOne);

             if (bitNumber == DATA_BITS_AMOUNT - 1) {
-
                 //This was the last value bit
-                //All is done we can return the whole message to the client!
-                printDataArray();
+
+                //All is done we can return the whole message to the client
+                if (checkSumMatch()) {
+                    printDataArray();
+                }

                 //clear state to zero since nothing more we can do
                 setState(0, true);
@@ -132,13 +134,7 @@

 void printDataArray() {
     Serial.println("==== Sensor data captured ===");
-
-    for (byte i = 0; i < DATA_ARRAY_SIZE; i++) {
-        printByteAsBitSet(data[i]);
-        Serial.print("|");
-    }
-    Serial.println();
-
+
     byte sensorNumber = data[1] >> 2;
     byte powerOnUUID = (data[0] << 2) | (data[1] & 3);
     byte powerState = data[2] >> 3;
@@ -160,20 +156,9 @@

     Serial.print("Humidity: ");
     Serial.println(humidity);
-
-    Serial.print("CheckSumMatch: ");
-    printByteAsBitSet(checkSumMatch());
-    Serial.println();
-}
-
-void printByteAsBitSet(byte b) {
-    Serial.print((b & 8) >> 3);
-    Serial.print((b & 4) >> 2);
-    Serial.print((b & 2) >> 1);
-    Serial.print(b & 1);
-}
-
-byte checkSumMatch() {
+}
+
+boolean checkSumMatch() {

     //Sum first 8 tetrads
     int sum = 0;
@@ -182,8 +167,7 @@
     }

     //returns true if calculated check sum matches received
-    //return getLastFourBitsReversed(sum) == data[DATA_ARRAY_SIZE - 1];
-    return getLastFourBitsReversed(sum);
+    return getLastFourBitsReversed(sum) == data[DATA_ARRAY_SIZE - 1];
 }

 int getTemperature() {


wifi joining and status report now working

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -4,7 +4,11 @@
 #include <WiFiClient.h>
 #include <ESP8266WebServer.h>
 #include <DNSServer.h>
-
+
+// TODO refactor to create header from title
+// char* header() {
+//
+// }
 const char* ssid = "WaterElf";
 const char* html =
   "<title>WaterElf Aquaponics Helper</title>"
@@ -21,7 +25,6 @@
   "
data goes here...
"
   "

"
   "";
-
 const char* apChoice =
   "<title>WaterElf Aquaponics Helper: Wifi Config</title>"
   ""
@@ -29,6 +32,14 @@
   "
Choose a wifi access point to join

<form method='POST' action='chz'> "
   "_ITEMS_
Pass key: <input type='textarea' name='key'>

 "
   "<input type='submit' value='Submit'></form>
";
+const char* wstatus =
+  "<title>WaterElf Aquaponics Helper: Wifi Status</title>"
+  ""
+  ""
+  "
Wifi Status

";
+const char* footer =
+  "
WaterElf Home
"
+  "
Fish4Tea
";

 const byte DNS_PORT = 53;
 IPAddress apIP(192, 168, 1, 1);
@@ -59,8 +70,11 @@
   server.on("/L0", handle_L0);
   server.on("/L2", handle_L2);
   server.on("/ALL", handle_ALL);
+  server.onNotFound(handleNotFound);
+
   server.on("/wifi", handle_wifi);
-  server.onNotFound(handleNotFound);
+  server.on("/wifistatus", handle_wifistatus);
+  server.on("/chz", handle_chz);
   server.begin();

   Serial.println("HTTP server started");
@@ -100,6 +114,8 @@
       ""
       "
No AP data :-(
"
       "Back
Try again
"
+      "
WaterElf Home "
+      "Fish4Tea
"
       "";
   } else {
     Serial.print(n);
@@ -138,6 +154,65 @@
   delay(100);
 }

+void handle_wifistatus() {
+  Serial.println("serving page at /wifistatus");
+  String toSend = wstatus;
+  toSend += "
SSID: ";
+  toSend += WiFi.SSID();
+  toSend += "
";
+  toSend += "
Status: ";
+  switch(WiFi.status()) {
+    case WL_IDLE_STATUS:
+      toSend += "WL_IDLE_STATUS
"; break;
+    case WL_NO_SSID_AVAIL:
+      toSend += "WL_NO_SSID_AVAIL
"; break;
+    case WL_SCAN_COMPLETED:
+      toSend += "WL_SCAN_COMPLETED
"; break;
+    case WL_CONNECTED:
+      toSend += "WL_CONNECTED
"; break;
+    case WL_CONNECT_FAILED:
+      toSend += "WL_CONNECT_FAILED
"; break;
+    case WL_CONNECTION_LOST:
+      toSend += "WL_CONNECTION_LOST
"; break;
+    case WL_DISCONNECTED:
+      toSend += "WL_DISCONNECTED
"; break;
+    default:
+       toSend += "unknown
";
+  }
+  toSend += "

";
+  toSend += footer;
+  server.send(200, "text/html", toSend);
+  delay(100);
+}
+
+void handle_chz() {
+  Serial.println("serving page at /chz");
+  String toSend = "
Done! Joining...
";
+  String ssid = "";
+  String key = "";
+
+  for ( uint8_t i = 0; i < server.args(); i++ ) {
+    Serial.println(" " + server.argName(i) + ": " + server.arg(i) + "\n");
+    if(server.argName(i) == "ssid")
+      ssid = server.arg(i);
+    else if(server.argName(i) == "key")
+      key = server.arg(i);
+  }
+
+  if(ssid == "") {
+    toSend = "
Ooops, no SSID...?
";
+  } else {
+    char ssidchars[sizeof(ssid)];
+    char keychars[sizeof(key)];
+    ssid.toCharArray(ssidchars, sizeof(ssid));
+    key.toCharArray(keychars, sizeof(key));
+    WiFi.begin(ssidchars, keychars);
+  }
+
+  server.send(200, "text/html", toSend);
+  delay(100);
+}
+
 void handle_L0() { handle_root(); }
 void handle_L2() { handle_root(); }
 void handle_ALL() { handle_root(); }


Switched from SQL to MQTT to communicate with server.

--- esp8266-weather-station.ino
+++ esp8266-weather-station.ino
@@ -1,12 +1,10 @@
 #include "Sensor.h"
 #include "DebugStream.h"
-
-#include <MySQL_Connection.h>
-#include <MySQL_Cursor.h>

 #include <ESP8266WiFi.h>
 #include <ESP8266WebServer.h>
 #include <ArduinoOTA.h>
+#include <PubSubClient.h>

 #include <time.h>

@@ -26,13 +24,13 @@

 ESP8266WebServer httpServer(80);

-WiFiClient sqlClient;
-MySQL_Connection sqlConn(&sqlClient);
-MySQL_Cursor sqlCursor(&sqlConn);
-IPAddress sqlAddr;
+WiFiClient mqttClient;
+PubSubClient mqtt(DATA_SERVER_ADDR, DATA_SERVER_PORT, mqttClient);

 WiFiServer telnetServer(23);
 WiFiClient telnetClients[MAX_SRV_CLIENTS];
+
+void sendDataViaMqtt(float temp, int humidity, int pressure, int sensorId);

 void handleRoot()
 {
@@ -165,39 +163,98 @@
     }
 }

-void sendDataToSql(Sensor& sensor)
+void sendDataToServer(Sensor& sensor)
 {
     if (sensor.isValid())
     {
-        sendDataToSql(sensor.getTemperature(),
-                      roundf(sensor.getHumidity()),
-                      roundf(sensor.getPressureMmHg()),
-                      sensor.getId());
-    }
-}
-
-void sendDataToSql(float temp, int humidity, int pressure, int sensorId)
+        sendDataViaMqtt(sensor.getTemperature(),
+                        roundf(sensor.getHumidity()),
+                        roundf(sensor.getPressureMmHg()),
+                        sensor.getId());
+    }
+}
+
+/*uint32_t getParamsHash(curTime, temp, humidity, pressure, sensorId)
+{
+    return;
+}*/
+
+void mqttCallback(char* topic, byte* payload, unsigned int length)
+{
+    DebugPrint(debug, "Message arrived [%s]\n", topic);
+
+    for (unsigned int i = 0; i < length; ++i)
+    {
+        DebugPrint(debug, "%c", (char)payload[i]);
+    }
+    DebugPrint(debug, "\n");
+
+    // Switch on the LED if an 1 was received as first character
+    if ((char)payload[0] == '1')
+    {
+        digitalWrite(BUILTIN_LED, LOW);
+        // Turn the LED on (Note that LOW is the voltage level
+        // but actually the LED is on; this is because
+        // it is acive low on the ESP-01)
+    }
+    else
+    {
+        digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
+    }
+}
+
+void sendDataViaMqtt(float temp, int humidity, int pressure, int sensorId)
 {
     digitalWrite(led, 0);
-
-    char buf[128];
+
+    if (!timeIsSet)
+        return;
+
+    char payload[128];
     char tempStr[7];
+    char tokenStr[10];
     dtostrf(temp, sizeof(tempStr)-1, 2, tempStr);

-    int res = snprintf(buf, sizeof(buf),
-        "INSERT INTO Weather.sensor_smile (temp, hum, press, sensorId) VALUES (%s, %d, %d, %d)",
-        tempStr, humidity, pressure, sensorId);
-
-    if (res < 0 || res >= sizeof(buf))
-    {
-        DebugPrint(debug, "The SQL buffer is too small.\r\n");
+    // remove trailing space
+    char* tempStrP = tempStr;
+    while (*tempStrP == ' ')
+        ++tempStrP;
+
+    const uint32_t curTime = time(nullptr);
+    const uint32_t token = 0; //getParamsHash(curTime, temp, humidity, pressure, sensorId);
+    snprintf(tokenStr, sizeof(tokenStr), "%x", token);
+
+    // {"d":1495917000, "t":25.7, "h":51, "p":750, "sid":1003, "tok":"806be8"}
+    int res = snprintf(payload, sizeof(payload),
+        "{\"d\":%u,\"t\":%s,\"h\":%d,\"p\":%d,\"sid\":%d,\"tok\":\"%s\"}",
+        curTime, tempStrP, humidity, pressure, sensorId, tokenStr);
+
+    // WITHOUT TIME
+    //int res = snprintf(payload, sizeof(payload),
+    //    "{\"t\":%s,\"h\":%d,\"p\":%d,\"sid\":%d,\"tok\":\"%s\"}",
+    //    tempStrP, humidity, pressure, sensorId, tokenStr);
+
+    if (res < 0 || res >= sizeof(payload))
+    {
+        DebugPrint(debug, "Payload buffer is too small.\r\n");
         return;
     }

-    if (sqlCursor.execute(buf))
-    {
-        DebugPrint(debug, "SQL sent: %s\r\n", buf);
-    }
+    if (mqtt.connect(WiFi.macAddress().c_str()))
+    {
+        DebugPrint(debug, "Sending to mqtt: %s\r\n", payload);
+
+        if (!mqtt.publish(MQTT_TOPIC, payload))
+        {
+            DebugPrint(debug, "Cannot send to mqtt server: %s:%d\r\n", DATA_SERVER_ADDR, DATA_SERVER_PORT);
+        }
+    }
+    else
+    {
+        DebugPrint(debug, "Server unreachable: %s:%d\r\n", DATA_SERVER_ADDR, DATA_SERVER_PORT);
+    }
+
+    mqtt.disconnect();

     digitalWrite(led, 1);
 }
@@ -220,11 +277,11 @@
         DebugPrint(debug, "Error[%u]: ", error);
         switch (error)
         {
-            case OTA_AUTH_ERROR: DebugPrint(debug, "Auth Failed\r\n"); break;
-            case OTA_BEGIN_ERROR: DebugPrint(debug, "Begin Failed\r\n"); break;
+            case OTA_AUTH_ERROR:    DebugPrint(debug, "Auth Failed\r\n"); break;
+            case OTA_BEGIN_ERROR:   DebugPrint(debug, "Begin Failed\r\n"); break;
             case OTA_CONNECT_ERROR: DebugPrint(debug, "Connect Failed\r\n"); break;
             case OTA_RECEIVE_ERROR: DebugPrint(debug, "Receive Failed\r\n"); break;
-            case OTA_END_ERROR: DebugPrint(debug, "End Failed\r\n"); break;
+            case OTA_END_ERROR:     DebugPrint(debug, "End Failed\r\n"); break;
         }
     });
 }
@@ -235,7 +292,7 @@
     digitalWrite(led, 1);
     Serial.begin(115200);

-    sqlAddr.fromString(SQL_SERVER_ADDR);
+    mqtt.setCallback(mqttCallback);

     telnetServer.begin();
     telnetServer.setNoDelay(true);
@@ -279,25 +336,14 @@

         ArduinoOTA.begin();
     }
-
-    if (!sqlConn.connected())
-    {
-        DebugPrint(debug, "Connecting to SQL... ");
-        if (sqlConn.connect(sqlAddr, 3306, SQL_USER, SQL_PASS))
-        {
-            DebugPrint(debug, "OK\r\n");
-        }
-        else
-        {
-            DebugPrint(debug, "FAILED\r\n");
-        }
-    }
+
+    handleTelnet();

     // Time setting
     if (!timeIsSet)
     {
-        const int daySavingOffset = 3600;
-        const int timezoneSec = 2 * 3600 + daySavingOffset;
+        //const int daySavingOffset = 3600;
+        const int timezoneSec = 0; //2 * 3600 + daySavingOffset;

         configTime(timezoneSec, 0, "pool.ntp.org", "time.nist.gov");
         DebugPrint(debug, "Waiting for time");
@@ -305,9 +351,9 @@
         while (millis() < waitTill)
         {
             DebugPrint(debug, ".");
-            const unsigned long someTimeAfter1970 = (2016 - 1970) * 365 * 24 * 3600;
-            time_t now = time(nullptr);
-            if (now > someTimeAfter1970)
+            const unsigned long anyTimeAfter1970 = (2016 - 1970) * 365 * 24 * 3600;
+            const time_t now = time(nullptr);
+            if (now > anyTimeAfter1970)
             {
                 timeIsSet = true;
                 break;
@@ -317,7 +363,7 @@

         if (timeIsSet)
         {
-            time_t now = time(nullptr);
+            const time_t now = time(nullptr);
             DebugPrint(debug, " OK - %s\r\n", ctime(&now));
         }
         else
@@ -326,28 +372,27 @@
         }
     }

-    handleTelnet();
-
     httpServer.handleClient();

-    unsigned long curTime = millis();
+    const unsigned long curTime = millis();
     for (auto& sensor : sensors)
     {
         if (sensor.update(curTime))
         {
-            sendDataToSql(sensor);
+            sendDataToServer(sensor);
         }
     }

     ArduinoOTA.handle();

     /*static long lastUpdateTime = 0;
-    if (curTime - lastUpdateTime > 1000)
+    if (curTime - lastUpdateTime > 10000)
     {
         lastUpdateTime = curTime;
         //debug.printf("1Analog pins: %d, %d, %d\n2Analog pins: %d, %d, %d\n", analogRead(0), analogRead(1), analogRead(2));
         //debug.printf("12345\r\n12345\r\n12345\r\n");
         time_t now = time(nullptr);
         DebugPrint(debug, "cur time: %s", ctime(&now));
+        sendDataViaHttp(25.7, 35, 750, 1003);
     }*/
 }


Nuke each kind of external nmea data independently if no update for 30 seconds.

Decide if devise is active just by looking at GPS speed over ground.

--- device.ino
+++ device.ino
@@ -3,6 +3,10 @@
  FloatHub Arduino Code
  (c) 2011-2014 Modiot Labs
  (begun June 6, 2011)
+
+  July, 2015
+
+  Simplified active to just use GPS SOG. Had NMEA values get nuked based on timestamp.

   March 26, 2014
@@ -101,7 +105,7 @@
 //#define STRESS_MEMORY_ON
 //#define BYPASS_AES_ON
 //#define BARO_DEBUG_ON
-#define ACTIVE_DEBUG_ON
+//#define ACTIVE_DEBUG_ON

 /*
   Anything which changes what the Floathub Data Receiver (fdr) needs to do
@@ -164,7 +168,7 @@

 String        float_hub_id;			// default: outofbox
 String        float_hub_server;			// default: fdr.floathub.net
-unsigned int  float_hub_server_port;		// default: 44
+unsigned int  float_hub_server_port;		// default: 50003
 String        gprs_apn;				// default: apn.name
 String        gprs_username;			// default: username
 String        gprs_password;			// default: password
@@ -178,9 +182,11 @@
   Status LED's
 */

-#define RED_LED	    9
-#define YELLOW_LED  8
-#define GREEN_LED   6
+#define COM_LED_1   6
+#define COM_LED_2   7
+
+#define GPS_LED_1   8
+#define GPS_LED_2   9

 /*
    Some global Strings, character arrays
@@ -230,7 +236,8 @@
 unsigned long led_update_interval = 200;          	//  Update the LED's every 200 miliseconds
 unsigned long nmea_update_interval = 100;         	//  Update NMEA in serial line every 1/10 of a second
 unsigned long hardware_watchdog_interval = 120000; 	//  Do a hardware reset if we don't pat the dog every 2 minutes
-boolean green_led_state = false;         	  	//  For cycling on and off
+unsigned long nmea_sample_interval = 30000;		//  Nuke nmea data older than 30 seconds
+boolean com_led_state = false;         	  		//  For cycling on and off

 unsigned long sensor_previous_timestamp = 0;
 unsigned long gps_previous_timestamp = 0;
@@ -246,7 +253,11 @@
 unsigned long hardware_watchdog_timestamp = 0;
 unsigned long wifi_scan_previous_timestamp = 0;
 unsigned long wifi_read_previous_timestamp = 0;
-
+unsigned long nmea_speed_water_timestamp = 0;
+unsigned long nmea_depth_water_timestamp = 0;
+unsigned long nmea_wind_speed_timestamp = 0;
+unsigned long nmea_wind_direction_timestamp = 0;
+unsigned long nmea_water_temperature_timestamp = 0;

 /*
   Is the device currently "active" (i.e. is the vessel in movement and sending high frequency updates)?
@@ -356,14 +367,6 @@
 String         gps_hdp = "";          //  Horizontal dillution of precision (how good is our fix)
 String         gps_altitude = "";     //  We should be able to build a tide table out of this.

-/*
-  We keep a running average of position to do a little pythagorean calculation to tell if we're moving or not
-*/
-
-#define LOCATION_HISTORY_LENGTH 5
-
-float           latitude_history[LOCATION_HISTORY_LENGTH];
-float          longitude_history[LOCATION_HISTORY_LENGTH];

 /*
   Global variables for battery banks/chargers/pumps
@@ -380,6 +383,7 @@
 pump_state pump_one_state = off;
 pump_state pump_two_state = off;
 pump_state pump_three_state = off;
+

 /*
   Global variables for NMEA data
@@ -608,11 +612,11 @@
   EEPROM.write(40, '\0');

   //
-  //  Set default port
-  //
-
-  EEPROM.write(80, 0);
-  EEPROM.write(81, 44);
+  //  Set default port of 50003
+  //
+
+  EEPROM.write(80, 195);
+  EEPROM.write(81, 83);

   //
   //  set default gprs apn / wireless network name
@@ -967,23 +971,18 @@
   randomSeed(analogRead(0));

   //
-  //	We have no location history
-  //
-
-  for(i = 0; i < LOCATION_HISTORY_LENGTH; i++)
-  {
-    latitude_history[i] = 0.0;
-    longitude_history[i] = 0.0;
-  }
-
-  //
-  //  Setup LED pins, Red always on to show power
-  //
-
-  pinMode(RED_LED, OUTPUT);
-  pinMode(YELLOW_LED, OUTPUT);
-  pinMode(GREEN_LED, OUTPUT);
-  digitalWrite(RED_LED, HIGH);
+  //  Setup LED pins, initial is red on both
+  //
+
+  pinMode(GPS_LED_1, OUTPUT);
+  pinMode(GPS_LED_2, OUTPUT);
+  pinMode(COM_LED_1, OUTPUT);
+  pinMode(COM_LED_2, OUTPUT);
+
+  digitalWrite(GPS_LED_1, HIGH);
+  digitalWrite(GPS_LED_2, LOW);
+  digitalWrite(COM_LED_1, HIGH);
+  digitalWrite(COM_LED_2, LOW);

   //
@@ -1456,50 +1455,19 @@
   {
     gps_sog  = gps_read_buffer.substring(sog_start + 1, tmg_start);
     gps_bearing_true  = gps_read_buffer.substring(tmg_start + 1, date_start);
-
+
+    //
+    //   Use speed over gound to figure out if active. Used to have some
+    // really complicated math in here for running average of latitude and
+    // longitude, but this is far simpler and seems more reliable
+    //
+
     memset(temp_string, 0, 20 * sizeof(char));
-    gps_latitude.substring(0,2).toCharArray(temp_string, 3);
-    int_one = atoi(temp_string);
-
-    memset(temp_string, 0, 20 * sizeof(char));
-    gps_latitude.substring(3,11).toCharArray(temp_string, 9);
+    gps_sog.substring(0,gps_sog.length()).toCharArray(temp_string, 19);
     float_one = atof(temp_string);
-
-    float current_latitude = int_one + (float_one / 60.0);
-
-    memset(temp_string, 0, 20 * sizeof(char));
-    gps_longitude.substring(0,3).toCharArray(temp_string, 4);
-    int_one = atoi(temp_string);
-
-    memset(temp_string, 0, 20 * sizeof(char));
-    gps_longitude.substring(4,12).toCharArray(temp_string, 9);
-    float_one = atof(temp_string);
-
-    float current_longitude = int_one + (float_one / 60.0);
-
-
-    //
-    //  Calculate average of past positions
-    //
-
-    float average_latitude = 0.0;
-    float average_longitude = 0.0;
-    for(i = 0; i < LOCATION_HISTORY_LENGTH; i++)
-    {
-      average_latitude += latitude_history[i];
-      average_longitude += longitude_history[i];
-    }
-
-    average_latitude = average_latitude / ((float) LOCATION_HISTORY_LENGTH);
-    average_longitude = average_longitude / ((float) LOCATION_HISTORY_LENGTH);
-
-    //
-    //  Find pythagorean distance from average
-    //
-
-    float distance = sqrt(pow(average_latitude - current_latitude, 2) + pow(average_longitude - current_longitude, 2));
-
-    if(distance > 0.0001)  //  1/10,000th of a degree is roughly 35 feet
+
+    //if(float_one > 0.0)  //  Always active for debugging
+    if(float_one > 0.25)  //  Moving faster than a 1/4 knot?
     {
       #ifdef ACTIVE_DEBUG_ON
       debug_info(F("active: ON"));
@@ -1513,28 +1481,14 @@
       #endif
       currently_active = false;
     }
-
-
-    //
-    //  Slide averages
-    //
-
-    for(i = 0; i < LOCATION_HISTORY_LENGTH - 1; i++)
-    {
-      latitude_history[i] = latitude_history[i + 1];
-      longitude_history[i] = longitude_history[i + 1];
-    }
-    latitude_history[LOCATION_HISTORY_LENGTH - 1] = current_latitude;
-    longitude_history[LOCATION_HISTORY_LENGTH - 1] = current_longitude;
   }
   else
   {
-      #ifdef ACTIVE_DEBUG_ON
-      debug_info(F("active: OFF BGPS"));
-      #endif
+    #ifdef ACTIVE_DEBUG_ON
+    debug_info(F("active: OFF BGPS"));
+    #endif
     currently_active = false;
   }
-
 }

 void parse_gps_buffer_as_gga()
@@ -1767,6 +1721,9 @@
 void individual_pump_read(int pump_number, pump_state &state, int analog_input)
 {
   float pump_value = analogRead(analog_input) / 37.213;
+  #ifdef PUMP_DEBUG_ON
+  debug_info("Pump " + String(pump_number) + " on input " + String(analog_input) + " reads ", pump_value);
+  #endif
   if(pump_value > 2.0)
   {
      if(state == unknown)
@@ -2420,10 +2377,12 @@

   if(detailed_state_count > pump_state_count)
   {
+    debug_info(F("ATSL: d"));
     pop_off_detailed_message();
   }
   else
   {
+    debug_info(F("ATSL: p"));
     pop_off_pump_message();
   }
 }
@@ -2884,8 +2843,10 @@
   plain[1] = '\n';
   if(cc3000_client.write(plain, 2) != 2)
   {
+    debug_info(F("ATSL: \r\n fail"));
     return false;
   }
+  debug_info(F("ATSL: \r\n good"));
   return true;
 }

@@ -2913,6 +2874,21 @@
 }
 */

+void ATSL_debug_out_latest_message_send()
+{
+    Serial.println(F("ATSL start"));
+    for(i = 0; i < latest_message_to_send.length(); i = i + 1)
+    {
+      Serial.print(latest_message_to_send.charAt(i));
+    }
+    Serial.println();
+    Serial.println(F("ATSL end"));
+}
+
+
+
+
+
 void wifi_read()
 {
   if(gprs_or_wifi_communications_on == false)
@@ -2952,6 +2928,8 @@
     {
       if(open_fdr())
       {
+        debug_info("ATSLL: ", (int) latest_message_to_send.length());
+        ATSL_debug_out_latest_message_send();
         if(push_latest_message_out_socket())
         {
           #ifdef WIFI_DEBUG_ON
@@ -2995,6 +2973,8 @@
       pop_off_message_queue();
       if(latest_message_to_send.length() > 0)
       {
+        debug_info("ATSLL: ", (int) latest_message_to_send.length());
+        ATSL_debug_out_latest_message_send();
         if(push_latest_message_out_socket())
         {
           #ifdef WIFI_DEBUG_ON
@@ -3764,43 +3744,50 @@

   if(gps_valid)
   {
-    digitalWrite(YELLOW_LED, HIGH);
+    digitalWrite(GPS_LED_1, LOW);
+    digitalWrite(GPS_LED_2, HIGH);
   }
   else
   {
-    digitalWrite(YELLOW_LED, LOW);
+    digitalWrite(GPS_LED_1, HIGH);
+    digitalWrite(GPS_LED_2, LOW);
   }

   if(gprs_or_wifi_communications_on == false)
   {
-    digitalWrite(GREEN_LED, LOW);
+    digitalWrite(COM_LED_1, HIGH);
+    digitalWrite(COM_LED_2, LOW);
     return;
   }

   #ifdef WIFI_NOT_CELL
-  if(cc3000.getStatus() == STATUS_CONNECTED)
+  if(cc3000.getStatus() == STATUS_CONNECTED && cc3000.checkDHCP())
   {
     if(wifi_communication_state == idle)
     {
-      digitalWrite(GREEN_LED, HIGH);
+      digitalWrite(COM_LED_1, LOW);
+      digitalWrite(COM_LED_2, HIGH);
     }
     else
     {
-      if(green_led_state == true)
+      if(com_led_state == true)
       {
-        digitalWrite(GREEN_LED, LOW);
-        green_led_state = false;
+        digitalWrite(COM_LED_1, LOW);
+        digitalWrite(COM_LED_2, HIGH);
+        com_led_state = false;
       }
       else
       {
-        digitalWrite(GREEN_LED, HIGH);
-        green_led_state = true;
+        digitalWrite(COM_LED_1, LOW);
+        digitalWrite(COM_LED_2, LOW);
+        com_led_state = true;
       }
     }
   }
   else
   {
-    digitalWrite(GREEN_LED, LOW);
+        digitalWrite(COM_LED_1, HIGH);
+        digitalWrite(COM_LED_2, LOW);
   }
   #else

@@ -3812,25 +3799,29 @@
   {
     if(gprs_communication_state == idle)
     {
-      digitalWrite(GREEN_LED, HIGH);
+        digitalWrite(COM_LED_1, LOW);
+        digitalWrite(COM_LED_2, HIGH);
     }
     else
     {
-      if(green_led_state == true)
+      if(com_led_state == true)
       {
-        digitalWrite(GREEN_LED, LOW);
-        green_led_state = false;
+        digitalWrite(COM_LED_1, LOW);
+        digitalWrite(COM_LED_2, HIGH);
+        com_led_state = false;
       }
       else
       {
-        digitalWrite(GREEN_LED, HIGH);
-        green_led_state = true;
+        digitalWrite(COM_LED_1, LOW);
+        digitalWrite(COM_LED_2, LOW);
+        com_led_state = true;
       }
     }
   }
   else
   {
-    digitalWrite(GREEN_LED, LOW);
+        digitalWrite(COM_LED_1, HIGH);
+        digitalWrite(COM_LED_2, LOW);
   }
   #endif
 }
@@ -3897,6 +3888,7 @@
     #ifdef NMEA_DEBUG_ON
     debug_info("NMEA d water:", nmea_depth_water);
     #endif
+    nmea_depth_water_timestamp = millis();
   }

   //
@@ -3909,6 +3901,7 @@
     #ifdef NMEA_DEBUG_ON
     debug_info("NMEA w temp:", nmea_water_temperature);
     #endif
+    nmea_water_temperature_timestamp = millis();
   }

   //
@@ -3920,6 +3913,7 @@
     #ifdef NMEA_DEBUG_ON
     debug_info("NMEA s water:", nmea_speed_water);
     #endif
+    nmea_speed_water_timestamp = millis();
   }

   //
@@ -3931,11 +3925,13 @@
     #ifdef NMEA_DEBUG_ON
     debug_info("NMEA w speed:", nmea_wind_speed);
     #endif
+    nmea_wind_speed_timestamp = millis();
     if(	popout_nmea_value("MWV", commas[0], commas[1], nmea_wind_direction))
     {
       #ifdef NMEA_DEBUG_ON
       debug_info("NMEA w direction:", nmea_wind_direction);
       #endif
+      nmea_wind_direction_timestamp = millis();
     }
   }
 }
@@ -4074,15 +4070,29 @@
 {
   //
   //	Can't have nmea values persisting long after they were read, so this
-  //	is called to nuke them after a console report
-  //
-
-  nmea_speed_water = -1.0;
-  nmea_depth_water = -1.0;
-  nmea_wind_speed = -1.0;
-  nmea_wind_direction = -1.0;
-  nmea_water_temperature = -1.0;
-
+  //	is called to nuke them if they are stale more than 30 seconds
+  //
+
+  if(millis() - nmea_speed_water_timestamp > nmea_sample_interval)
+  {
+    nmea_speed_water = -1.0;
+  }
+  if(millis() - nmea_depth_water_timestamp > nmea_sample_interval)
+  {
+    nmea_depth_water = -1.0;
+  }
+  if(millis() - nmea_wind_speed_timestamp > nmea_sample_interval)
+  {
+    nmea_wind_speed = -1.0;
+  }
+  if(millis() - nmea_wind_direction_timestamp > nmea_sample_interval)
+  {
+    nmea_wind_direction = -1.0;
+  }
+  if(millis() - nmea_water_temperature_timestamp > nmea_sample_interval)
+  {
+    nmea_water_temperature = -1.0;
+  }
 }

@@ -4204,13 +4214,15 @@

   #ifdef EXECUTION_PATH_DEBUG_ON
-  if(random(0,100) < 10)
-  {
-    digitalWrite(RED_LED, HIGH);
+  if(random(0,100) < 50)
+  {
+    digitalWrite(GPS_LED_1, HIGH);
+    digitalWrite(GPS_LED_2, LOW);
   }
   else
   {
-    digitalWrite(RED_LED, LOW);
+    digitalWrite(GPS_LED_1, LOW);
+    digitalWrite(GPS_LED_2, HIGH);
   }
   #endif
 }


Accidentally rolled back a fix from last branch. Corrected.

--- KSPboard.ino
+++ KSPboard.ino
@@ -209,6 +209,7 @@
   setupSerial();
   setupState();
   setupHelm();
+  setupOps();

   delay(DELAY_START);
 }


Power subsystems on and off as needed.

Power subsystems on and off as needed.

--- fed-arduino/fed-arduino.ino
+++ fed-arduino/fed-arduino.ino
@@ -55,6 +55,9 @@

 int logData() {
   String year, month, day, hour, minute, second;
+  power_twi_enable();
+  power_spi_enable();
+
   DateTime datetime = RTC.now();
   year = String(datetime.year(), DEC);
   month = String(datetime.month(), DEC);
@@ -82,6 +85,8 @@
     dataFile.println(timeElapsed);
     dataFile.close();
   }
+  power_twi_disable();
+  power_spi_disable();
 }

 void setMotorToTurn() {
@@ -115,6 +120,9 @@
     pinMode(i, INPUT_PULLUP);
   }
   ADCSRA = 0;  // disable ADC as we won't be using it
+  power_adc_disable(); // ADC converter
+  power_timer1_disable();// Timer 1
+  power_timer2_disable();// Timer 2

   Serial.begin(9600);
   Serial.println(F("Starting up..."));
@@ -255,6 +263,8 @@

 void enterSleep()
 {
+  power_usart0_disable();// Serial (USART)
+
   sleep_enable();

   attachInterrupt(0, pinInterrupt, RISING);
@@ -276,9 +286,8 @@
   /* The program will continue from here after the WDT timeout*/
   sleep_disable(); /* First thing to do is disable sleep. */

-  /* Re-enable the peripherals. */
-  power_all_enable();
-
+  /* Re-enable the serial. */
+  power_usart0_enable();
 }

 // Send the clear display command (0x76)


added support for 2x16 display (tested with JHD162a) removed fanStatus inverted fan output to match relay board

--- fancontrol.ino
+++ fancontrol.ino
@@ -7,18 +7,21 @@
  */

 #include <DHT.h>
+#include <LiquidCrystal.h>
 #include "humidity.h"

 // used sensor type
 #define SENSOR_TYPE DHT22
+// timeout between readings
+#define SENSOR_TIMEOUT 2000

 // minimum temperature to operate
 #define MIN_TEMP 10

 // input pin for inside sensor
-#define SENSOR_INSIDE_PIN 5
+#define SENSOR_INSIDE_PIN 6
 // input pin for outside sensor
-#define SENSOR_OUTSIDE_PIN 6
+#define SENSOR_OUTSIDE_PIN 7
 // output pin for fan
 #define FAN_PIN 8

@@ -32,15 +35,19 @@
 // inside sensor
 DHT dhtIn(SENSOR_INSIDE_PIN, SENSOR_TYPE);
 // outside
-DHT dhtOut(SENSOR_INSIDE_PIN, SENSOR_TYPE);
+DHT dhtOut(SENSOR_OUTSIDE_PIN, SENSOR_TYPE);
+
+// 2x16 display
+LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

 void setup() {
 	Serial.begin(9600);
 	dhtIn.begin();
 	dhtOut.begin();
+	lcd.begin(16, 2);
 	pinMode(FAN_PIN, OUTPUT);

-
+	// Header for serial data
 	Serial.println("Humidity based fan control");
 	Serial.println("Inside | Outside | State");
 }
@@ -53,6 +60,7 @@
 	int hIn = dhtIn.readHumidity();
 	int hOut = dhtOut.readHumidity();

+	// check for reading errors
 	if (isnan(tIn) || isnan(tOut) || isnan(hIn) || isnan(hOut)) {
 		Serial.println("Error while reading sensors");
 		return;
@@ -62,33 +70,65 @@
 	float humidIn = absoluteHumidity(hIn, tIn);
 	float humidOut = absoluteHumidity(hOut, tOut);

-	int fanState = LOW;
-
 	// simple state machine to provide easy extension and modification
 	switch (state) {
 		case STATE_IDLE:
-			fanState = LOW;
 			if (humidIn > humidOut && tOut > MIN_TEMP) {
 				state = STATE_ACTIVE;
 			}
 			break;
 		case STATE_ACTIVE:
-			fanState = HIGH;
 			if (humidIn <= humidOut || tOut <= MIN_TEMP) {
 				state = STATE_IDLE;
 			}
 			break;
 	}

-	digitalWrite(FAN_PIN, fanState);
+	// Relay module works inversed
+	digitalWrite(FAN_PIN, !state);

+	/********************************
+	 * Display output               *
+	 ********************************/
+	lcd.clear();

+	// inside humidity
+	lcd.setCursor(0, 0);
+	lcd.print("in: ");
+	// correct number alignment
+	if (humidIn < 10) {
+		lcd.print(" ");
+	}
+	lcd.print(humidIn);
+
+	// outside humidity
+	lcd.setCursor(0, 1);
+	lcd.print("out:");
+	// correct number alignment
+	if (humidOut < 10) {
+		lcd.print(" ");
+	}
+	lcd.print(humidOut);
+
+	// active state
+	if (state == STATE_ACTIVE) {
+		lcd.setCursor(10, 0);
+		lcd.print("active");
+	}
+	// outside lower than min temperature
+	if (tOut < MIN_TEMP) {
+		lcd.setCursor(12, 1);
+		lcd.print("cold");
+	}
+
+	// serial data output
 	Serial.print(humidIn);
 	Serial.print(" | ");
 	Serial.print(humidOut);
 	Serial.print(" | ");
 	Serial.println(state);

-	delay(2000);
+	// sensors can only be read every 2 seconds
+	delay(SENSOR_TIMEOUT);
 }


Update SW01_Humidity_Measurement.ino

Update SW01_Humidity_Measurement.ino

--- examples/SW01_Humidity_Measurement/SW01_Humidity_Measurement.ino
+++ examples/SW01_Humidity_Measurement/SW01_Humidity_Measurement.ino
@@ -45,7 +45,7 @@
 }

 void loop(){
-	// Create a variable to store the data read from SW03
+	// Create a variable to store the data read from SW01
 	float humidity;
 	humidity = 0;


add delay to secure example publish loop

--- examples/adafruitio_secure_esp8266/adafruitio_secure_esp8266.ino
+++ examples/adafruitio_secure_esp8266/adafruitio_secure_esp8266.ino
@@ -111,6 +111,9 @@
     Serial.println(F("OK!"));
   }

+  // wait a couple seconds to avoid rate limit
+  delay(2000);
+
 }


subscribe

subscribe

--- enviar/enviar.ino
+++ enviar/enviar.ino
@@ -32,10 +32,10 @@
       while (true) {
       Serial.println(TTS);
       if (TTS % 2) {
-       client.publish("teste", "digital reconhecida");
-      } else { client.publish("teste", "digital desconhecida");}
+       client.publish("fingerprint/receive", "digital reconhecida");
+      } else { client.publish("fingerprint/receive", "digital desconhecida");}
       delay(5000);
-      client.subscribe("inTopic");
+      client.subscribe("fingerprint/confirm");
       TTS++;
       }
       // ... and resubscribe


reformat

reformat

--- testing/arduino/ArduinoMotionSensorExample/AvrCopter.ino
+++ testing/arduino/ArduinoMotionSensorExample/AvrCopter.ino
@@ -14,12 +14,11 @@

 int ret;
 void setup() {
-	Fastwire::setup(400,0);
-	Serial.begin(38400);
-	ret = mympu_open(mpu_addr, 200, gyro_orientation);
-	Serial.print("MPU init: "); Serial.println(ret);
-	Serial.print("Free mem: "); Serial.println(freeRam());
-
+    Fastwire::setup(400,0);
+    Serial.begin(38400);
+    ret = mympu_open(mpu_addr, 200, gyro_orientation);
+    Serial.print("MPU init: "); Serial.println(ret);
+    Serial.print("Free mem: "); Serial.println(freeRam());
 }

 unsigned int c = 0; //cumulative number of successful MPU/DMP reads
@@ -28,85 +27,85 @@
 unsigned int err_o = 0; //cumulative number of MPU/DMP reads that had overflow bit set

 void loop() {
-	#if defined MPU9150 || defined MPU9250
-		ret = mympu_update_compass();
-	#endif
+    #if defined MPU9150 || defined MPU9250
+        ret = mympu_update_compass();
+    #endif

-	ret = mympu_update();
+    ret = mympu_update();

-	switch (ret) {
-		case 0: c++; break;
-		case 1: np++; return;
-		case 2: err_o++; return;
-		case 3: err_c++; return;
-		default:
-			Serial.print("READ ERROR!  ");
-			Serial.println(ret);
-			return;
-	}
+    switch (ret) {
+        case 0: c++; break;
+        case 1: np++; return;
+        case 2: err_o++; return;
+        case 3: err_c++; return;
+        default:
+            Serial.print("READ ERROR!  ");
+            Serial.println(ret);
+            return;
+    }

-	// Every 25 Packages go through this
-	if (!(c%25)) {
+    // Every 25 Packages go through this
+    if (!(c%25)) {

-		// IMU Type
-		#if defined MPU6050
-			Serial.print("MPU6050|");
-		#endif
+        // IMU Type
+        #if defined MPU6050
+            Serial.print("MPU6050|");
+        #endif

-		#if defined MPU9150
-			Serial.print("MPU9150|");
-		#endif
+        #if defined MPU9150
+            Serial.print("MPU9150|");
+        #endif

-		#if defined MPU6500
-			Serial.print("MPU6500|");
-		#endif
+        #if defined MPU6500
+            Serial.print("MPU6500|");
+        #endif

-		#if defined MPU9250
-			Serial.print("MPU9250|");
-		#endif
+        #if defined MPU9250
+            Serial.print("MPU9250|");
+        #endif

-		// No Package Count
-		Serial.print(np);
-		Serial.print("|");
+        // No Package Count
+        Serial.print(np);
+        Serial.print("|");

-		// Yaw, Pitch, Roll
-		Serial.print(mympu.ypr[0]);
-		Serial.print("|");
-		Serial.print(mympu.ypr[1]);
-		Serial.print("|");
-		Serial.print(mympu.ypr[2]);
-		Serial.print("|");
+        // Yaw, Pitch, Roll
+        Serial.print(mympu.ypr[0]);
+        Serial.print("|");
+        Serial.print(mympu.ypr[1]);
+        Serial.print("|");
+        Serial.print(mympu.ypr[2]);
+        Serial.print("|");

-		// Gyroscope
-		Serial.print(mympu.gyro[0]);
-		Serial.print("|");
-		Serial.print(mympu.gyro[1]);
-		Serial.print("|");
-		Serial.print(mympu.gyro[2]);
-		Serial.print("|");
+        // Gyroscope
+        Serial.print(mympu.gyro[0]);
+        Serial.print("|");
+        Serial.print(mympu.gyro[1]);
+        Serial.print("|");
+        Serial.print(mympu.gyro[2]);
+        Serial.print("|");

-		// Accelerometer
-		Serial.print(mympu.accel[0]);
-		Serial.print("|");
-		Serial.print(mympu.accel[1]);
-		Serial.print("|");
-		Serial.print(mympu.accel[2]);
-		Serial.print("|");
+        // Accelerometer
+        Serial.print(mympu.accel[0]);
+        Serial.print("|");
+        Serial.print(mympu.accel[1]);
+        Serial.print("|");
+        Serial.print(mympu.accel[2]);
+        Serial.print("|");

-		// Magnetometer / Compas
-		#if defined MPU9150 || defined MPU9250
-			Serial.print(mympu.comp[0]);
-			Serial.print("|");
-			Serial.print(mympu.comp[1]);
-			Serial.print("|");
-			Serial.print(mympu.comp[2]);
-			Serial.print("|");
-		#endif
-		#if !defined MPU9150 && !defined MPU9250
-			Serial.print("0|0|0");
-		#endif
+        // Magnetometer / Compas
+        #if defined MPU9150 || defined MPU9250
+            Serial.print(mympu.comp[0]);
+            Serial.print("|");
+            Serial.print(mympu.comp[1]);
+            Serial.print("|");
+            Serial.print(mympu.comp[2]);
+            Serial.print("|");
+        #endif
+        #if !defined MPU9150 && !defined MPU9250
+            Serial.print("0|0|0");
+        #endif

-		Serial.println("");
-	}
+        Serial.println("");
+    }
 }


update TOC

update TOC

--- build/shared/examples/examples.ino
+++ build/shared/examples/examples.ino
@@ -11,10 +11,10 @@

 SETUP
 If this is your first time using the Papilio ZAP IDE then please take some time to install Xilinx's ISE software and setup the environment.
-
+	http://gadgetfactory.net/learn/2013/10/23/install-xilinxs-free-ise-webpack/
 LEARN
 To discover new tutorials for DesignLab visit:
-http://learn.gadgetfactory.net
+	http://learn.gadgetfactory.net

 USAGE
 Start with any of the example projects linked below or create a new project with the Papilio/New Papilio Project menu.


Apply "indent -kr -i2 -nut" to format whitespace roughly to the arduino standard

--- V1_0.ino
+++ V1_0.ino
@@ -4,11 +4,11 @@
 #include <SPI.h>
 #include <RFM22.h>
 #include <TinyGPS.h>
-
-#define ASCII 7          // ASCII 7 or 8
-#define STOPBITS 2       // Either 1 or 2
-#define TXDELAY 0        // Delay between sentence TX's
-#define RTTY_BAUD 50    // Baud rate for use with RFM22B Max = 600
+
+#define ASCII 7                 // ASCII 7 or 8
+#define STOPBITS 2              // Either 1 or 2
+#define TXDELAY 0               // Delay between sentence TX's
+#define RTTY_BAUD 50            // Baud rate for use with RFM22B Max = 600
 #define RADIO_FREQUENCY 434.160

@@ -16,17 +16,17 @@
 #define RFM22B_PIN 10
 #define LED 7

-char callsign[8] = "pFALCON"; //Callsign
+char callsign[8] = "pFALCON";   //Callsign

 char datastring[80];
 char txstring[80];
-volatile int txstatus=1;
-volatile int txstringlength=0;
+volatile int txstatus = 1;
+volatile int txstringlength = 0;
 volatile char txc;
 volatile int txi;
 volatile int txj;
-unsigned int count=0;
-
+unsigned int count = 0;
+
 TinyGPS gps;
 rfm22 radio1(RFM22B_PIN);

@@ -40,14 +40,14 @@

 float flat, flon = 0;
 unsigned long age;
-char latbuf[12] = "0", lonbuf[12] = "0" ,altbuf[12] = "0";
-int hour = 0 , minute = 0 , second = 0, oldsecond = 0, sats = 0;
+char latbuf[12] = "0", lonbuf[12] = "0", altbuf[12] = "0";
+int hour = 0, minute = 0, second = 0, oldsecond = 0, sats = 0;
 unsigned long date, time;
 long int ialt = 123;

 long int ticks = 1;
-
-byte gps_set_sucess = 0 ;
+
+byte gps_set_sucess = 0;

 bool newData = false;

@@ -57,284 +57,266 @@
 bool reinit_done = false;
 int reinitcnt = 8;
 int reinitcntr = 0;
-
+
 void setup()
-{
-   pinMode(LED,OUTPUT);
-   digitalWrite(LED, LOW);
-   delay(500);
-   digitalWrite(LED, HIGH);
-   delay(500);
-
-    initialise_interrupt();
-
-    Serial.begin(9600);
-
-    //Setup GPS
-    uint8_t setNav[] = {
-      0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x05, 0x00, 0xFA,
-    0x00, 0xFA, 0x00, 0x64, 0x00, 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0xDC};
-
-    uint8_t ecoMode[] = {0xB5, 0x62, 0x06, 0x11, 0x02, 0x00, 0x00, 0x04, 0x1D, 0x85};
-
-    while(!gps_set_sucess)
-    {
-      sendUBX(setNav, sizeof(setNav)/sizeof(uint8_t));
-      gps_set_sucess=getUBX_ACK(setNav);
-      /*sendUBX(ecoMode, sizeof(ecoMode)/sizeof(uint8_t));
-      gps_set_sucess&=getUBX_ACK(ecoMode);*/
-    }
-    gps_set_sucess=0;
-
-   digitalWrite(LED, LOW);
-   delay(500);
-   digitalWrite(LED, HIGH);
-   delay(500);
-   digitalWrite(LED, LOW);
-   delay(500);
-   digitalWrite(LED, HIGH);
-   delay(500);
-   digitalWrite(LED, LOW);
-
-    while(sats < 6 && flat == 0)
-    {
-      while(Serial.available())
-      {
+{
+  pinMode(LED, OUTPUT);
+  digitalWrite(LED, LOW);
+  delay(500);
+  digitalWrite(LED, HIGH);
+  delay(500);
+
+  initialise_interrupt();
+
+  Serial.begin(9600);
+
+  //Setup GPS
+  uint8_t setNav[] = {
+    0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x06, 0x03, 0x00, 0x00,
+        0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x05, 0x00, 0xFA,
+    0x00, 0xFA, 0x00, 0x64, 0x00, 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0xDC
+  };
+
+  uint8_t ecoMode[] =
+      { 0xB5, 0x62, 0x06, 0x11, 0x02, 0x00, 0x00, 0x04, 0x1D, 0x85 };
+
+  while (!gps_set_sucess) {
+    sendUBX(setNav, sizeof(setNav) / sizeof(uint8_t));
+    gps_set_sucess = getUBX_ACK(setNav);
+    /*sendUBX(ecoMode, sizeof(ecoMode)/sizeof(uint8_t));
+       gps_set_sucess&=getUBX_ACK(ecoMode); */
+  }
+  gps_set_sucess = 0;
+
+  digitalWrite(LED, LOW);
+  delay(500);
+  digitalWrite(LED, HIGH);
+  delay(500);
+  digitalWrite(LED, LOW);
+  delay(500);
+  digitalWrite(LED, HIGH);
+  delay(500);
+  digitalWrite(LED, LOW);
+
+  while (sats < 6 && flat == 0) {
+    while (Serial.available()) {
       char c = Serial.read();
       newData = gps.encode(c);
-        if(newData)
-        {
+      if (newData) {
         gps.f_get_position(&flat, &flon, &age);
         sats = gps.satellites();
+      }
+    }
+  }
+
+  setupGPSpower();
+  delay(1000);
+  //Setup RFM22B
+  setupRadio();
+}
+
+void loop()
+{
+  unsigned long chars;
+  unsigned short sentences, failed;
+
+  while (Serial.available()) {
+    char c = Serial.read();
+    if (gps.encode(c))          // Did a new valid sentence come in?
+      newData = true;
+  }
+
+  if (newData) {
+    digitalWrite(LED, HIGH);
+    gps.f_get_position(&flat, &flon, &age);
+    sats = gps.satellites();
+    dtostrf(flat, 10, 6, latbuf);
+    dtostrf(flon, 9, 6, lonbuf);
+    if (lonbuf[0] == ' ') {
+      lonbuf[0] = '+';
+    }
+    if (latbuf[0] == ' ') {
+      latbuf[0] = '+';
+    }
+    ialt = (gps.altitude() / 100);
+    if (ialt >= 0) {
+      itoa(ialt, altbuf, 10);
+    }
+
+    gps.get_datetime(&date, &time, &age);
+    hour = (time / 1000000);
+    minute = ((time - (hour * 1000000)) / 10000);
+    second = ((time - ((hour * 1000000) + (minute * 10000))));
+    second = second / 100;
+
+    sensorValue = analogRead(analogInPin);
+    actualValue = (sensorValue / 1023.00) * divider;
+    v1 = actualValue;
+    v2 = (actualValue - v1) * 100;
+    snprintf(voltage, sizeof(voltage), "%i.%02i", v1, v2);
+
+    cBusy = true;
+    sprintf(datastring, "$$$$%s,%li,%02i:%02i:%02i,%s,%s,%s,%i,%s",
+            callsign, ticks, hour, minute, second, latbuf, lonbuf, altbuf,
+            sats, voltage);
+    unsigned int CHECKSUM = gps_CRC16_checksum(datastring);     // Calculates the checksum for this datastring
+    char checksum_str[7];
+    sprintf(checksum_str, "*%04X\n", CHECKSUM);
+    strcat(datastring, checksum_str);
+    cBusy = false;
+
+    gps.stats(&chars, &sentences, &failed);
+
+  } else {
+    digitalWrite(LED, LOW);
+  }
+  if (reinit == true) {
+    setupRadio();
+    reinit = false;
+  }
+
+}
+
+ISR(TIMER1_COMPA_vect)
+{
+  switch (txstatus) {
+  case 0:                      // This is the optional delay between transmissions.
+    txj++;
+    if (txj > (TXDELAY * RTTY_BAUD)) {
+      txj = 0;
+      txstatus = 1;
+    }
+    break;
+  case 1:                      // Initialise transmission, take a copy of the string so it doesn't change mid transmission.
+    if (reinit == false) {
+      if (cBusy == false) {
+        if (reinitcntr == reinitcnt) {
+          reinit = true;
+          reinitcntr = 0;
+        } else {
+          strcpy(txstring, datastring);
+          txstringlength = strlen(txstring);
+          if (txstringlength != 0)
+            txj = 0;
+          ticks++;
+          txstatus = 2;
+          reinitcntr++;
         }
       }
     }
-
-    setupGPSpower();
-    delay(1000);
-    //Setup RFM22B
-    setupRadio();
-}
-
-void loop()
-{
-    unsigned long chars;
-    unsigned short sentences, failed;
-
-    while(Serial.available())
-    {
-    char c = Serial.read();
-    if (gps.encode(c)) // Did a new valid sentence come in?
-    newData = true;
-    }
-
-    if (newData)
-    {
-      digitalWrite(LED,HIGH);
-      gps.f_get_position(&flat, &flon, &age);
-      sats = gps.satellites();
-      dtostrf(flat, 10, 6, latbuf);
-      dtostrf(flon, 9, 6, lonbuf);
-      if(lonbuf[0] == ' ')
-            {
-              lonbuf[0] = '+';
-            }
-      if(latbuf[0] == ' ')
-            {
-              latbuf[0] = '+';
-            }
-      ialt = (gps.altitude() / 100);
-      if(ialt >= 0)
-      {
-        itoa(ialt, altbuf, 10);
-      }
-
-      gps.get_datetime(&date, &time, &age);
-              hour = (time / 1000000);
-              minute = ((time - (hour * 1000000)) / 10000);
-              second = ((time - ((hour * 1000000) + (minute * 10000))));
-              second = second / 100;
-
-        sensorValue = analogRead(analogInPin);
-        actualValue = (sensorValue / 1023.00) * divider;
-        v1 = actualValue;
-        v2 = (actualValue - v1) * 100;
-        snprintf(voltage, sizeof(voltage), "%i.%02i", v1, v2);
-
-    cBusy = true;
-    sprintf(datastring,"$$$$%s,%li,%02i:%02i:%02i,%s,%s,%s,%i,%s",callsign,ticks,hour,minute,second,latbuf,lonbuf,altbuf,sats,voltage);
-    unsigned int CHECKSUM = gps_CRC16_checksum(datastring);  // Calculates the checksum for this datastring
-    char checksum_str[7];
-    sprintf(checksum_str, "*%04X\n", CHECKSUM);
-    strcat(datastring,checksum_str);
-    cBusy = false;
-
-    gps.stats(&chars, &sentences, &failed);
-
-  }
-  else
-  {
-    digitalWrite(LED,LOW);
-  }
-  if(reinit == true)
-  {
-    setupRadio();
-    reinit = false;
-  }
-
-}
-
-ISR(TIMER1_COMPA_vect)
-{
-  switch(txstatus) {
-  case 0: // This is the optional delay between transmissions.
-    txj++;
-    if(txj>(TXDELAY*RTTY_BAUD)) {
-      txj=0;
-      txstatus=1;
-    }
     break;
-  case 1: // Initialise transmission, take a copy of the string so it doesn't change mid transmission.
-  if(reinit == false)
-  {
-    if(cBusy == false)
-    {
-    if(reinitcntr == reinitcnt)
-    {
-      reinit = true;
-      reinitcntr = 0;
-    }
-    else
-    {
-      strcpy(txstring,datastring);
-      txstringlength=strlen(txstring);
-      if(txstringlength != 0)
-      txj=0;
-      ticks++;
-      txstatus=2;
-      reinitcntr++;
-    }
-    }
-   }
-    break;
-  case 2: // Grab a char and lets go transmit it.
-    if ( txj < txstringlength)
-    {
+  case 2:                      // Grab a char and lets go transmit it.
+    if (txj < txstringlength) {
       txc = txstring[txj];
       txj++;
-      txstatus=3;
-      rtty_txbit (0); // Start Bit;
-      txi=0;
-    }
-    else
-    {
-      txstatus=0; // Should be finished
-      txj=0;
+      txstatus = 3;
+      rtty_txbit(0);            // Start Bit;
+      txi = 0;
+    } else {
+      txstatus = 0;             // Should be finished
+      txj = 0;
     }
     break;
   case 3:
-    if(txi<ASCII)
-    {
+    if (txi < ASCII) {
       txi++;
-      if (txc & 1) rtty_txbit(1);
-      else rtty_txbit(0);
+      if (txc & 1)
+        rtty_txbit(1);
+      else
+        rtty_txbit(0);
       txc = txc >> 1;
       break;
-    }
-    else
-    {
-      rtty_txbit (1); // Stop Bit
-      txstatus=4;
-      txi=0;
+    } else {
+      rtty_txbit(1);            // Stop Bit
+      txstatus = 4;
+      txi = 0;
       break;
     }
   case 4:
-    if(STOPBITS==2)
-    {
-      rtty_txbit (1); // Stop Bit
-      txstatus=2;
+    if (STOPBITS == 2) {
+      rtty_txbit(1);            // Stop Bit
+      txstatus = 2;
       break;
-    }
-    else
-    {
-      txstatus=2;
+    } else {
+      txstatus = 2;
       break;
     }
-
-  }
-}
-
-void rtty_txbit (int bit)
-{
-  if (bit)
-  {
-    radio1.write(0x73,0x03); // High
-  }
-  else
-  {
-    radio1.write(0x73,0x00); // Low
-  }
-}
-
-void setupGPSpower() {
+
+  }
+}
+
+void rtty_txbit(int bit)
+{
+  if (bit) {
+    radio1.write(0x73, 0x03);   // High
+  } else {
+    radio1.write(0x73, 0x00);   // Low
+  }
+}
+
+void setupGPSpower()
+{
   //Set GPS ot Power Save Mode
-  uint8_t setPSM[] = { 0xB5, 0x62, 0x06, 0x11, 0x02, 0x00, 0x08, 0x01, 0x22, 0x92 }; // Setup for Power Save Mode (Default Cyclic 1s)
-
-  sendUBX(setPSM, sizeof(setPSM)/sizeof(uint8_t));
-}
-
-void setupRadio(){
-  pinMode(RFM22B_SDN, OUTPUT);    // RFM22B SDN is on ARDUINO A3
+  uint8_t setPSM[] = { 0xB5, 0x62, 0x06, 0x11, 0x02, 0x00, 0x08, 0x01, 0x22, 0x92 };    // Setup for Power Save Mode (Default Cyclic 1s)
+
+  sendUBX(setPSM, sizeof(setPSM) / sizeof(uint8_t));
+}
+
+void setupRadio()
+{
+  pinMode(RFM22B_SDN, OUTPUT);  // RFM22B SDN is on ARDUINO A3
   digitalWrite(RFM22B_SDN, LOW);
   delay(1000);
   rfm22::initSPI();
   radio1.init();
-  radio1.write(0x71, 0x00); // unmodulated carrier
+  radio1.write(0x71, 0x00);     // unmodulated carrier
   //This sets up the GPIOs to automatically switch the antenna depending on Tx or Rx state, only needs to be done at start up
-  radio1.write(0x0b,0x12);
-  radio1.write(0x0c,0x15);
+  radio1.write(0x0b, 0x12);
+  radio1.write(0x0c, 0x15);
   radio1.setFrequency(RADIO_FREQUENCY);
-  radio1.write(0x6D, 0x04);// turn tx low power 11db
+  radio1.write(0x6D, 0x04);     // turn tx low power 11db
   radio1.write(0x07, 0x08);
   delay(500);
 }
-
-uint16_t gps_CRC16_checksum (char *string)
+
+uint16_t gps_CRC16_checksum(char *string)
 {
   size_t i;
   uint16_t crc;
   uint8_t c;
-
+
   crc = 0xFFFF;
-
+
   // Calculate checksum ignoring the first four $s
-  for (i = 4; i < strlen(string); i++)
-  {
+  for (i = 4; i < strlen(string); i++) {
     c = string[i];
-    crc = _crc_xmodem_update (crc, c);
-  }
-
+    crc = _crc_xmodem_update(crc, c);
+  }
+
   return crc;
-}
+}
+
 void initialise_interrupt()
 {
   // initialize Timer1
-  cli();          // disable global interrupts
-  TCCR1A = 0;     // set entire TCCR1A register to 0
-  TCCR1B = 0;     // same for TCCR1B
-  OCR1A = F_CPU / 1024 / RTTY_BAUD - 1;  // set compare match register to desired timer count:
-  TCCR1B |= (1 << WGM12);   // turn on CTC mode:
+  cli();                        // disable global interrupts
+  TCCR1A = 0;                   // set entire TCCR1A register to 0
+  TCCR1B = 0;                   // same for TCCR1B
+  OCR1A = F_CPU / 1024 / RTTY_BAUD - 1; // set compare match register to desired timer count:
+  TCCR1B |= (1 << WGM12);       // turn on CTC mode:
   // Set CS10 and CS12 bits for:
   TCCR1B |= (1 << CS10);
   TCCR1B |= (1 << CS12);
   // enable timer compare interrupt:
   TIMSK1 |= (1 << OCIE1A);
-  sei();          // enable global interrupts
+  sei();                        // enable global interrupts
 }

 // Send a byte array of UBX protocol to the GPS
-void sendUBX(uint8_t *MSG, uint8_t len) {
-  for(int i=0; i<len; i++) {
+void sendUBX(uint8_t * MSG, uint8_t len)
+{
+  for (int i = 0; i < len; i++) {
     Serial.write(MSG[i]);
     //mySerial.print(MSG[i], HEX);
   }
@@ -342,59 +324,57 @@
 }

 // Calculate expected UBX ACK packet and parse UBX response from GPS
-boolean getUBX_ACK(uint8_t *MSG) {
+boolean getUBX_ACK(uint8_t * MSG)
+{
   uint8_t b;
   uint8_t ackByteID = 0;
   uint8_t ackPacket[10];
   unsigned long startTime = millis();
   //mySerial.print(" * Reading ACK response: ");
-
+
   // Construct the expected ACK packet
-  ackPacket[0] = 0xB5;	// header
-  ackPacket[1] = 0x62;	// header
-  ackPacket[2] = 0x05;	// class
-  ackPacket[3] = 0x01;	// id
-  ackPacket[4] = 0x02;	// length
+  ackPacket[0] = 0xB5;          // header
+  ackPacket[1] = 0x62;          // header
+  ackPacket[2] = 0x05;          // class
+  ackPacket[3] = 0x01;          // id
+  ackPacket[4] = 0x02;          // length
   ackPacket[5] = 0x00;
-  ackPacket[6] = MSG[2];	// ACK class
-  ackPacket[7] = MSG[3];	// ACK id
-  ackPacket[8] = 0;		// CK_A
-  ackPacket[9] = 0;		// CK_B
-
+  ackPacket[6] = MSG[2];        // ACK class
+  ackPacket[7] = MSG[3];        // ACK id
+  ackPacket[8] = 0;             // CK_A
+  ackPacket[9] = 0;             // CK_B
+
   // Calculate the checksums
-  for (uint8_t i=2; i<8; i++) {
+  for (uint8_t i = 2; i < 8; i++) {
     ackPacket[8] = ackPacket[8] + ackPacket[i];
     ackPacket[9] = ackPacket[9] + ackPacket[8];
   }
-
+
   while (1) {
-
+
     // Test for success
     if (ackByteID > 9) {
       // All packets in order!
       //mySerial.println(" (SUCCESS!)");
       return true;
     }
-
     // Timeout if no valid response in 3 seconds
-    if (millis() - startTime > 3000) {
+    if (millis() - startTime > 3000) {
       //mySerial.println(" (FAILED!)");
       return false;
     }
-
     // Make sure data is available to read
     if (Serial.available()) {
       b = Serial.read();
-
+
       // Check that bytes arrive in sequence as per expected ACK packet
-      if (b == ackPacket[ackByteID]) {
+      if (b == ackPacket[ackByteID]) {
         ackByteID++;
         //mySerial.print(b, HEX);
-      }
-      else {
-        ackByteID = 0;	// Reset and look again, invalid order
+      } else {
+        ackByteID = 0;          // Reset and look again, invalid order
       }
-
-    }
-  }
-}
+
+    }
+  }
+}


Update SW01_Temperature_Measurement.ino

Update SW01_Temperature_Measurement.ino

--- examples/SW01_Temperature_Measurement/SW01_Temperature_Measurement.ino
+++ examples/SW01_Temperature_Measurement/SW01_Temperature_Measurement.ino
@@ -45,7 +45,7 @@
 }

 void loop(){
-	// Create a variable to store the data read from SW03
+	// Create a variable to store the data read from SW01
 	float temperature;
 	temperature = 0;


MAJ : des pin pour le fonctionnement des deux drivers

--- Asservissement/TestDriver/TestDriver1.0/TestDriver1.0.ino
+++ Asservissement/TestDriver/TestDriver1.0/TestDriver1.0.ino
@@ -1,32 +1,48 @@
- int pwm1 =3; // Attention sur Due PWM ou Pwm sont des keyword -> donc ne pas les utiliser pour des nom de variable
- const int pwm2 = 6;
- int IN1 = 50;
- int IN2 = 49;
+  int MotorR =3; // Attention sur Due PWM ou Pwm sont des keyword -> donc ne pas les utiliser pour des nom de variable
+  int MotorL = 6;
+  int IN1MotorL = 22;
+  int IN2MotorL = 21;
+  int IN1MotorR = 52;
+  int IN2MotorR = 53;
+

 void setup() {
-  pinMode(pwm1,OUTPUT);
-  pinMode(pwm2,OUTPUT);
-  pinMode(IN1,OUTPUT);
-  pinMode(IN2,OUTPUT);
+  pinMode(MotorR,OUTPUT);
+  pinMode(MotorL,OUTPUT);
+  pinMode(IN1MotorR,OUTPUT);
+  pinMode(IN2MotorR,OUTPUT);
+  pinMode(IN1MotorL,OUTPUT);
+  pinMode(IN2MotorL,OUTPUT);
   //analogWriteResolution(8);// seulement sur Arduino Due pour gere la Resolution du convertisseur DAC
 }

 void loop() {
-  digitalWrite(IN1,LOW);
-  digitalWrite(IN2,LOW);
-  delay(2000);
-  digitalWrite(IN1,LOW);
-  digitalWrite(IN2,HIGH);
-  analogWrite(pwm1,10);
-  analogWrite(pwm2,10);
-  delay(5000);
-  digitalWrite(IN1,LOW);
-  digitalWrite(IN2,LOW);
-  delay(2000);
-  digitalWrite(IN1,HIGH);
-  digitalWrite(IN2,LOW);
-  analogWrite(pwm1,10);
-  analogWrite(pwm2,10);
-  delay(5000);
-
+  /*digitalWrite(IN1MotorR,LOW);
+  digitalWrite(IN2MotorR,LOW);
+  digitalWrite(IN1MotorL,LOW);
+  digitalWrite(IN2MotorL,LOW);
+  analogWrite(MotorR,10);
+  analogWrite(MotorL,10);*/
+  //delay(500);
+  digitalWrite(IN1MotorR,HIGH);
+  digitalWrite(IN2MotorR,LOW);
+  digitalWrite(IN1MotorL,HIGH);
+  digitalWrite(IN2MotorL,LOW);
+  analogWrite(MotorR,10);
+  analogWrite(MotorL,10);
+  /*delay(1000);
+  digitalWrite(IN1MotorR,LOW);
+  digitalWrite(IN2MotorR,LOW);
+  digitalWrite(IN1MotorL,LOW);
+  digitalWrite(IN2MotorL,LOW);
+  analogWrite(MotorR,10);
+  analogWrite(MotorL,10);
+  delay(500);
+  digitalWrite(IN1MotorR,HIGH);
+  digitalWrite(IN2MotorR,LOW);
+  digitalWrite(IN1MotorL,HIGH);
+  digitalWrite(IN2MotorL,LOW);
+  analogWrite(MotorR,10);
+  analogWrite(MotorL,10);
+  delay(1000);*/
 }


show help any time a key is sent that is not a command

--- ampy.ino
+++ ampy.ino
@@ -45,7 +45,10 @@
       case 'o':
         body.playMotion(dance_o, 5);
         break;
-      case 'h':
+      case '\n':
+      case '\r':
+        break;
+      default:
         Serial.write("wsad - move\n");
         Serial.write("j - scan\n");
         Serial.write("k - home\n");


ManualEthernet.ino edited online with Bitbucket

--- examples/Transports/Advanced/ManualEthernet/ManualEthernet.ino
+++ examples/Transports/Advanced/ManualEthernet/ManualEthernet.ino
@@ -1,11 +1,11 @@
-#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
+#define BLYNK_PRINT Serial    // Comment this out to disable prints and have more memory available
 #include <SPI.h>
 #include <Ethernet.h>
 #include <EthernetClient.h>
 #include <BlynkSimpleEthernet.h>

-// Auth token you get from App
-char auth[] = "00000000000000000000000000000000";
+// You should get Auth Token in Blynk App. Go to the Project Settings (nut icon)
+char auth[] = "YourAuthToken";

 IPAddress server_ip (10, 0, 0, 10);


Jig can read accelerometer

Jig can read accelerometer

--- test_jig_lsm303c/test_jig_lsm303c.ino
+++ test_jig_lsm303c/test_jig_lsm303c.ino
@@ -24,6 +24,7 @@
 LSM303C myIMU;

 void setup() {
+  delay(1000);
   Serial.begin(115200);

   if (myIMU.begin(
@@ -101,6 +102,7 @@
     Serial.println("Failed setup.");
     while(1);
   }
+  delay(2000);
 }

 float x, y, z;
@@ -109,8 +111,17 @@
 {

   x = myIMU.readAccelX();
+  while (isnan(x)) {
+    x = myIMU.readAccelX();
+  }
   y = myIMU.readAccelY();
+  while (isnan(y)){
+    y = myIMU.readAccelY();
+  }
   z = myIMU.readAccelZ();
+  while (isnan(z)){
+    z = myIMU.readAccelZ();
+  }

   Serial.print(x);
   Serial.print(",");


Printing freq values

Printing freq values

--- scratchpad/CC1101ScanRSSI__MODIFIED/CC1101ScanRSSI__MODIFIED.ino
+++ scratchpad/CC1101ScanRSSI__MODIFIED/CC1101ScanRSSI__MODIFIED.ino
@@ -67,7 +67,11 @@
     average[j] = ( average[j] * count + tmpave ) / ( count + 1 );
     if ( tmpave > max[j] ) max[j] = tmpave;
     Serial.print("Chan ");Serial.print(channel[j]);
-    Serial.print(": current | cum ave | max (dbm) ");
+    Serial.print(": freq2 | freq1 | freq 0 | current | cum ave | max (dbm) ");
+    Serial.print(" "); Serial.print(freq2);
+    Serial.print(" | "); Serial.print(freq1);
+    Serial.print(" | "); Serial.print(freq0);
+    Serial.print(" | ");
     Serial.print( tmpave, 1 );Serial.print( " | " );
     Serial.print( average[j], 1 );Serial.print( " | " );
     Serial.print( max[j], 1 );Serial.println( "" );


Replaced

Replaced

--- knot/arduino/sensomatic.ino
+++ knot/arduino/sensomatic.ino
@@ -1,160 +0,0 @@
-#include <dht.h>
-#include <CmdMessenger.h>
-#include <avr/wdt.h>
-
-#define PIN_RX     1 // Serial
-#define PIN_TX     2 // Serial
-#define PIN_LED_G  3 // LED
-#define PIN_D4     4 // Button
-#define PIN_DHT    5 // Hum and Temp Sensor
-#define PIN_D6     6 // Button
-#define PIN_D7     7 // Button
-#define PIN_D8     8 // Button
-#define PIN_LED_B  9 // LED
-#define PIN_LED_R 10 // LED
-#define PIN_MOSI  11 // Programming
-#define PIN_MISO  12 // Programming
-#define PIN_SCK   13 // Programming
-#define PIN_A1    A1 //
-#define PIN_A2    A2 //
-#define PIN_LIGHT A3 // Light
-#define PIN_A4    A4 //
-#define PIN_A5    A5 //
-
-#define SAMPLE_DELAY    1000
-#define BUTTON_DELAY     500
-#define AVERAGE_COUNTER  100
-#define NUM_BUTTONS        4
-
-dht          DHT;
-CmdMessenger cmdMessenger = CmdMessenger(Serial, ',', ';');
-uint32_t     lastSampleTime;
-uint32_t     lastButtonTime[NUM_BUTTONS];
-
-enum{
-  kAcknowledge,
-  kError,
-  kSetRgb,
-  kSetR,
-  kSetG,
-  kSetB,
-  kGetTemp,
-  kGetHumidity,
-  kGetLight,
-  kTemp,
-  kHumidity,
-  kLight,
-  kButtonPressed,
-};
-
-void attachCommandCallbacks(){
-  cmdMessenger.attach(              OnUnknownCommand);
-  cmdMessenger.attach(kSetRgb,      OnSetRgb        );
-  cmdMessenger.attach(kSetR,        OnSetR          );
-  cmdMessenger.attach(kSetG,        OnSetG          );
-  cmdMessenger.attach(kSetB,        OnSetB          );
-  cmdMessenger.attach(kGetTemp,     OnGetTemp       );
-  cmdMessenger.attach(kGetHumidity, OnGetHumidity   );
-  cmdMessenger.attach(kGetLight,    OnGetLight      );
-}
-
-void OnUnknownCommand(){
-  cmdMessenger.sendCmd(kError,"Command without attached callback");
-}
-
-void OnSetRgb(){
-  int16_t r = cmdMessenger.readInt16Arg();
-  int16_t g = cmdMessenger.readInt16Arg();
-  int16_t b = cmdMessenger.readInt16Arg();
-
-  analogWrite(PIN_LED_R, r);
-  analogWrite(PIN_LED_G, g);
-  analogWrite(PIN_LED_B, b);
-
-  cmdMessenger.sendCmdStart(kAcknowledge);
-}
-
-void OnSetR(){
-  int16_t r = cmdMessenger.readInt16Arg();
-  analogWrite(PIN_LED_R, r);
-  cmdMessenger.sendCmd(kAcknowledge, r);
-}
-
-void OnSetG(){
-  int16_t g = cmdMessenger.readInt16Arg();
-  analogWrite(PIN_LED_G, g);
-  cmdMessenger.sendCmd(kAcknowledge, g);
-}
-
-void OnSetB(){
-  int16_t b = cmdMessenger.readInt16Arg();
-  analogWrite(PIN_LED_B, b);
-  cmdMessenger.sendCmd(kAcknowledge, b);
-}
-
-void checkSampleTime(){
-  if( (millis() - lastSampleTime) > SAMPLE_DELAY){
-    DHT.read22(PIN_DHT);
-    lastSampleTime = millis();
-  }
-}
-
-void OnGetTemp(){
-  checkSampleTime();
-  cmdMessenger.sendCmd(kTemp, DHT.temperature);
-}
-
-void OnGetHumidity(){
-  checkSampleTime();
-  cmdMessenger.sendCmd(kHumidity, DHT.humidity);
-}
-
-void OnGetLight(){
-  uint32_t light = 0;
-  for (uint16_t i = 0; i < AVERAGE_COUNTER; i++){
-    light += analogRead(PIN_LIGHT);
-  }
-  cmdMessenger.sendCmd(kLight, light / AVERAGE_COUNTER);
-}
-
-void setup() {
-  Serial.begin(9600);
-  cmdMessenger.printLfCr(true);
-  attachCommandCallbacks();
-  cmdMessenger.sendCmd(kAcknowledge, "Arduino ready!");
-  wdt_enable(WDTO_2S);
-  lastSampleTime = 0;
-  for(uint8_t i = 0; i < NUM_BUTTONS; i++){
-    lastButtonTime[i] = 0;
-  }
-  analogWrite(PIN_LED_R, 0);
-  analogWrite(PIN_LED_G, 0);
-  analogWrite(PIN_LED_B, 0);
-  pinMode(PIN_D4, INPUT_PULLUP);
-  pinMode(PIN_D6, INPUT_PULLUP);
-  pinMode(PIN_D7, INPUT_PULLUP);
-  pinMode(PIN_D8, INPUT_PULLUP);
-}
-
-void buttonCheck(uint16_t pin, uint8_t button){
-  if(!digitalRead(pin)) {
-    if( (millis() - lastButtonTime[button]) > BUTTON_DELAY){
-      cmdMessenger.sendCmd(kButtonPressed, button);
-      lastButtonTime[button] = millis();
-    }
-  }
-}
-
-void parseButtons(){
-  buttonCheck(PIN_D4, 0);
-  buttonCheck(PIN_D6, 1);
-  buttonCheck(PIN_D7, 2);
-  buttonCheck(PIN_D8, 3);
-}
-
-void loop() {
-  cmdMessenger.feedinSerialData();
-  parseButtons();
-  wdt_reset();
-}
-


updated offsets

updated offsets

--- chillduino.ino
+++ chillduino.ino
@@ -77,8 +77,8 @@
   pinMode(DEFROST, OUTPUT);

   chillduino
-    .setMinimumFreshFoodThermistorReading(286)
-    .setMaximumFreshFoodThermistorReading(331)
+    .setMinimumFreshFoodThermistorReading(243) //decrewsed set point
+    .setMaximumFreshFoodThermistorReading(350) //increased set point
     .setCompressorTicksPerDefrost(100 * TICKS_PER_HOUR)
     .setDefrostDurationInTicks(30 * TICKS_PER_MINUTE)
     .setMinimumTicksForCompressorChange(10 * TICKS_PER_MINUTE)


Add audio

Add audio

--- clock_base.ino
+++ clock_base.ino
@@ -6,16 +6,23 @@
  * /                              Last Updated January, 2019
  * /
 /********************************************************************************************/
+// TODO
+// * eeprom settings
+// * setting update ui
+// * alarm function and settings
+// * handle hour rollover screen issue

 #define build 1
 #define revision 6
-
+#define buzzer 10
+#define OCTAVE_OFFSET 0
+#define isdigit(n) (n >= '0' && n <= '9')
 #include <Wire.h>
 #include <LiquidCrystal_I2C.h>
 #include <RTClib.h>
 RTC_DS1307 RTC;
-// Set the pins on the I2C chip used for LCD connections
 LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
+
 // custom characters for time font
 byte x10[8] = {0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x07};// digit piece
 byte x11[8] = {0x00,0x00,0x00,0x00,0x00,0x1C,0x1C,0x1C};// digit piece
@@ -33,16 +40,12 @@
     SHOW_CUSTOM_TEXT,    // Displays the time and custom text from the serial port
     SHOW_SYSTEM_INFO,    // Displays System Information
 };
-// holds the current state of the clock
-states state;
-// holds the previous state of the clock
-// used to refresh the screen once when the mode changes
-states previousState;
+// holds the current and previous state of the clock
+states state, previousState;

 //////////////////////
 // Global Variables //
 //////////////////////
-
 // Button Pins
 int button1Pin = 2;
 int button2Pin = 3;
@@ -59,6 +62,14 @@
 // Time Display options (TODO Store in eeprom)
 bool showSeconds = true;
 bool militaryTime = false;
+// sound playback
+const int tonePin = buzzer;  // for rEDI board
+// These values can also be found as constants in the Tone library (Tone.h)
+int notes[] = { 0, 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494, 523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988, 1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976, 2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951};
+// alarms
+char *nokia = "NokiaTun:d=4,o=5,b=225:8e6,8d6,f#,g#,8c#6,8b,d,e,8b,8a,c#,e,2a";
+char *hamster_dance = "HamsterD:d=16,o=6,b=140:g#,g,8g#,8e,8e,e,8b5.,4b5,4g#,8b5,g#,8a,2b.,e7,c#7,b,c#7,b,g#,b,g#,f#,e,c#,e,f#,e,g#,b,g#,b,f#,e,8c#,2e";
+char *twentyfour_phone = "24Ctu:d=16,o=5,b=565:f6,p,f6,4p,p,f6,p,f6,2p,p,b6,p,b6,p,b6,p,b6,p,b,p,b,p,b,p,b,p,b,p,b,p,b,p,b,1p.,2p.,p,f6,p,f6,4p,p,f6,p,f6,2p,p,b6,p,b6,p,b6,p,b6,p,b,p,b,p,b,p,b,p,b,p,b,p,b,p,c";

 ///////////////////////
 // Setup - runs once //
@@ -75,6 +86,9 @@
     pinMode(button2Pin, INPUT_PULLUP);
     pinMode(button3Pin, INPUT_PULLUP);
     pinMode(button4Pin, INPUT_PULLUP);
+    // Set buzzer as an output
+    pinMode(buzzer, OUTPUT);
+    noTone (buzzer);
     // setup LCD  for 20 columns and 4 rows
     lcd.begin(20,4);
     // create custom characters for clock font
@@ -166,12 +180,19 @@
         // Button 2 - Green
         if (button2State == LOW) {
           Serial.println("Button 2 Pressed - Green");
+          delay(150);
+          play_rtttl(hamster_dance);
+          Serial.println("Done Playing Songs.");
           delay(500);
         }
         // Button 3 - Blue
         if (button3State == LOW) {
-          Serial.println("Button 3 Pressed - Blue");
-          delay(500);
+           Serial.println("Button 3 Pressed - Blue");
+           play_rtttl(twentyfour_phone);
+           delay(150);
+            play_rtttl(nokia);
+           delay(150);
+
         }
     }
     if (previousToggleState != button4State && (state == SHOW_TIME || state == SHOW_CUSTOM_TEXT)){
@@ -378,6 +399,7 @@
 // draw a loading screen
 void drawLoadingScreen()
 {
+
   lcd.clear();
   //drawSolidBorder();
   lcd.setCursor(1, 1);
@@ -487,6 +509,7 @@
       case 5: lcd.write(byte(2)); lcd.write(byte(2));
               lcd.setCursor(c,r+1); lcd.write(byte(4)); lcd.write(byte(2));
               lcd.setCursor(c,r+2); lcd.write(byte(2)); lcd.write(byte(3)); break;
+
       case 6: lcd.write(byte(1)); lcd.print(" ");
               lcd.setCursor(c,r+1); lcd.write(byte(4)); lcd.write(byte(2));
               lcd.setCursor(c,r+2); lcd.write(byte(4)); lcd.write(byte(3)); break;
@@ -536,3 +559,167 @@
   }
   return free_memory;
 }
+
+/////////////////////
+// Tones and Music //
+/////////////////////
+void play_rtttl(char *p)
+{
+  // Absolutely no error checking in here
+  byte default_dur = 4;
+  byte default_oct = 6;
+  int bpm = 63;
+  int num;
+  long wholenote;
+  long duration;
+  byte note;
+  byte scale;
+
+  // format: d=N,o=N,b=NNN:
+  // find the start (skip name, etc)
+
+  while(*p != ':') p++;    // ignore name
+  p++;                     // skip ':'
+
+  // get default duration
+  if(*p == 'd')
+  {
+    p++; p++;              // skip "d="
+    num = 0;
+    while(isdigit(*p))
+    {
+      num = (num * 10) + (*p++ - '0');
+    }
+    if(num > 0) default_dur = num;
+    p++;                   // skip comma
+  }
+
+  Serial.print("ddur: "); Serial.println(default_dur, 10);
+
+  // get default octave
+  if(*p == 'o')
+  {
+    p++; p++;              // skip "o="
+    num = *p++ - '0';
+    if(num >= 3 && num <=7) default_oct = num;
+    p++;                   // skip comma
+  }
+
+  Serial.print("doct: "); Serial.println(default_oct, 10);
+
+  // get BPM
+  if(*p == 'b')
+  {
+    p++; p++;              // skip "b="
+    num = 0;
+    while(isdigit(*p))
+    {
+      num = (num * 10) + (*p++ - '0');
+    }
+    bpm = num;
+    p++;                   // skip colon
+  }
+
+  Serial.print("bpm: "); Serial.println(bpm, 10);
+
+  // BPM usually expresses the number of quarter notes per minute
+  wholenote = (60 * 1000L / bpm) * 4;  // this is the time for whole note (in milliseconds)
+
+  Serial.print("wn: "); Serial.println(wholenote, 10);
+
+  // now begin note loop
+  while(*p)
+  {
+    // first, get note duration, if available
+    num = 0;
+    while(isdigit(*p))
+    {
+      num = (num * 10) + (*p++ - '0');
+    }
+
+    if(num) duration = wholenote / num;
+    else duration = wholenote / default_dur;  // we will need to check if we are a dotted note after
+
+    // now get the note
+    note = 0;
+
+    switch(*p)
+    {
+      case 'c':
+        note = 1;
+        break;
+      case 'd':
+        note = 3;
+        break;
+      case 'e':
+        note = 5;
+        break;
+      case 'f':
+        note = 6;
+        break;
+      case 'g':
+        note = 8;
+        break;
+      case 'a':
+        note = 10;
+        break;
+      case 'b':
+        note = 12;
+        break;
+      case 'p':
+      default:
+        note = 0;
+    }
+    p++;
+
+    // now, get optional '#' sharp
+    if(*p == '#')
+    {
+      note++;
+      p++;
+    }
+
+    // now, get optional '.' dotted note
+    if(*p == '.')
+    {
+      duration += duration/2;
+      p++;
+    }
+
+    // now, get scale
+    if(isdigit(*p))
+    {
+      scale = *p - '0';
+      p++;
+    }
+    else
+    {
+      scale = default_oct;
+    }
+
+    scale += OCTAVE_OFFSET;
+
+    if(*p == ',')
+      p++;       // skip comma for next note (or we may be at the end)
+
+    // now play the note
+    if(note)
+    {
+      Serial.print("Playing: ");
+      Serial.print(scale, 10); Serial.print(' ');
+      Serial.print(note, 10); Serial.print(" (");
+      Serial.print(notes[(scale - 4) * 12 + note], 10);
+      Serial.print(") ");
+      Serial.println(duration, 10);
+      tone(tonePin, notes[(scale - 4) * 12 + note]);
+      delay(duration);
+      noTone(tonePin);
+    }
+    else
+    {
+      Serial.print("Pausing: ");
+      Serial.println(duration, 10);
+      delay(duration);
+    }
+  }
+}


20150217.1238

--- cmdMULTIsens/src/sketch.ino
+++ cmdMULTIsens/src/sketch.ino
@@ -62,7 +62,7 @@
         Serial.println(" ");
         Serial.println("cmdMULTIsens help is underway!");
         Serial.println(" ");
-        Serial.println("A | a : All sensor and calculated values (T,S,H,D,E)")
+        Serial.println("A | a : All sensor and calculated values (T,S,H,D,E)");
         Serial.println("D | d : DHT22 calculated Dewpoint");
         Serial.println("E | e : DHT22 calculated Dewpoint2");
         Serial.println("H | h : DHT22 humidity");


verifying

verifying

--- arduino/neopixel_emote/neopixel_emote.ino
+++ arduino/neopixel_emote/neopixel_emote.ino
@@ -1,6 +1,6 @@
 #include <Adafruit_NeoPixel.h>
 #ifdef __AVR__
-  #include <avr/power.h>
+#include <avr/power.h>
 #endif

 #define PIN            6
@@ -10,7 +10,7 @@

 int rec_pixel = 8;
 int delayval = 50;
-char state = "d";
+char state = 'd';
 int health = 150;
 int range[] = {0,NUMPIXELS};
 String direction = "down";
@@ -25,197 +25,197 @@
 bool isrecording = false;

 void setup() {
-  Serial.begin(9600);
-  pixels.begin();
-  dreaming(); //initialize as dreaming
+    Serial.begin(9600);
+    pixels.begin();
+    dreaming(); //initialize as dreaming
 }

 void checkForUpdate() {
     if (Serial.available()) {
-      state = Serial.read();
-      switch (state) {
-        case 'd':
-          dreaming();
-          break;
-        case 'l':
-          listening();
-          break;
-        case 'c':
-          two_connected();
-          initial_connection();
-          break;
-        case 'r':
-          isrecording = true;
-          recording();
-          break;
-        case 's':
-          singing();
-          vibrate();
-          break;
-        case 'e':
-          isrecording = false;
-          break;
-         case 'u':
-          uploading();
-          break;
-         case 'h':
-          int days;
-          days = Serial.read();
-          health = 150 - days*50;
-          if (health < 20) {
-            health = 20;
-          }
-          break;
-        default:
-          dreaming();
-       }
+        state = Serial.read();
+        switch (state) {
+            case 'd':
+                dreaming();
+                break;
+            case 'l':
+                listening();
+                break;
+            case 'c':
+                two_connected();
+                initial_connection();
+                break;
+            case 'r':
+                isrecording = true;
+                recording();
+                break;
+            case 's':
+                singing();
+                // vibrate();
+                break;
+            case 'e':
+                isrecording = false;
+                break;
+            case 'u':
+                uploading();
+                break;
+            case 'h':
+                int days;
+                days = Serial.read();
+                health = 150 - days*50;
+                if (health < 20) {
+                    health = 20;
+                }
+                break;
+            default:
+                dreaming();
+        }
     }
 }

 void loop() {
-  checkForUpdate();
-  nextIntensity();
-  nextColor();
-
-  for(int i=range[0];i < range[1]; i++){
-    pixels.setPixelColor(i, pixels.Color(r_base*(intensity/100.0),g_base*(intensity/100.0),b_base*(intensity/100.0)));
+    checkForUpdate();
+    nextIntensity();
+    nextColor();
+
+    for(int i=range[0];i < range[1]; i++){
+        pixels.setPixelColor(i, pixels.Color(r_base*(intensity/100.0),g_base*(intensity/100.0),b_base*(intensity/100.0)));
+        if (colorChange) {
+            delay(30);
+        }
+        randomSpark(i);
+
+        //too hungry
+        if (health < 50) {
+            if (random(0,5) == 0) {
+                pixels.setPixelColor(i, pixels.Color(0,0,0));
+            }
+        }
+
+        //red recording light
+        if (isrecording) {
+            pixels.setPixelColor(rec_pixel, pixels.Color(255, 0, 0));
+            pixels.setPixelColor((rec_pixel + 1)%16, pixels.Color(255, 0, 0));
+            pixels.setPixelColor(rec_pixel - 1, pixels.Color(255, 0, 0));
+
+        }
+        pixels.show();
+        delay(delayval);
+    }
+}
+
+void randomSpark(int i) {
+    if (random(0,70) == 1) {
+        pixels.setPixelColor(i, pixels.Color(random(0,50),random(0,50), random(0,50)));
+    }
+}
+
+void nextIntensity() {
+    if (direction == "down") {
+        intensity = intensity - speed;
+    } else {
+        intensity = intensity + speed;
+    }
+    if (intensity > max) {
+        intensity = max;
+        direction = "down";
+    } else if (intensity < min) {
+        intensity = min;
+        direction = "up";
+    }
+}
+
+void nextColor() {
     if (colorChange) {
-      delay(30);
-    }
-    randomSpark(i);
-
-    //too hungry
-    if (health < 50) {
-      if (random(0,5) == 0) {
-        pixels.setPixelColor(i, pixels.Color(0,0,0));
-      }
-    }
-
-    //red recording light
-    if (isrecording) {
-      pixels.setPixelColor(rec_pixel, pixels.Color(255, 0, 0));
-      pixels.setPixelColor((rec_pixel + 1)%16, pixels.Color(255, 0, 0));
-      pixels.setPixelColor(rec_pixel - 1, pixels.Color(255, 0, 0));
-
-    }
-    pixels.show();
-    delay(delayval);
-  }
-}
-
-void randomSpark(int i) {
-  if (random(0,70) == 1) {
-    pixels.setPixelColor(i, pixels.Color(random(0,50),random(0,50), random(0,50)));
-  }
-}
-
-void nextIntensity() {
-  if (direction == "down") {
-    intensity = intensity - speed;
-  } else {
-    intensity = intensity + speed;
-  }
-  if (intensity > max) {
-    intensity = max;
-    direction = "down";
-  } else if (intensity < min) {
-    intensity = min;
-    direction = "up";
-  }
-}
-
-void nextColor() {
-  if (colorChange) {
-    r_base = r_base + random(-20, 20);
-    g_base = g_base + random(-20, 20);
-    b_base = b_base + random(-20, 20);
-  }
+        r_base = r_base + random(-20, 20);
+        g_base = g_base + random(-20, 20);
+        b_base = b_base + random(-20, 20);
+    }
 }

 void initial_connection() {
-  for(int i=0; i < 16; i++){
-    pixels.setPixelColor(i, pixels.Color(r_base*(intensity/100.0),g_base*(intensity/100.0),b_base*(intensity/100.0)));
-    pixels.show();
-  }
-
-  for (int r = 0; r < 5; r++) {
-      pixels.setPixelColor(5 + r, pixels.Color(0,0,0));
-      pixels.setPixelColor(5 - r, pixels.Color(0,0,0));
-      pixels.show();
-      delay(400);
-  }
+    for(int i=0; i < 16; i++){
+        pixels.setPixelColor(i, pixels.Color(r_base*(intensity/100.0),g_base*(intensity/100.0),b_base*(intensity/100.0)));
+        pixels.show();
+    }
+
+    for (int r = 0; r < 5; r++) {
+        pixels.setPixelColor(5 + r, pixels.Color(0,0,0));
+        pixels.setPixelColor(5 - r, pixels.Color(0,0,0));
+        pixels.show();
+        delay(400);
+    }
 }

 void dreaming() {
-     range[0] = 0;
-     range[1] = 16;
-     speed = 2;
-     max = min(150, health);
-     min = 0;
-     r_base = 0;
-     g_base = 50;
-     b_base = 30;
-     colorChange = false;
+    range[0] = 0;
+    range[1] = 16;
+    speed = 2;
+    max = min(150, health);
+    min = 0;
+    r_base = 0;
+    g_base = 50;
+    b_base = 30;
+    colorChange = false;
 }

 void two_connected() {
-     range[0] = 10;
-     range[1] = 16;
-     speed = 10;
-     max = min(200, health);
-     min = 20;
-     r_base = 75;
-     g_base = 40;
-     b_base = 0;
-     colorChange = false;
+    range[0] = 10;
+    range[1] = 16;
+    speed = 10;
+    max = min(200, health);
+    min = 20;
+    r_base = 75;
+    g_base = 40;
+    b_base = 0;
+    colorChange = false;
 }

 void recording() {
-     range[0] = 0;
-     range[1] = 16;
-     speed = 10;
-     max = min(200, health);
-     min = 20;
-     r_base = 50;
-     g_base = 30;
-     b_base = 40;
-     colorChange = false;
+    range[0] = 0;
+    range[1] = 16;
+    speed = 10;
+    max = min(200, health);
+    min = 20;
+    r_base = 50;
+    g_base = 30;
+    b_base = 40;
+    colorChange = false;
 }

 void singing() {
-     range[0] = 0;
-     range[1] = 16;
-     speed = 8;
-     max = min(200, health);
-     min = 20;
-     r_base = 10;
-     g_base = 70;
-     b_base = 0;
-     colorChange = true;
+    range[0] = 0;
+    range[1] = 16;
+    speed = 8;
+    max = min(200, health);
+    min = 20;
+    r_base = 10;
+    g_base = 70;
+    b_base = 0;
+    colorChange = true;
 }

 void listening() {
-     range[0] = 0;
-     range[1] = 16;
-     speed = 8;
-     max = min(200, health);
-     min = 20;
-     r_base = 70;
-     g_base = 70;
-     b_base = 70;
-     colorChange = true;
+    range[0] = 0;
+    range[1] = 16;
+    speed = 8;
+    max = min(200, health);
+    min = 20;
+    r_base = 70;
+    g_base = 70;
+    b_base = 70;
+    colorChange = true;
 }

 void uploading() {
-     range[0] = 10;
-     range[1] = 16;
-     speed = 15;
-     max = min(200, health);
-     min = 20;
-     r_base = 70;
-     g_base = 0;
-     b_base = 70;
-     colorChange = false;
-}
-
+    range[0] = 10;
+    range[1] = 16;
+    speed = 15;
+    max = min(200, health);
+    min = 20;
+    r_base = 70;
+    g_base = 0;
+    b_base = 70;
+    colorChange = false;
+}
+


Release 2.9.0

Release 2.9.0

--- TinyScreenClockAndDisplay.ino
+++ TinyScreenClockAndDisplay.ino
@@ -27,7 +27,7 @@
 int buttonReleased=0;
 int countdown = 0;

-char notificationLine1[20]="Sunday";
+char notificationLine1[20]="Release 2.9.0";

 void setup(void) {
   Wire.begin();
@@ -37,6 +37,7 @@
   Serial.begin(9600);
   RTC.start();
   startup();
+  Serial.println("Initialized");
 }

 void loop() {
@@ -46,6 +47,7 @@
     displayState = 1;
     display.on();
     countdown = 90;
+    Serial.println("Display on");
   	}
     if(buttons == 0){
       countdown=countdown-1;
@@ -53,6 +55,7 @@
   if (countdown<=0){
   displayState=0;
   display.off();
+  Serial.println("Display off");
 }
   displayNotifications();
   displayBattery();
@@ -72,12 +75,12 @@
         day = RTC.getDays();
         month = RTC.getMonths();
         year = RTC.getYears();
-        weakday = RTC.getDayOfWeek();
-        dayOfWeekName[] = { "Sunday","Monday","Tuesday","Wednesday",
-            "Thursday","Friday","Saturday"};
+        //weakday = RTC.getDayOfWeek();
+        //dayOfWeekName[] = { "Sunday","Monday","Tuesday","Wednesday",
+        //    "Thursday","Friday","Saturday"};

-day = dayOfWeekName[weekday];
+//day = dayOfWeekName[weekday];
   display.setFont(liberationSans_10ptFontInfo);
 // Date
   display.setCursor(0,10);
@@ -99,12 +102,12 @@
     display.print("0");
   }
   display.print(minute);
-  if (hour > 12) {
+  /*if (hour > 12) {
   display.print(" AM");
   }
   else {
     display.print(" PM");
-  }
+  }*/
 }
 void displayNotifications(){
   display.setFont(liberationSans_10ptFontInfo);


preprocessor to optionally use serial output

--- ardustat.ino
+++ ardustat.ino
@@ -5,6 +5,7 @@
 These shift the center point up and down
 */

+#define SERIALDEBUG
 #include <EEPROM.h>

 // Arduino convention is usually byte, but even arduino.h uses uint8_t
@@ -54,8 +55,10 @@
     pinMode(relayAC, OUTPUT);
     pinMode(relayHeat, OUTPUT);

+#if defined(SERIALDEBUG)
     // start serial monitor
     Serial.begin(9600);
+#endif

     // get mode and temperature settings from eeprom or default values
     // we store a basic check pattern in first bit
@@ -63,11 +66,15 @@
     // otherwise use the defaults and write them to EEPROM
     // note that mode only stores either "on" or "off"
     if (eepCheckVal == EEPROM.read(eepCheckAddr)) {
+#if defined(SERIALDEBUG)
         Serial.println(F("Using mode and temperature from EEPROM"));
+#endif
         mode = EEPROM.read(eepModeAddr);
         centerpoint = getEEPROMint(eepCenterpointAddr);
     } else {
+#if defined(SERIALDEBUG)
         Serial.println(F("Using mode and temperature from defaults"));
+#endif
         mode = on;
         centerpoint = defaultCenterpoint;

@@ -136,11 +143,13 @@
     }
     driveUnit(mode);

+#if defined(SERIALDEBUG)
     // print the current state for debugging
     Serial.print(F("   deg F: "));
     Serial.print(temperature);
     Serial.print(F("   centerpoint:"));
     Serial.println(centerpoint);
+#endif

     // slow the loop slightly
     delay(50); //ms
@@ -173,10 +182,12 @@
     tempC = (voltage - 0.5) * 100.0;
     tempF = (tempC * (9.0/5.0) + 32.0);

+#if defined(SERIALDEBUG)
     Serial.print(F("voltage: "));
     Serial.print(voltage);
     Serial.print(F("   deg C: "));
     Serial.print(tempC);
+#endif

     return int(tempF * 10.0);
 }
@@ -255,6 +266,17 @@
             digitalWrite(relayAC, LOW);
             digitalWrite(relayHeat, LOW);
     }
+
+#if defined(SERIALDEBUG)
+    Serial.print(F("   mode "));
+    Serial.print(mode);
+    Serial.print(F("   unit "));
+    Serial.print(unit);
+    Serial.print(F("   timeCur "));
+    Serial.print(timeCurrent);
+    Serial.print(F("   timeFan "));
+    Serial.print(timeFanOn);
+#endif
 }

@@ -301,4 +323,4 @@
     if (EEPROM.read(address) != value) {
         EEPROM.write(address, value);
     }
-}+}