Fixed mispelled D7S_OK #3

Fixed mispelled D7S_OK #3

--- examples/SelfDiagnostic/SelfDiagnostic.ino
+++ examples/SelfDiagnostic/SelfDiagnostic.ino
@@ -52,7 +52,7 @@
   Serial.print("The result of the selftest is: ");

   //checking the result
-  if (D7S.getSelftestResult() == OK) {
+  if (D7S.getSelftestResult() == D7S_OK) {
     Serial.println("SUCCESS!");
   } else {
     Serial.println("ERROR!");


Intermediate version, but it doesn't really help me. It works for outputting the information and everything over BLE, but saddly the millis() counter is not updated and we don't have any timing information - pretty much useless as it stands. Now we try to reset the ble chipset everytime we have a round, or something like that - let's see!

--- BuggyTracker/BuggyTracker.ino
+++ BuggyTracker/BuggyTracker.ino
@@ -19,10 +19,13 @@
 long curDistance = 0;
 #define LED  13

+#define DEBUG 0
+
 File dataFile;
 File currentRunFile;
 File runs;
-//RTC_DS1307 RTC;
+long lastMeasurement = 0;
+long beginRun = 0;

 void setup()
 {
@@ -31,7 +34,11 @@
   attachInterrupt(interupt, BtnDownCB, FALLING );

   // Call the function to enable low power consumption
-  ble_low_power();
+  #if !DEBUG
+    ble_low_power();
+  #else
+   Serial.begin(9600);
+  #endif

   // If you are using the Blend, uncomment below
   ble_set_pins(6, 7);
@@ -49,7 +56,6 @@

     // Open up the file we're going to log to!
     dataFile = SD.open("datalog.txt", FILE_WRITE);
-    currentRunFile = SD.open("currun.txt", FILE_WRITE);
      runs=SD.open("run.txt",FILE_WRITE);
   }

@@ -58,105 +64,60 @@
 }

+void stroller_ble_print() {
+  #if DEBUG
+    Serial.println("printing distance");
+  #endif
+  if (ble_connected()) {
+              char output[27];
+            // length of output should be: 5 fixed, 10 time, 12 distance;
+         sprintf(output,"D:%10lu:%10lu\n\n",millis(),curDistance);
+
+          ble_write_bytes((unsigned char *)output,27);
+  }
+}
+
 volatile int hadRound = 0;
 void loop()
 {
-//      Wire.begin();
-////      RTC.begin();
-      union {
-        char data[4];
-        long stamp;
-      } time;
-//        time.stamp = RTC.now().unixtime();
-    time.stamp=millis();
-//    time.stamp=100L;
-      char chrTime[10];
-//      ltoa(millis(),chrTime,10);
+  long time = millis();
+
   if (hadRound== 1) {
+        #if DEBUG
+    Serial.println("had round");
+  #endif
     // compare the time of the last logged or the current logged value
     // the actual calculation
-
+      if (beginRun==0) {
+        beginRun=time;
+      }
+      if (lastMeasurement == 0 ){
+        lastMeasurement = time;
+      }
       curDistance = curDistance + distance;
 //
 //      // write to SD card
-////
+
 ////      // here, we can write the full, readable timestamp:
-      dataFile.write(chrTime, 10);
-      dataFile.write(';');
-      dataFile.write('R');
-      dataFile.write('\n');
-      dataFile.flush();
-//      currentRunFile.seek(0); // always start at the beginning of the file
-////      // read the first four bytes of the file, that contain the last written timestamp
-////
-//      union{
-//        char data[4];
-//        long stamp;
-//      } lastTime ;
-//      //read the last saved timestamp
-//       lastTime.data[0]=currentRunFile.read();
-//       lastTime.data[1]=currentRunFile.read();
-//       lastTime.data[2]=currentRunFile.read();
-//       lastTime.data[3]=currentRunFile.read();
-//
-//      byte reset= 0;
-//      if ((time.stamp-lastTime.stamp)>timeBetweenRounds) {
-//        // we have a new file, reset the distance and save to a new file
-//
-//        char distanceBuf[10];
-////        ltoa(curDistance,distanceBuf,10);
-//                int length;
-//
-//   for (byte i = 0;i< sizeof(distanceBuf);i++){
-//       if (distanceBuf[i]==NULL) {
-//              length=i+1;
-//              break;
-//            }
-//         }
-//         char outBuf[length];
-//         for (byte i = 0;i<length;i++){
-//            outBuf[i]=distanceBuf[i];
-//         }
-//        runs.write(chrTime, 10);
-//        runs.write(':');
-//        runs.write(outBuf, length);
-//        reset=1;
-//        currentRunFile.read(); //";"
-////        currentRunFile.read();//"Distance" 1
-////        currentRunFile.read();//"Distance" 2
-////        currentRunFile.read();//"Distance" 3
-////        currentRunFile.read();//"Distance" 4
-////        currentRunFile.read();//";"
-//
-//        union{
-//          char data[4];
-//          long stamp;
-//        } startingTime ;
-//
-//       startingTime.data[0]=currentRunFile.read();
-//       startingTime.data[1]=currentRunFile.read();
-//       startingTime.data[2]=currentRunFile.read();
-//       startingTime.data[3]=currentRunFile.read();
-//        char startingTimeOut[10];
-////        ltoa(startingTime.stamp,startingTimeOut,10);
-//        runs.write(':');
-//        runs.write(startingTimeOut, 10);
-//        runs.write('\n');
-//        runs.flush();
-//        curDistance=distance;
-//      }
-//      currentRunFile.seek(0);
-//      currentRunFile.write(time.data, 4);
-////      currentRunFile.write(':');
-////      currentRunFile.write((unsigned char*)&curDistance, 4);
-//      if (reset==1) {
-//        currentRunFile.write(':');
-//        currentRunFile.write(time.data, 4); // origin time, will not be changed later on
-//        currentRunFile.flush();
-//      }
-//
-//
-      hadRound=0;
+              char output[27];
+            // length of output should be: 5 fixed, 10 time, 12 distance;
+            sprintf(output,"R:%10lu:%10.2lu\n",time,curDistance);
+            dataFile.write(output,27);
+            dataFile.flush();
+
+      byte reset= 0;
+      if ((lastMeasurement-time)>timeBetweenRounds) {
+          reset=1;
+          char result[100];
+          sprintf(result,"Run:%10lu:%10lu:%10.2lf\n",beginRun,time,curDistance);
+          runs.write(result,100);
+        runs.flush();
+        curDistance=distance;
+        beginRun=millis();
+      }
+          stroller_ble_print();
+          lastMeasurement = millis();
+          hadRound=0;

   }
   if (ble_available() )
@@ -166,57 +127,13 @@
     {
       temp = ble_read();
       if ('r' == temp) { // read comand from smartphone)
-//        int length = 4+sizeof(curDistance);
-//        String output = "D:";
-//        output+=curDistance;
-//        output+="\n";
-//        byte length= 8;
-
-
-//        char distanceBuf[10];
-//
-//        ltoa(curDistance,distanceBuf,10);
-//        int length;
-//
-//   for (byte i = 0;i<sizeof(distanceBuf);i++){
-//       if (distanceBuf[i]==NULL) {
-//              length=i+1;
-//              break;
-//            }
-//         }
-//         char outBuf[length];
-//         for (byte i = 0;i<length;i++){
-//            outBuf[i]=distanceBuf[i];
-//         }
-//
-
-
-//         ble_write(length);
-         ble_write('D');
-         ble_write(':');
-//          ble_write_bytes((unsigned char *)outBuf,length);
-          ble_write('\n');
-//          ble_write_bytes();
+          stroller_ble_print();
       }
       else if ( 'c' == temp ) { // aCcept or commit command from smartphone, later used for resetting
         curDistance=0;
         ble_write('r');
         ble_write('\n');
       }
-      //            temp = ble_read();
-      //            if('o' == temp)
-      //            {
-      //                temp = ble_read();
-      //                if('n' == temp)
-      //                {
-      //
-      //                    ble_write_bytes((unsigned char *)"LED on", 6);
-      //                }
-      //                else if('f' == temp && 'f' == ble_read())
-      //                {
-      //                    ble_write_bytes((unsigned char *)"LED off", 7);
-      //                }
-      //            }
     }
   }
 //  delay(50);
@@ -230,13 +147,6 @@
   PRR1 = 0x00;
   digitalWrite(LED,HIGH);
   hadRound = 1;
-  //    delay(100);  //jitters elimination
-  //    if(LOW == digitalRead(1))
-//  if ( ble_connected() )
-//  {
-//    ble_write_bytes((unsigned char *)"Button down", 11);
-//  }
-
 }


LCD text fixes and variable changes.

LCD text fixes and variable changes.

--- chicken_door_timer_v2.ino
+++ chicken_door_timer_v2.ino
@@ -30,8 +30,6 @@
 #define DELAY_MS 10
 #define MAX_DELAY_MINUTES 100
 #define DOOR_RETRY_SECONDS 10
-#define MAX_TIMEDELTA_MINS 240
-#define MIN_TIMEDELTA_MINS -240

 // Pins
 #define PIN_ENC_A     7
@@ -790,18 +788,14 @@
 }

 // read encoder and update time delta value on LCD
-byte updatetime_valLoop(byte prev){
+char updatetime_valLoop(char prev){
   encState eState = encoder.read();
   if (eState == ENC_DEC) {
-    if (prev < MIN_TIMEDELTA_MINS) {
-      prev = MAX_TIMEDELTA_MINS;
-    } else {
-      prev = (prev - 1);
-    }
+    prev--;
     tone(PIN_PIEZO, 100 + prev * 12, 25);
     drawAdjustTime(prev);
   } else if (eState == ENC_INC) {
-    prev = (prev + 1) % (MAX_TIMEDELTA_MINS);
+    prev++;
     tone(PIN_PIEZO, 100 + prev * 12, 25);
     drawAdjustTime(prev);
   }
@@ -813,7 +807,7 @@
   now = rtc.now();
   drawAdjustTime(0);
   bool set_time_dt_val = false;
-  byte deltaTimeMins = 0;
+  char deltaTimeMins = 0;
   while(!set_time_dt_val){
     wdt_reset();
     deltaTimeMins = updatetime_valLoop(deltaTimeMins);
@@ -838,13 +832,10 @@
   lcd.print(":");
   tensDigitLCD(now.minute());
   lcd.setCursor(0, 1);
-  if(delta < 0){
-    lcd.print("-");
-  } else if (delta > 0){
+  if (delta > 0){
     lcd.print("+");
   }
-  lcd.print(" ");
-  lcd.print((char)delta);
+  lcd.print((int)delta);
   lcd.print(" mins.");
 }

@@ -881,9 +872,9 @@
 // delay adjust menu option
 void drawDelayOption(){
   lcd.clear();
-  lcd.print("Set pre/post delays");
+  lcd.print("Set pre/post");
   lcd.setCursor(0, 1);
-  lcd.print("[2/2]");
+  lcd.print("delays [2/2]");
   in_delay_adj_menu = true;
   in_time_adj_menu = false;
 }
@@ -900,9 +891,9 @@
     }
   } else if (menu_pos == 1){
     if(!in_options_menu){
+      drawPostDelayMenu();
+    } else {
       drawDelayOption();
-    } else {
-      drawPostDelayMenu();
       //in_post_delay_menu = true;
     }
   }


add some lines of comment to ChatServer.ino, remove redundant assignment of Client-instance

--- libraries/Ethernet/examples/ChatServer/ChatServer.ino
+++ libraries/Ethernet/examples/ChatServer/ChatServer.ino
@@ -62,6 +62,7 @@

     boolean newClient = true;
     for (byte i=0;i<4;i++) {
+      //check whether this client refers to the same socket as one of the existing instances:
       if (clients[i]==client) {
         newClient = false;
         break;
@@ -69,8 +70,9 @@
     }

     if (newClient) {
+      //check which of the existing clients can be overridden:
       for (byte i=0;i<4;i++) {
-        if (clients[i]!=client) {
+        if (!clients[i] && clients[i]!=client) {
           clients[i] = client;
           break;
         }
@@ -89,7 +91,7 @@
     if (client.available() > 0) {
       // read the bytes incoming from the client:
       char thisChar = client.read();
-      // echo the bytes back to the client:
+      // echo the bytes back to all other connected clients:
       for (byte i=0;i<4;i++) {
         if (!clients[i] || (clients[i]==client)) {
           continue;
@@ -102,8 +104,8 @@
   }
   for (byte i=0;i<4;i++) {
     if (!(clients[i].connected())) {
+      // client.stop() invalidates the internal socket-descriptor, so next use of == will allways return false;
       clients[i].stop();
-      clients[i]=EthernetClient();
     }
   }
 }


Update documentation/comments

Update documentation/comments

--- examples/StanBox/StanBox.ino
+++ examples/StanBox/StanBox.ino
@@ -14,19 +14,14 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 //
-//
-// This example demonstrates the functionality of the LED7Seg library
-// optimized for a 3 or 4 digit display.
-//
-// It creates a PWM output on pins D10,D11 compatible with Talon, TalonSRX
+// This example creates a PWM output on pin D10 compatible with Talon, TalonSRX
 // and SparkMax FRC motor controllers
 //
-// It monitors the battery voltage on A7:
-//            2.2K             1.0K
-//  VIN  ----/\/\/\-----o-----/\/\/\-------|>
-//                      |
-//                      A7
-// User input is set using a quadrature rotary encoder on D2-D3
+// User input is set using a quadrature rotary encoder on D2-D3 and pushbutton
+// on D0.
+//
+// Values are output on the 4-digit 7-segment LED display.
+//
 // Power is -1.00..+1.00 corresponding to:
 //     1.0 msec (full rev)
 //     1.5 msec (stop)
@@ -49,13 +44,20 @@

 Servo pwmOut;

-//           MOD         ENA ENB D1   A   F  D2  D3   B
+//           BUT     GND ENA ENB                         PWM
+//            |       |   |   |                           |
+//            |       |   |   |  D1   A   F  D2  D3   B   |
 //      +-o---o---o---o---o---o---o---o---o---o---o---o---o---o---o-+
 //	    |TX0 RX1 RST GND D2  D3| D4  D5  D6  D7  D8  D9| D10 D11 D12|
 //	    |                      |     Arduino Nano      |            |
 //      |VIN GND RST 5V  A7  A6| A5  A4  A3  A2  A1  A0|REF 3V3 D13 |
 //      +-o---o---o---o---o---o---o---o---o---o---o---o---o---o---o-+
-//                       AIN BAT  E   D  DP   C   G  D4
+//        |   |       |   |   |  E   D  DP   C   G  D4
+//        |   +--POT--+   |   |
+//        |   |   A       |   |
+//       20K 10K  +-------+   |
+//        |   |               |
+//        +---+---------------+
 const byte ledPins[] = { /*segA-F+DP=*/ 5, 9, A2, A4, A5, 6, A1, A3, /*dig1-4=*/ 4, 7, 8, A0};

 void setup()


Fix issue with lcd_nav example

Fix issue with lcd_nav example

--- examples/lcd_nav/lcd_nav.ino
+++ examples/lcd_nav/lcd_nav.ino
@@ -13,14 +13,19 @@

 // renderer

+// The LCD circuit:
+//    * LCD RS pin to digital pin 8
+//    * LCD Enable pin to digital pin 9
+//    * LCD D4 pin to digital pin 4
+//    * LCD D5 pin to digital pin 5
+//    * LCD D6 pin to digital pin 6
+//    * LCD D7 pin to digital pin 7
+//    * LCD R/W pin to ground
+LiquidCrystal lcd = LiquidCrystal(8, 9, 4, 5, 6, 7);
+
 class MyRenderer : public MenuComponentRenderer
 {
 public:
-    MyRenderer()
-    : lcd(LiquidCrystal(8, 9, 4, 5, 6, 7))
-    {
-    }
-
     virtual void render(Menu const& menu) const
     {
         lcd.clear();
@@ -49,9 +54,6 @@
     {
         lcd.print(menu.get_name());
     }
-
-private:
-    mutable LiquidCrystal lcd;
 };
 MyRenderer my_renderer;

@@ -69,21 +71,7 @@
 Menu mu1("Level 1 - Item 3 (Menu)");
 MenuItem mu1_mi1("Level 2 - Item 1 (Item)", on_item3_selected);

-/*
-The LCD circuit:
- * LCD RS pin to digital pin 8
- * LCD Enable pin to digital pin 9
- * LCD D4 pin to digital pin 4
- * LCD D5 pin to digital pin 5
- * LCD D6 pin to digital pin 6
- * LCD D7 pin to digital pin 7
- * LCD R/W pin to ground
- */
-// initialize the library with the numbers of the interface pins
-LiquidCrystal lcd(8     ,     9 ,      4 ,      5 ,      6 ,      7 );
-
 // Menu callback function
-// In this example all menu items use the same callback.

 void on_item1_selected(MenuItem* p_menu_item)
 {
@@ -105,21 +93,6 @@
   lcd.print("Item3 Selected  ");
   delay(1500); // so we can look the result on the LCD
 }
-
-
-/*void displayMenu() {*/
-  /*lcd.clear();*/
-  /*lcd.setCursor(0,0);*/
-  /*// Display the menu*/
-  /*Menu const* cp_menu = ms.get_current_menu();*/
-
-  /*//lcd.print("Current menu name: ");*/
-  /*lcd.print(cp_menu->get_name());*/
-
-  /*lcd.setCursor(0,1);*/
-
-  /*lcd.print(cp_menu->get_current_component()->get_name());*/
-/*}*/

 void serialPrintHelp() {
   Serial.println("***************");
@@ -170,30 +143,16 @@
   lcd.begin(16, 2);

   serialPrintHelp();
-  Serial.println("Setting up the menu.");
-  // Menu setup
-  /*
-  Menu Structure:
-   -Item1
-   -Item2
-   -Item3
-   --Item1
-   */
+
   ms.get_root_menu().add_item(&mm_mi1);
   ms.get_root_menu().add_item(&mm_mi2);
   ms.get_root_menu().add_menu(&mu1);
   mu1.add_item(&mu1_mi1);
-
-  Serial.println("Menu set");

   ms.display();
 }

 void loop()
 {
-  // Handle serial commands
   serialHandler();
-
-  // Wait for two seconds so the output is viewable
-  //delay(2000);
 }


Pushing latest, not really sure what it is....

--- ASC_Alexa_Sprinkler_Controller/ASC_Alexa_Sprinkler_Controller.ino
+++ ASC_Alexa_Sprinkler_Controller/ASC_Alexa_Sprinkler_Controller.ino
@@ -20,7 +20,6 @@
 #include <ESP8266WiFi.h>        // ESP8266 (ESP-12E) wifi library
 #include "SSD1306.h"            // SSD1306 OLED display
 #include "Adafruit_MCP23017.h"  // Adafruit-MCP23017-Arduino-Library, GPIO EXPANDER
-#include "SparkFunTMP102.h"     // TMP102 I2C temperature sensor
 #include "fauxmoESP.h"          // Alexa suppport. (fake WeMo devices)
 #include <NTPClient.h>          // Supports NTP server time queries.
 #include <WiFiUdp.h>            // Adds UDP protocol support, required by NTP service.
@@ -30,9 +29,9 @@
 //------------------------------------------------------------------------------------------------

 // PIN DEFINITION CONSTANTS
-const int I2C_SDA = 0;      //I2C bus data pin (SCL). ESP-12E "D3" GPIO0
-const int I2C_SCL = 14;     //I2C bus clock pin (SCL). ESP-12E "D5" GPIO14
-const int alertPin = 5;     //TMP102 alert pin. ESP8266 "D1" GPIO5
+const int I2C_SDA = 4;      //I2C bus data pin (SCL). ESP-12E "D1"
+const int I2C_SCL = 5;     //I2C bus clock pin (SCL). ESP-12E "D2"
+const int ONE_WIRE = 14;     //1 WIRE Interface for AM2301 "HT21" Temp/Humidity. ESP-12E "D5"
 const int relayPin_K1 = 0;  //K1 relay control pin. MCP23017 Pin 21/GPA0
 const int relayPin_K2 = 1;  //K2 relay control pin. MCP23017 Pin 22/GPA1
 const int relayPin_K3 = 2;  //K3 relay control pin. MCP23017 Pin 23/GPA2
@@ -50,7 +49,6 @@
 // LIBRARY INITIALIZATION
 SSD1306  display(0x3c, I2C_SDA, I2C_SCL); // SSD1306 Pin Assignments
 fauxmoESP fauxmo;                         // Initialize fauxmo
-TMP102 sensor0(0x48);                     // Initialize sensor at I2C address 0x48
 Adafruit_MCP23017 mcp;                    // Adafruit-MCP23017-Arduino-Library
 WiFiUDP ntpUDP;                           // Initalize WifiUDP library

@@ -69,14 +67,14 @@

   //START I2C COMMUNICATION
   display.init();   // SSD12306 - OLED screen start I2C comms
+  Serial.println("SSD1306 INIT");
   mcp.begin();      // MCP23017 - I/O Expander start I2C comms
-  sensor0.begin();  // TMP102 - Temp Sensor start I2C comms

   //Flip Screen orientation in software, (pins on top)
   display.flipScreenVertically(); //SSD12306

   //CONFIGURE PIN USAGE
-  pinMode(alertPin, INPUT); // Declare alertPin as an input TMP102
+
   //set PORT A I/O expander pins to OUTPUTS for relay use
   mcp.pinMode(relayPin_K1, OUTPUT);
   mcp.pinMode(relayPin_K2, OUTPUT);
@@ -113,35 +111,8 @@
   fauxmo.onMessage(callback); //function call for fauxmo state check.

-  //------------TMP102 Setup----------------------------------------------------------
-  // Initialize sensor0 settings
-  // These settings are saved in the sensor, even if it loses power
-
-  // set the number of consecutive faults before triggering alarm.
-  // 0-3: 0:1 fault, 1:2 faults, 2:4 faults, 3:6 faults.
-  sensor0.setFault(3);  // Trigger alarm immediately
-
-  // set the polarity of the Alarm. (0:Active LOW, 1:Active HIGH).
-  sensor0.setAlertPolarity(1); // Active HIGH
-
-  // set the sensor in Comparator Mode (0) or Interrupt Mode (1).
-  sensor0.setAlertMode(0); // Comparator Mode.
-
-  // set the Conversion Rate (how quickly the sensor gets a new reading)
-  //0-3: 0:0.25Hz, 1:1Hz, 2:4Hz, 3:8Hz
-  sensor0.setConversionRate(2);
-
-  //set Extended Mode.
-  //0:12-bit Temperature(-55C to +128C) 1:13-bit Temperature(-55C to +150C)
-  sensor0.setExtendedMode(0);
-
-  //set T_HIGH, the upper limit to trigger the alert on
-  sensor0.setHighTempF(77.0);  // set T_HIGH in F
-  //sensor0.setHighTempC(29.4); // set T_HIGH in C
-
-  //set T_LOW, the lower limit to shut turn off the alert
-  sensor0.setLowTempF(76.0);  // set T_LOW in F
-  //sensor0.setLowTempC(26.67); // set T_LOW in C
+  //------------AM2301 Setup----------------------------------------------------------
+
   //----------------------------------------------------------------------------------

   //------------USB Serial Comms Setup -----------------------------------------------
@@ -180,61 +151,7 @@
   display.drawString(0, 16, "TIME:");
   display.drawString(45, 16, (timeString));
 }
-//UPDATE TEMP FUNCTION (SHITSHOW CODE, BUT IT WORKS)
-//------------------------------------------------------------------------------------------------
-
-void updateTemp() {
-
-  float temperature;
-  String stringVal = "";
-  boolean alertPinState, alertRegisterState;
-
-  // read temperature data and write to OLED screen
-  temperature = sensor0.readTempF();
-  //temperature = sensor0.readTempC();
-
-  // convert temperature float to string
-  stringVal += String(int(temperature)) + "." + String(getDecimal(temperature)); //combining both whole and decimal part in string with a fullstop between them
-  //Serial.print("stringVal: ");Serial.println(stringVal);              //display string value
-
-  char charVal[stringVal.length() + 1];                    //initialise character array to store the values
-  stringVal.toCharArray(charVal, stringVal.length() + 1);  //passing the value of the string to the character array
-
-  //Serial.print("charVal: ");
-  for (uint8_t i = 0; i < sizeof(charVal); i++) //Serial.print(charVal[i]); //display character array
-
-    display.setTextAlignment(TEXT_ALIGN_LEFT);
-  display.setFont(ArialMT_Plain_16);
-  display.drawString(0, 32, "TEMP:");
-  display.drawString(80, 32, "F");
-  display.drawString(48, 32, (stringVal));
-
-  // Check for Alert
-  alertPinState = digitalRead(alertPin); // read the Alert from pin
-  alertRegisterState = sensor0.alert();   // read the Alert from register
-
-  /*
-    // Print temperature and alarm state
-    Serial.print("Temperature: ");
-    Serial.print(temperature);
-
-    Serial.print("\tAlert Pin: ");
-    Serial.print(alertPinState);
-
-    Serial.print("\tAlert Register:  ");
-    Serial.println(alertRegisterState);
-  */
-}
-//function to extract decimal part of float (SUB ROUTINE OF TEMP UPDATE)
-long getDecimal(float val)
-{
-  int intPart = int(val);
-  long decPart = 10 * (val - intPart); //I am multiplying by 1000 assuming that the foat values will have a maximum of 3 decimal places.
-  //Change to match the number of decimal places you need
-  if (decPart > 0)return (decPart);       //return the decimal part of float number if it is available
-  else if (decPart < 0)return ((-1) * decPart); //if negative, multiply by -1
-  else if (decPart = 0)return (00);       //return 0 if decimal part of float number is not available
-}
+
 //FAUXMO CALLBACK FUNCTION add devices here
 //------------------------------------------------------------------------------------------------
 void callback(uint8_t device_id, const char * device_name, bool state) {
@@ -337,11 +254,12 @@
 void loop() {
   display.clear();     // wipe display clean to refresh it
   updateIP();          // function call for display update
-  updateTemp();        // fuction call for TMP102 temp
+  //updateTemp();        // fuction call for TMP102 temp
   updateTime();
   fauxmo.handle();     // call fauxmo device function
   display.display();   // write display buffer
-  delay(10);           // loop governor, determine how fast this loop runs
+  Serial.println("LOOP");
+  delay(100);           // loop governor, determine how fast this loop runs
 }
 //================================================================================================


Avoid 'time' because of clash on Due

Avoid 'time' because of clash on Due

--- frogger.ino
+++ frogger.ino
@@ -43,7 +43,7 @@
 static byte lives;
 static byte done[5];
 static byte homes[5] = { 24, 72, 120, 168, 216 };
-static int time;
+static int ti;

 void frog_start()
 {
@@ -53,7 +53,7 @@
   frogdir = 0;
   frogface = 0x0000;
   dying = 0;
-  time = 120 << 7;
+  ti = 120 << 7;
 }

 void level_start()
@@ -286,13 +286,13 @@

   prevt = t;
   t++;
-  time = max(0, time - 1);
-  if ((time == 0) && (dying == 0))
+  ti = max(0, ti - 1);
+  if ((ti == 0) && (dying == 0))
     dying = 1;

   // Draw 'time remaining' by clearing a black rectangle
   {
-    byte tw = 120 - (time >> 7);
+    byte tw = 120 - (ti >> 7);
     byte tx = 72;
     GD.SaveContext();
     GD.ScissorXY(tx, 248);
@@ -372,7 +372,7 @@

   if (dying) {
     if (++dying == 64) {
-      if (--lives == 0 || time == 0) {
+      if (--lives == 0 || ti == 0) {
         game_over();
         game_start();
         level_start();


Adapt code to new ntp_client API.

Adapt code to new ntp_client API.

--- wifi-feather/wifi-feather.ino
+++ wifi-feather/wifi-feather.ino
@@ -34,11 +34,7 @@
 typedef persistent_queue<message> pending_messages_queue;

 static pending_messages_queue* pending_messages;
-
-static WiFiUDP Udp;
-// TODO make ntp_client a template capable of handling both WiFiUDP and EthernetUDP
-static ntp_client ntp(Udp);
-
+static ntp_client ntp(std::unique_ptr<UDP>(new WiFiUDP()));
 static PrintEx serial = Serial;

 void setup() {
@@ -57,7 +53,6 @@
   connect_wifi();

   Serial.println("Syncing with NTP clock");
-  Udp.begin(local_port);
   setSyncProvider([]() { return ntp.get_time(); });
   bool success = wait_for_condition(
     []() { return timeStatus() != timeNotSet; },


changed to action_loop

changed to action_loop

--- arduino/slavenode_Innenthermometer/slavenode_Innenthermometer.ino
+++ arduino/slavenode_Innenthermometer/slavenode_Innenthermometer.ino
@@ -44,6 +44,8 @@
 #include <DallasTemperature.h>
 #include <LCD5110_Graph.h>

+ISR(WDT_vect) { watchdogEvent(); }
+
 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
 OneWire oneWire(ONE_WIRE_BUS);

@@ -88,6 +90,83 @@

 // Network uses that radio
 RF24Network network(radio);
+
+void action_loop(void) {
+    switch (rxheader.type) {
+      case 1: {
+        // Temperature
+        txheader.type=1;
+        sensors.requestTemperatures(); // Send the command to get temperatures
+        temp=sensors.getTempCByIndex(0);
+        payload.value=temp;
+        network.write(txheader,&payload,sizeof(payload));
+       break; }
+      case 21:
+        // Set field 1
+        txheader.type=21;
+        print_field(payload.value,1);
+        network.write(txheader,&payload,sizeof(payload));
+       break;
+      case 22:
+        // Set field 2
+        txheader.type=22;
+        print_field(payload.value,2);
+        network.write(txheader,&payload,sizeof(payload));
+       break;
+      case 23:
+        // Set field 3
+        txheader.type=23;
+        print_field(payload.value,3);
+        network.write(txheader,&payload,sizeof(payload));
+       break;
+      case 24:
+        // Set field 4
+        txheader.type=24;
+        print_field(payload.value,4);
+        network.write(txheader,&payload,sizeof(payload));
+       break;
+      case 31:
+        // Displaylight ON <-> OFF
+        txheader.type=31;
+        if (payload.value > 0.5) {
+          digitalWrite(STATUSLED,STATUSLED_ON);
+        } else {
+          digitalWrite(STATUSLED,STATUSLED_OFF);
+        }
+        network.write(txheader,&payload,sizeof(payload));
+       break;
+      case 101:
+      // battery voltage
+        payload.value=read_battery_voltage();
+        draw_battery(74,1,payload.value);
+        txheader.type=101;
+        network.write(txheader,&payload,sizeof(payload));
+        break;
+      case 111:
+      // sleeptimer
+        if (payload.value > 0) sleeptime=payload.value;
+        radiomode=radio_sleep;
+        txheader.type=111;
+        network.write(txheader,&payload,sizeof(payload));
+        break;
+      case 112:
+      // radio on (=1) or off (=0) when sleep
+        txheader.type=112;
+        if ( payload.value > 0.5) radiomode=radio_listen; else radiomode=radio_sleep;
+        network.write(txheader,&payload,sizeof(payload));
+        break;
+      case 118:
+      // just in case that there are still some messages inside the network ...
+        init_finished=true;
+        txheader.type=118;
+        network.write(txheader,&payload,sizeof(payload));
+        break;
+      default:
+      // Default: just send the paket back
+        txheader=rxheader;
+        network.write(txheader,&payload,sizeof(payload));
+    }
+}

 void setup(void) {
   pinMode(STATUSLED, OUTPUT);
@@ -128,25 +207,7 @@
       network.read(rxheader,&payload,sizeof(payload));
       init_transmit=false;
       init_loop_counter=0;
-      txheader.type=rxheader.type;
-      switch (rxheader.type) {
-        case 111: {
-        // Init des Sleeptimers
-          sleeptime=payload.value;
-          break; }
-        case 112: {
-          // radio on (=1) or off (=0) when sleep
-          if (payload.value > 0.5) radiomode = radio_listen; else radiomode=radio_sleep;
-          break; }
-        case 118: {
-          init_finished=true;
-          break; }
-        default: {
-            // nothing right now
-          }
-      }
-      //returns every message
-      network.write(txheader,&payload,sizeof(payload));
+      action_loop();
     }
     sleep4ms(30);
     init_loop_counter--;
@@ -332,75 +393,7 @@
     network_busy = true;
     stayawakeloopcount=0;
     network.read(rxheader,&payload,sizeof(payload));
-    switch (rxheader.type) {
-      case 1: {
-        // Temperature
-        txheader.type=1;
-        sensors.requestTemperatures(); // Send the command to get temperatures
-        temp=sensors.getTempCByIndex(0);
-        payload.value=temp;
-        network.write(txheader,&payload,sizeof(payload));
-       break; }
-      case 21:
-        // Set field 1
-        txheader.type=21;
-        print_field(payload.value,1);
-        network.write(txheader,&payload,sizeof(payload));
-       break;
-      case 22:
-        // Set field 2
-        txheader.type=22;
-        print_field(payload.value,2);
-        network.write(txheader,&payload,sizeof(payload));
-       break;
-      case 23:
-        // Set field 3
-        txheader.type=23;
-        print_field(payload.value,3);
-        network.write(txheader,&payload,sizeof(payload));
-       break;
-      case 24:
-        // Set field 4
-        txheader.type=24;
-        print_field(payload.value,4);
-        network.write(txheader,&payload,sizeof(payload));
-       break;
-      case 31:
-        // Displaylight ON <-> OFF
-        txheader.type=31;
-        if (payload.value > 0.5) {
-          digitalWrite(STATUSLED,STATUSLED_ON);
-        } else {
-          digitalWrite(STATUSLED,STATUSLED_OFF);
-        }
-        network.write(txheader,&payload,sizeof(payload));
-       break;
-      case 101:
-      // battery voltage
-        payload.value=read_battery_voltage();
-        draw_battery(74,1,payload.value);
-        txheader.type=101;
-        network.write(txheader,&payload,sizeof(payload));
-        break;
-      case 111:
-      // sleeptimer
-        if (payload.value > 0) sleeptime=payload.value;
-        radiomode=radio_sleep;
-        txheader.type=111;
-        network.write(txheader,&payload,sizeof(payload));
-        break;
-      case 112:
-      // radio on (=1) or off (=0) when sleep
-        txheader.type=112;
-        if ( payload.value > 0.5) radiomode=radio_listen; else radiomode=radio_sleep;
-        network.write(txheader,&payload,sizeof(payload));
-        break;
-      case 118:
-      // just in case that there are still some messages inside the network ...
-        txheader.type=118;
-        network.write(txheader,&payload,sizeof(payload));
-        break;
-    }
+    action_loop();
   }
   if ( stayawakeloopcount > STAYAWAKEDEFAULT ) {
     network_busy=false;


clean in interrupted mode for 1-wire devices

--- arduino_pico/arduino_pico.ino
+++ arduino_pico/arduino_pico.ino
@@ -3,7 +3,7 @@
 #include "TimerOne.h"

 // Data wire is plugged into port 2 on the Arduino
-#define ONE_WIRE_BUS 7
+#define ONE_WIRE_BUS A0
 #define TEMPERATURE_PRECISION 12

 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
@@ -12,29 +12,19 @@
 // Pass our oneWire reference to Dallas Temperature.
 DallasTemperature sensors(&oneWire);

-// arrays to hold device addresses
-DeviceAddress heatThermometer, pipeThermometer,boilThermometer;
+// Device addresses
+DeviceAddress heatThermometer, pipeThermometer, boilThermometer;
+float         heatTemp,        pipeTemp,        boilTemp;

 void setup(void)
 {
   // start serial port
-  Serial.begin(9600);
-  Serial.println("Dallas Temperature IC Control Library Demo");
+  Serial.begin(57600);
+

   // Start up the library
   sensors.begin();
-
-  // locate devices on the bus
-  Serial.print("Locating devices...");
-  Serial.print("Found ");
-  Serial.print(sensors.getDeviceCount(), DEC);
-  Serial.println(" devices.");
-
-  // report parasite power requirements
-  Serial.print("Parasite power is: ");
-  if (sensors.isParasitePowerMode()) Serial.println("ON");
-  else Serial.println("OFF");

   // assign address manually.  the addresses below will beed to be changed
   // to valid device addresses on your bus.  device address can be retrieved
@@ -50,66 +40,32 @@
   sensors.setResolution(pipeThermometer, TEMPERATURE_PRECISION);
   sensors.setResolution(boilThermometer, TEMPERATURE_PRECISION);

-  Timer1.initialize(10000000); // set a timer of length 20000 microseconds (or 0.02 sec - or 50Hz => frequency of electricity in europe)
+  sensors.setWaitForConversion(false);
+
+  Timer1.initialize(750000);
   Timer1.attachInterrupt( timerIsr ); // attach the service routine here

 }

-// function to print a device address
-void printAddress(DeviceAddress deviceAddress)
+void interruptTemperature (void)
 {
-  for (uint8_t i = 0; i < 8; i++)
-  {
-    // zero pad the address if necessary
-    if (deviceAddress[i] < 16) Serial.print("0");
-    Serial.print(deviceAddress[i], HEX);
-  }
-}

-// function to print the temperature for a device
-void printTemperature(DeviceAddress deviceAddress)
-{
-  float tempC = sensors.getTempC(deviceAddress);
-  Serial.print("Temp C: ");
-  Serial.print(tempC);
-  Serial.print(" Temp F: ");
-  Serial.print(DallasTemperature::toFahrenheit(tempC));
-}
-
-// function to print a device's resolution
-void printResolution(DeviceAddress deviceAddress)
-{
-  Serial.print("Resolution: ");
-  Serial.print(sensors.getResolution(deviceAddress));
-  Serial.println();
-}
-
-// main function to print information about a device
-void printData(DeviceAddress deviceAddress)
-{
-  Serial.print("Device Address: ");
-  printAddress(deviceAddress);
-  Serial.print(" ");
-  printTemperature(deviceAddress);
-  Serial.println();
+  heatTemp = sensors.getTempC(heatThermometer);
+  pipeTemp = sensors.getTempC(pipeThermometer);
+  boilTemp = sensors.getTempC(boilThermometer);
+
+  // call sensors.requestTemperatures() to issue a global temperature
+  // request to all devices on the bus
+  sensors.requestTemperatures();
 }

 void timerIsr()
 {
-  // call sensors.requestTemperatures() to issue a global temperature
-  // request to all devices on the bus
-  Serial.print("Requesting temperatures...");
-  sensors.requestTemperatures();
-  Serial.println("DONE");
+  interruptTemperature(); // get temperature data and request measure

-  // print the device information
-  printData(heatThermometer);
-  printData(pipeThermometer);
-  printData(boilThermometer);
 }

 void loop(void){

-
-
+
 }


Update deadbolt firmata

Update deadbolt firmata

--- firmata/deadbolt/deadbolt.ino
+++ firmata/deadbolt/deadbolt.ino
@@ -52,12 +52,16 @@
   pinMode(ALERT_PIN, OUTPUT);
 }

-void flashLed() {
+void feedback(alert) {
   digitalWrite(LED_PIN, HIGH);
-  digitalWrite(ALERT_PIN, HIGH);
+  if (alert) {
+    digitalWrite(ALERT_PIN, HIGH);
+  }
   delay(1000);
   digitalWrite(LED_PIN, LOW);
-  digitalWrite(ALERT_PIN, LOW);
+  if (alert) {
+    digitalWrite(ALERT_PIN, LOW);
+  }
 }

 void toggle(bool lockedState) {
@@ -77,7 +81,7 @@

   if (buttonState == HIGH) {
     toggle(locked);
-    flashLed();
+    feedback(false);
   }

   uint8_t success;
@@ -110,7 +114,7 @@

     if (isAuthorized) {
       toggle(locked);
-      flashLed();
+      feedback();
     }
   }
 }


WDRC_8Band_FIR_full: initialize BLE with myTympan instead of Serial1

--- examples/05-FullSystems/WDRC_8BandFIR_full/WDRC_8BandFIR_full.ino
+++ examples/05-FullSystems/WDRC_8BandFIR_full/WDRC_8BandFIR_full.ino
@@ -55,9 +55,9 @@

 // Create classes for controlling the system
 #include      "SerialManager.h"
-#include      "State.h"                //must be after N_CHAN is defined
-BLE_UI        ble(&Serial1);           //create bluetooth BLE class
-SerialManager serialManager(&ble);     //create the serial manager for real-time control (via USB or App)
+#include      "State.h"                 //must be after N_CHAN is defined
+BLE_UI        ble(&myTympan);           //create bluetooth BLE class
+SerialManager serialManager(&ble);      //create the serial manager for real-time control (via USB or App)
 State         myState(&audio_settings, &myTympan, &serialManager); //keeping one's state is useful for the App's GUI


spelling correction

spelling correction

--- examples/CAP1188_TWI_wMenu/CAP1188_TWI_wMenu.ino
+++ examples/CAP1188_TWI_wMenu/CAP1188_TWI_wMenu.ino
@@ -18,7 +18,7 @@
         ~ slight_DebugMenu
             written by stefan krueger (s-light),
                 github@s-light.eu, http://s-light.eu, https://github.com/s-light/
-            License: MIT
+            license: MIT

     written by stefan krueger (s-light),
         github@s-light.eu, http://s-light.eu, https://github.com/s-light/


INA219a MMA, some cosmetic fixes

INA219a MMA, some cosmetic fixes

--- ArduinoWeatherStation.ino
+++ ArduinoWeatherStation.ino
@@ -8,16 +8,15 @@
  Much of this is based on Mike Grusin's USB Weather Board code: https://www.sparkfun.com/products/10586

  */
-const String wxVersion = "L13bB1"; // jjj
+const String wxVersion = "L14cB1"; // jjj
 const String wxOwner = "-DJ-";
-const byte IPgw = 254;    //Marshall must be 254
-const byte IPq3 = 243;    //Marshall must be 243
 const byte ina219a_HWaddr = 0x40;  //0x40 for everyone but Lance. 0x44 for Lance.
 const byte ina219b_HWaddr = 0x41;  //
 const byte bme280a_HWaddr = 0x76;  //Default may be 0x77 depending on mfgr
 const byte bme280b_HWaddr = 0x77;
 const bool disableNTP = false;      //Set to false to allow NTP, but it can cause crashes if it doesn't get a response.
-const String startupMessage = "UM Weather Station (ver L13bB1 2017/09/15) starting at ms ";
+const String startupMessage = "UM Weather Station (ver L13gB1 2017/09/26 INA219a smoothing) starting at ms ";
+//#define FOURMINUTEDAY              // Switch from day to night every four minutes for DEBUG

 #include <avr/wdt.h>   // WatchDog Timer. If I hit an endless loop, reset. Kindof. May not reset Ethernet properly.
@@ -43,6 +42,13 @@
 #define logOneLine2( line, base) Serial.println(line,base);
 #define logSome( line) Serial.print(line);

+// Redefine INA219 sample & average so we don't have to modify the header. This is probably poor coding practice. I'm sorry.
+// First line is original and is used to initialize the INA219. 2nd line is what we're copying. 3rd line makes it happen. Note 0x0078 in 3rd line.
+#define INA219_CONFIG_SADCRES_12BIT_1S_532US   (0x0018)  // 1 x 12-bit shunt sample
+#define INA219_CONFIG_SADCRES_12BIT_128S_69MS  (0x0078)  // 128 x 12-bit shunt samples averaged together
+//#undef  INA219_CONFIG_SADCRES_12BIT_1S_532US
+//#define INA219_CONFIG_SADCRES_12BIT_1S_532US   (0x0078)  // REDEFINE the 1 sample to really be 128 samples so we don't have to modify Adafruit_INA219.h
+

 Adafruit_INA219 ina219a(ina219a_HWaddr);     // First  ina219 sensor: A
 Adafruit_INA219 ina219b(ina219b_HWaddr);     // Second ina219 sensor: B
@@ -51,13 +57,13 @@
 MPL3115A2 myPressure;            //Sparkfun pressure sensor
 HTU21D myHumidity;               //Sparkfun humidity sensor

+
 //Hardware pin definitions, weather station
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 // digital I/O pins
 const byte WSPEED = 3;
 const byte RAIN = 2;
 const byte STAT1 = 7;
-const byte STAT2 = 8; //TODO: This pin (second status LED) seems wrong

 const byte PIN_ETH_DISABLE = 8; // Ethernet power control; on=LOW, off=HIGH
 const byte ETH_DISABLED = HIGH;
@@ -68,8 +74,8 @@
 const byte UBIQUITI_ENABLED = HIGH;

 const byte PIN_SOLAR_DISABLE = 16;    // Solar panel control; on=LOW, off=HIGH
-const byte SOLAR_DISABLED = HIGH;
-const byte SOLAR_ENABLED = LOW;
+const byte SOLAR_DISABLED = LOW;
+const byte SOLAR_ENABLED = HIGH;

 // analog I/O pins
 const byte WDIR = A0;
@@ -79,10 +85,10 @@
 const byte SLA_BATT = A12;

 // I2C devices
-// 0x40  64 Humidity/temp sensor?
+// 0x40  64 Sparkfun Humidity/temp sensor?
 // 0x44  68 INA219 on 3rd address (1st address is 0x40, conflicts with humidty sensor)
 // 0x41  65 INA219 on 2nd address
-// 0x60  96 Humidity/temp sensor?
+// 0x60  96 Sparkfun Humidity/temp sensor?
 // 0x76 118 BME280 environmental sensor

 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
@@ -199,10 +205,26 @@
 float sla_30sec = 11.8;    // 10 second rolling average of SLA battery voltage (~12v)
 int   sla_10secRaw = 1180; // 10 second average of AnalogPort reading (0-1023).
 float light_lvl = 455;     // [analog value from 0 to 1023]
+
+//INA 219 volt & current sensor. MMA means Modified Moving Average. PWM charging requires some smoothing.
 float ina219a_volts;
 float ina219a_current;
 float ina219b_volts;
 float ina219b_current;
+float ina219a_MMAtemp;
+float ina219a_MMAcurrentSum;
+float ina219a_MMAcurrentAvg;
+float ina219a_MMAvoltSum;
+float ina219a_MMAvoltAvg;
+const byte ina219a_MMAcount = 128;
+float shuntvoltage = 0;
+float busvoltage = 0;
+float current_mA = 0;
+float loadvoltage = 0;
+unsigned int ina219a_MMAmillis = 0;
+unsigned int ina219a_MMAloops = 0;
+
+

 // volatiles are subject to modification by IRQs
 volatile unsigned long raintime, rainlast, raininterval, rain;
@@ -301,14 +323,38 @@
   pinMode(PIN_UBIQUITI_DISABLE, OUTPUT);                 // prepares Ubiquiti power control pin
   digitalWrite(PIN_UBIQUITI_DISABLE, UBIQUITI_ENABLED);  // turns Ubiquiti on

+  // Ubiquiti takes 30 seconds to turn on and Ethernet takes 5; try to make them ready at the same time
+  // This a poor way to accomplish this task; better would be to ping
+  for (int i=0; i<30; i++) {
+    wdt_reset();
+    delay(1000);
+  }
+
   pinMode(PIN_ETH_DISABLE, OUTPUT);                     // prepares ETH power control pin
   digitalWrite(PIN_ETH_DISABLE, ETH_ENABLED);           // turns ETH shield on
+
+  // ETH takes 5 seconds to be ready to send when turned on
+  // This a poor way to accomplish this task; better would be to ping
+  for (int i=0; i<5; i++) {
+    wdt_reset();
+    delay(1000);
+  }
+
+  Ethernet.begin(mac, ip, dnsServer, gateway, subnet); // jjj Eth must be initialized after each power up
+
 }

 // Turns off power for network components to save power
 void disableEthernet() {
   pinMode(PIN_UBIQUITI_DISABLE, OUTPUT);                  // prepares Ubiquiti power control pin
   digitalWrite(PIN_UBIQUITI_DISABLE, UBIQUITI_DISABLED);  // turns Ubiquiti off
+
+                                             //             Unlike regular boots, the Ethernet shield's SPI pins will be active after a reset because of the Ariadne Bootloader.
+                                             //             When powering down the Ethernet shield, all connected pins must be set to low or preferrably inputs without pullups
+  pinMode(MOSI, INPUT);                      //             prevents leakage through ESD diodes
+  pinMode(MISO, INPUT);                      //             prevents leakage through ESD diodes
+  pinMode(SCK, INPUT);                       //             prevents leakage through ESD diodes
+  pinMode(SS, INPUT);                        //             prevents leakage through ESD diodes

   pinMode(PIN_ETH_DISABLE, OUTPUT);                      // prepares ETH power control pin
   digitalWrite(PIN_ETH_DISABLE, ETH_DISABLED);           // turns ETH shield off
@@ -354,7 +400,7 @@
 void wspeedIRQ()
 // Activated by the magnet in the anemometer (2 ticks per rotation), attached to input D3
 {
-    if (millis() - lastWindIRQ > 20) // Ignore switch-bounce glitches less than 10ms (142MPH max reading) after the reed switch closes. Now 20ms, 70mph max.
+    if (millis() - lastWindIRQ > 25) // Ignore switch-bounce glitches less than 10ms (142MPH max reading) after the reed switch closes. 20ms = 74mph max, 25ms = 60mph max
     {
         lastWindIRQ = millis(); //Grab the current time
         windClicks++; //There is 1.492MPH for each click per second.
@@ -410,6 +456,10 @@
       Serial.println("EEPROM eePowerSave was 255, is this a new Arduino? Setting to false (0).");
       EEPROM.update(eePowerSave, false);
     }
+
+    // Set the common GND source for "YYD-3" FET switches to LOW OUTPUT because it will need to be this way regardless of which bootup mode we're in
+    digitalWrite(30, LOW);                     //             must always be low
+    pinMode(30, OUTPUT);                       //             common GND source for "YYD-3" FET switches.

     // Check EEPROM to see if we should be in power save mode. If so, shut some stuff off immediately.
     Serial.print("Reading EEPROM to see power save state: ");
@@ -417,37 +467,13 @@
       Serial.print("Shutting off Eth and Ubiquiti... ");
       powerSave = true;

-      digitalWrite(30, LOW);                     //             must always be low
-      pinMode(30, OUTPUT);                       //             common GND source for "YYD-3" FET switches.
-
-      digitalWrite(PIN_UBIQUITI_DISABLE, LOW);   //             turns Ubiquiti off (on=HIGH / off=low, default=on)
-      pinMode(PIN_UBIQUITI_DISABLE, OUTPUT);     //             prepares Ubiquiti power control pin
-
-                                                 //             Unlike regular boots, the Ethernet shield's SPI pins will be active after a reset because of the Ariadne Bootloader.
-                                                 //             When powering down the Ethernet shield, all connected pins must be set to low or preferrably inputs without pullups
-      pinMode(MOSI, INPUT);                      //             prevents leakage through ESD diodes
-      pinMode(MISO, INPUT);                      //             prevents leakage through ESD diodes
-      pinMode(SCK, INPUT);                       //             prevents leakage through ESD diodes
-      pinMode(SS, INPUT);                        //             prevents leakage through ESD diodes
-                                                 //             next, power to Ethernet shield is turned off
-      digitalWrite(PIN_ETH_DISABLE, HIGH);       //             ETH shield off (on=low / off=HIGH, default=on)
-      pinMode(PIN_ETH_DISABLE, OUTPUT);          //             sets ETH power control pin to output
-
+      disableEthernet();

     } else {
       Serial.print("Turning on Eth and Ubiquiti... ");
       powerSave = false;
-                                                 //             The Ubiquiti will be powered on. It takes ?? seconds to establish a link
-      digitalWrite(PIN_UBIQUITI_DISABLE, HIGH);  //             Ubiquiti on (on=HIGH / off=low, default=on)
-      pinMode(PIN_UBIQUITI_DISABLE, OUTPUT);     //             sets Ubiquiti power control pin to output
-
-      digitalWrite(30, LOW);                     //             must always be low
-      pinMode(30, OUTPUT);                       //             common GND source for "YYD-3" FET switches.
-
-                                                 //             The Ethernet shield will be powered on (takes 3 seconds to go life).
-                                                 //             No need to reprogram the SPI pins, Ethernet.begin will do that (what about SS??)
-      digitalWrite(PIN_ETH_DISABLE, LOW);        //             ETH shield on (on=low / off=HIGH, default=on)
-      pinMode(PIN_ETH_DISABLE, OUTPUT);          //             sets ETH power control pin to output
+
+      enableEthernet();

       //Can't do this, it will set off the Watchdog. We can discuss disabling the watchdog, but I consider this a poor way to accomplish this task.
       //delay(30000);                            //             give eth and U 30 seconds time to boot up (better would be to  ping!)
@@ -458,7 +484,6 @@

     //Weather Station stuff
     pinMode(STAT1, OUTPUT); //Status LED Blue
-    pinMode(STAT2, OUTPUT); //Status LED Green

     pinMode(WSPEED, INPUT_PULLUP); // input from wind meters windspeed sensor
     pinMode(RAIN, INPUT_PULLUP); // input from wind meters rain gauge sensor
@@ -886,12 +911,19 @@
       * * * * * * * * * * * * * * * * * */
       // Turn off / on some peripherals at night & morning
       int minutesToday = hour() * 60 + minute();
+
+#ifdef FOURMINUTEDAY
+      if ( (minute() / 6) % 2 ) {
+        Serial.println("   !!DEBUG: Cycling to NIGHT every FOUR minutes because of ""#define FOURMINUTEDAY""");
+
+#else
       Serial.print("Minute of day is: ");
       Serial.print(minutesToday);
-      if ( (minutesToday < sunrise) or (minutesToday > sunset - 60) ) {     // jjj removed 60 to save even more   if ( (minutesToday < sunrise - 60) or (minutesToday > sunset - 60) ) {
+      if ( (minutesToday < sunrise) or (minutesToday > sunset - 60) ) {

         Serial.print(", which is Night time. We will switch to day at minute #");
         Serial.println(sunrise);     // jjj removed 60 to save even more     Serial.println(sunrise - 60);
+#endif
         // We're not between "half an hour before sunrise" and sunset, so turn stuff off.
         // First set variables and record in eeprom that we're in power save mode.
         if (!powerSave) {
@@ -912,11 +944,13 @@
           //if powerSave was set, that means we're transitioning to daytime now.
           // Until I figure out how to restart the Ethernet, just force a watchdog timeout with delays.
           enableEthernet();
-
+
+          /* No longer needed?
           Serial.println(F("   ! ! !   We just switched to DAY. Since we can't reset ETHERNET very well, we are rebooting soon!!! ! ! "));
           delay(10000);
           delay(20000);
           delay(30000);
+          */
         }

         //This below kind of doesn't count, because of the reboot above. We really should never get here.
@@ -1037,6 +1071,30 @@
     }
   } //END if(!ethStopped)

+
+  //INA 219 averaging. Shoot for maybe 80-120 readings a second?
+  if (ina219a_MMAmillis + 8 < millis()) {
+
+    shuntvoltage = ina219a.getShuntVoltage_mV();
+    busvoltage = ina219a.getBusVoltage_V();
+    ina219a_MMAtemp = busvoltage + (shuntvoltage / 1000);
+
+    ina219a_MMAvoltSum -= ina219a_MMAvoltAvg;
+    ina219a_MMAvoltSum += ina219a_MMAtemp;
+    ina219a_MMAvoltAvg  = ina219a_MMAvoltSum / ina219a_MMAcount;
+    ina219a_volts = ina219a_MMAvoltAvg;
+
+    ina219a_MMAtemp = ina219a.getCurrent_mA();
+    ina219a_MMAcurrentSum -= ina219a_MMAcurrentAvg;
+    ina219a_MMAcurrentSum += ina219a_MMAtemp;
+    ina219a_MMAcurrentAvg  = ina219a_MMAcurrentSum / ina219a_MMAcount;
+    ina219a_current = ina219a_MMAcurrentAvg * -1; // * -1 because it's wired backwards for convenience. Gotta reverse the sign.
+
+    ina219a_MMAloops++;
+
+  }
+
+
   loopCounter++;
 } // END OF LOOP()

@@ -1083,7 +1141,7 @@
 // NOTE if this is disabled, everything runs on battery power, even in daytime.
 void enableSolar() {
   Serial.println("Solar panel ENABLED via enableSolar();");
-  pinMode(PIN_SOLAR_DISABLE, OUTPUT);                 // prepares Solar Panel control pin
+  pinMode(PIN_SOLAR_DISABLE, INPUT);                 // prepares Solar Panel control pin
   digitalWrite(PIN_SOLAR_DISABLE, SOLAR_ENABLED);     // turns Solar Panel on

 }
@@ -1193,28 +1251,14 @@
     }

     //Get voltage and current from INA219 sensors
-    float shuntvoltage = 0;
-    float busvoltage = 0;
     float current_mA = 0;
-    float loadvoltage = 0;
     float avg_plus = 0;
     float avg_minus = 0;

     // INA219 AAAAAA
-    shuntvoltage = ina219a.getShuntVoltage_mV();
-    busvoltage = ina219a.getBusVoltage_V();
-    current_mA = ina219a.getCurrent_mA();
-    loadvoltage = busvoltage + (shuntvoltage / 1000);
-
-    avg_plus  = loadvoltage / VOLTAGE_AVG_SIZE;
-    avg_minus = ina219a_volts / VOLTAGE_AVG_SIZE;
-    ina219a_volts = ina219a_volts - avg_minus + avg_plus;
-
-    avg_plus = current_mA / VOLTAGE_AVG_SIZE;
-    avg_minus = ina219a_current / VOLTAGE_AVG_SIZE;
-    ina219a_current = ina219a_current -avg_minus + avg_plus;
-
-    // INA219 BBBBBB
+    // Now calculated near the end of loop() with an MMA targeting ~100 samples a second.
+
+    // INA219 BBBBBB   <-- this one isn't exposed to PWM voltage, so we'll just leave it.
     shuntvoltage = ina219b.getShuntVoltage_mV();
     busvoltage = ina219b.getBusVoltage_V();
     current_mA = ina219b.getCurrent_mA();
@@ -1325,25 +1369,25 @@
     // Each threshold is the midpoint between adjacent headings. The output is degrees for that ADC reading.
     // Note that these are not in compass degree order! See Weather Meters datasheet for more information.

-    if (adc < 380) { strWindDir = "ESE"; return (113); }    // ESE
-    if (adc < 393) { strWindDir = "ENE"; return  (68); }    // ENE
-    if (adc < 414) { strWindDir = "E";   return  (90); }    // E
-    if (adc < 456) { strWindDir = "SSE"; return (158); }    // SSE
-    if (adc < 508) { strWindDir = "SE";  return (135); }    //  SE
-    if (adc < 551) { strWindDir = "SSW"; return (203); }    // SSW
-    if (adc < 615) { strWindDir = "S";   return (180); }    // S
-    if (adc < 680) { strWindDir = "NNE"; return  (23); }    // NNE
-    if (adc < 746) { strWindDir = "NE";  return  (45); }    //  NE
-    if (adc < 801) { strWindDir = "WSW"; return (248); }    // WSW
-    if (adc < 833) { strWindDir = "SW";  return (225); }    //  SW
-    if (adc < 878) { strWindDir = "NNW"; return (338); }    // NNW
-    if (adc < 913) { strWindDir = "N";   return   (0); }    // N
-    if (adc < 940) { strWindDir = "WNW"; return (293); }    // WNW
-    if (adc < 967) { strWindDir = "NW";  return (315); }    //  NW
-    if (adc < 990) { strWindDir = "W";   return (270); }    // W
-    if (adc < 1010) {strWindDir = "W";   return (270); }    // W - Sometimes 270 returns higher than 990.
-    strWindDir = "ERR";
-    return (-10); // error, disconnected?
+    if      (adc < 81)   { strWindDir = "ERL"; return (-10); }
+    else if (adc < 162)  { strWindDir = "ESE"; return (113); }   // ESE
+    else if (adc < 188)  { strWindDir = "ENE"; return  (68); }   // ENE
+    else if (adc < 227)  { strWindDir = "E";   return  (90); }   // E
+    else if (adc < 305)  { strWindDir = "SSE"; return (158); }   // SSE
+    else if (adc < 395)  { strWindDir = "SE";  return (135); }   // SE
+    else if (adc < 466)  { strWindDir = "SSW"; return (203); }   // SSW
+    else if (adc < 559)  { strWindDir = "S";   return (180); }   // S
+    else if (adc < 651)  { strWindDir = "NNE"; return  (23); }   // NNE
+    else if (adc < 733)  { strWindDir = "NE";  return  (45); }   // NE
+    else if (adc < 800)  { strWindDir = "WSW"; return (248); }   // WSW
+    else if (adc < 835)  { strWindDir = "SW";  return (225); }   // SW
+    else if (adc < 883)  { strWindDir = "NNW"; return (338); }   // NNW
+    else if (adc < 919)  { strWindDir = "N";   return   (0); }   // N
+    else if (adc < 945)  { strWindDir = "WNW"; return (293); }   // WNW
+    else if (adc < 974)  { strWindDir = "NW";  return (315); }   // NW
+    else if (adc < 1005) { strWindDir = "W";   return (270); }   // W
+    else                 { strWindDir = "ERH"; return (-10); }
+    return (-10); // Never get here
 }

@@ -1537,7 +1581,9 @@

   // Connect to CSS website, do a PUT with weather values. Should be called once for every minute of weather data.
   logSome(F("  uploadWeather called, building string. Bytes free: "));
-  logOneLine(freeRam());
+  logSome(freeRam());
+  logSome(". ina219a readings this minute: ");
+  logOneLine(ina219a_MMAloops);
   byte uploadStatus = 90; //90 = haven't tried stopping the client yet.

   // Preemptively close any open connections, to keep sockets available.
@@ -1701,37 +1747,43 @@
     weatherString += "0";
   }

-  // 12b: temperature, F, inside BB from BME280b, instant
+  // 13 (was 12b): temperature, F, inside BB from BME280b, instant
   weatherString += String(charComma);
   weatherString += String(bme280b.readTempF(), 2);

-  // 12c: humidity, %, inside BB bme280b, instant (for checking dewpoint eventually)
+  // 14 (was 12c): humidity, %, inside BB bme280b, instant (for checking dewpoint eventually)
   weatherString += String(charComma);
   weatherString += String(bme280b.readFloatHumidity(), 0);

-  // 13: Current on ina219 sensor A (raw battery @ 12v maybe?)
+  // 15: Current on ina219 sensor A (Solar Panel / CC @ 12v maybe?)
   weatherString += String(charComma);
-  weatherString += String(ina219a_current, 2);
+  if (ina219a_current < 1000) weatherString += "0";
+  if (ina219a_current < 100)  weatherString += "0";
+  if (ina219a_current < 10)   weatherString += "0";
+  weatherString += String(ina219a_current, 0);
   //weatherString += String("mA");

-  // 14: Voltage on ina219 sensor A (raw battery @ 12v maybe?)
+  // 16: Voltage on ina219 sensor A (Solar Panel @ 12v maybe?)
   weatherString += String(charComma);
   weatherString += String(ina219a_volts, 2);
   //weatherString += String("v");
   //weatherString += String(batt_lvl, 2);

-  // 15: Power on ina219 sensor A (watts battery)
+  // 17: Power on ina219 sensor A (watts battery)
 //  weatherString += String(charComma);
 //  weatherString += String(ina219a_volts * ina219a_current / 1000, 2);
 //  weatherString += String("w");

-  // 16: Current on ina219 sensor B (after buck to 5v maybe?)
+  // 17: Current on ina219 sensor B (after buck to 5v maybe?)
   weatherString += String(charComma);
-  weatherString += String(ina219b_current, 2);
+  if (ina219b_current < 1000) weatherString += "0";
+  if (ina219b_current < 100)  weatherString += "0";
+  if (ina219b_current < 10)   weatherString += "0";
+  weatherString += String(ina219b_current, 0);
   //weatherString += String("mA");

-  // 17: Voltage on ina219 sensor A (after buck to 5v maybe?)
+  // 18: Voltage on ina219 sensor A (after buck to 5v maybe?)
   weatherString += String(charComma);
   weatherString += String(ina219b_volts, 2);
   //weatherString += String("v");
@@ -1749,11 +1801,11 @@
 //    weatherString += String(light_lvl, 2);
 //  weatherString += "0";

-  // 20: run time in days.HH:MM:SS
+  // 19: run time in H:MM:SS
   weatherString += String(charComma);
-  weatherString += String(days);
-  weatherString += String(".");
-  if (hours < 10) weatherString += String('0');
+  //weatherString += String(days);
+  //weatherString += String(".");
+  //if (hours < 10) weatherString += String('0');
   weatherString += String(hours);
   weatherString += String(":");
   if (minutes < 10) weatherString += String('0');
@@ -1773,7 +1825,7 @@
 //    weatherString += String(charComma);
 //    weatherString += String(freeRam());

-  // 21: print raw wind direction ADC reading, to see why 270 degree sometimes comes back as "invalid"
+  // 20: print raw wind direction ADC reading, to see why 270 degree sometimes comes back as "invalid"
   if (true) {
     weatherString += String(charComma);
     weatherString += String("wd=");
@@ -1786,7 +1838,7 @@
     weatherString += strWindDir;
   }

-  // 22+: Assorted info and error values
+  // 21+: Assorted info and error values
   // Tack on a ,R if we've rebooted to make it easier to spot them
   if(justRestarted) {
     weatherString += ",R";


- change the data format of datastr from its original form (dd/mm/yy) into UTC format - force each number in utcstr to have two digits - changes the original "values=xxxxx" to multiple "value-X=xxxxx", where X is the sensor type identifiers as described in the program - revise the MQTT message format with detailed GPS info. This is a preparation for future integration of MongoDB - add descriptions for sensor types - update the location format in MQTT to support GeoJSON format - the version number is also changed to v0.7.0, as the changes made in this batch are not minor.

--- Device_LinkItOne/LASS/LASS.ino
+++ Device_LinkItOne/LASS/LASS.ino
@@ -1,5 +1,3 @@
-
-
 /*
 	Location Aware Sensor System(LASS) by Linkit ONE

@@ -38,6 +36,20 @@
           10: dust sensor, 11: UV  sensor, 12: sound sensor
         Default user sensor order in APP-3 (MAPS):
           10: barometer sensor (high accuracy), 11&12: temperature & humidity sensor pro, 13: digital light sensor
+
+	Default Sensor Type: ( -: void;  0-9: reserved for system sensor;  A-Z: Grove sensors;  a-z: reserved for customized sensors)
+		-: unused
+		0: record ID
+		1: battery level
+		2: battery charging
+		3: ground speed
+		D: dust sensor
+		U: UV sensor
+		S: sound sensor
+		B: barometer sensor (hPa)
+		T: temperature sensor (degree C)
+		H: humidity sensor (%)
+		L: light sensor (LUX)

         Original:
           The idea come from here: http://iot-hackseries.s3-website-us-west-2.amazonaws.com/linkitone-setup.html
@@ -81,7 +93,7 @@
 #define VER_FORMAT "1"
 #define FMT_OPT 0 // FMT_OPT : 0: default format with gps, 1: default format but gps is fix data, need to update GPS_FIX_INFOR
     // ( format is right, but no actual gps information because no gps device exist )
-#define VER_APP "0.6.6"
+#define VER_APP "0.7.0"

 #define POLICY_ONLINE_ALWAYS 1
@@ -113,7 +125,8 @@
 #define LED_MODE LED_MODE_DEFAULT

 int period_target[2][3]= // First index is POLICY_POLICY[Sensing period],[Upload period],[Wifi check period], unit is second
-  {10,0,60, // don't care power
+//  {10,0,60, // don't care power
+  {10,10,60, // don't care power
    10,600,300  // power saving
   };

@@ -124,11 +137,9 @@
 #define APP_ID 3               // REPLACE: this is your unique application 0-255: system reserved, 256-32767: user public use, 32768-65536: private purpose
 #if APP_ID==1
   #define APP_NAME "EXAMPLE_APP1" // REPLACE: this is your unique application name
-#endif
-#if APP_ID==2
+#elif APP_ID==2
   #define APP_NAME "EXAMPLE_APP2" // REPLACE: this is your unique application name
-#endif
-#if APP_ID==3
+#elif APP_ID==3
   #define APP_NAME "MAPS" // REPLACE: this is your unique application name
   #include <DHT_linkit.h>     // Reference: https://github.com/Seeed-Studio/Grove_Starter_Kit_For_LinkIt/tree/master/libraries/Humidity_Temperature_Sensor
   #include <Digital_Light_TSL2561.h>  // Reference:  http://www.seeedstudio.com/wiki/Grove_-_Digital_Light_Sensor
@@ -157,15 +168,11 @@
   #define SENSOR_ID_DUST_BLYNK 4
   #define SENSOR_ID_UV_BLYNK 5
   #define SENSOR_ID_SOUND_BLYNK 6
-#endif
-
-#if APP_ID==2
+#elif APP_ID==2
   #define SENSOR_ID_DUST 10

   #define SENSOR_ID_DUST_BLYNK 4
-#endif
-
-#if APP_ID==3
+#elif APP_ID==3
   #define SENSOR_ID_BAROMETER 10
   #define SENSOR_ID_TEMPERATURE 11
   #define SENSOR_ID_HUMIDITY 12
@@ -218,6 +225,12 @@
 double ground_speed;
 #define GPS_SIGNAL_NOCHECK 1   // 0: log or send only when GPS have signal, 1: always log and send even when GPS have no signal
 #define GPS_FIX_INFOR "$GPGGA,064205.096,0,N,0,E,0,0,,207.8,M,15.0,M,,*4F\r" // If the device don't have GPS, setup the FIX GPS information here. The checksum don't need to be correct
+/// new variables starting from v0.7.0
+char str_GPS_location[60];
+char str_GPS_quality[5];
+char str_GPS_satellite[5];
+char str_GPS_altitude[10];
+

 //----- WIFI -----
 //System default wifi setting: SSID=LASS, PASS=LASS123456, WIFI_AUTH=LWIFI_WPA
@@ -228,8 +241,9 @@

 //----- SENSORS -----
 #define SENSOR_CNT 20          // REPLACE: the sensors count that publish to server.
+char sensorType[SENSOR_CNT];
 float sensorValue[SENSOR_CNT];
-#define SENSOR_STRING_MAX 150
+#define SENSOR_STRING_MAX 300
 char sensorUploadString[SENSOR_STRING_MAX]; //buffer // Please extend this if you need

@@ -609,7 +623,26 @@
   for(i=0;i<SENSOR_CNT;i++)
   {
    sensorValue[i]=0;
-  }
+   sensorType[i] = '-';
+  }
+
+  sensorType[0] = '0';
+  sensorType[1] = '1';
+  sensorType[2] = '2';
+  sensorType[3] = '3';
+#if APP_ID == 1
+  sensorType[10] = 'D';
+  sensorType[11] = 'U';
+  sensorType[12] = 'S';
+#elif APP_ID == 2
+  sensorType[10] = 'D';
+#elif APP_ID == 3
+  sensorType[10] = 'B';
+  sensorType[11] = 'T';
+  sensorType[12] = 'H';
+  sensorType[13] = 'L';
+#endif
+

 }
 // please customize the how to get the sensor data and store to sensorValue[]
@@ -652,8 +685,7 @@
       sensorValue[SENSOR_ID_SOUND] = get_sensor_data_sound();
       Serial.print("SensorValue(Sound):");
       Serial.println(sensorValue[SENSOR_ID_SOUND]);
-#endif    //if( APP_ID == 1)
-#if APP_ID == 2
+#elif APP_ID == 2
       Serial.print("[Performence TIME-COUNT]:");
       timecount=millis()-timecount;
       Serial.println(timecount);
@@ -661,8 +693,7 @@
       sensorValue[SENSOR_ID_DUST] = (float)pm25sensorG3();
       Serial.print("[SENSOR-DUST]:");
       Serial.println(sensorValue[SENSOR_ID_DUST]);
-#endif
-#if APP_ID == 3
+#elif APP_ID == 3
       sensorValue[SENSOR_ID_BAROMETER] = get_sensor_data_barometer();
       Serial.print("SensorValue(Barometer):");
       Serial.println(sensorValue[SENSOR_ID_BAROMETER]);
@@ -685,6 +716,7 @@
       Serial.print("SensorValue(Light):");
       Serial.println(sensorValue[SENSOR_ID_LIGHT]);
 #endif
+
   msg_sensor = "|values=";
   int i;
   for(i=0;i<SENSOR_CNT;i++)
@@ -692,8 +724,25 @@
     if(i>0){
        msg_sensor.concat(",");
     }
-    msg_sensor.concat(sensorValue[i]);
-  }
+    msg_sensor.concat(sensorValue[i]);
+  }
+
+  ////========================
+  //// keep the original output first, and add new messages below
+  //// note that the new message format is not confirmed by LASS yet and may be changed in the future versions
+  ////========================
+  //msg_sensor = "";
+  //int i;
+  for(i=0;i<SENSOR_CNT;i++)
+  {
+    if (sensorType[i] != '-'){
+      msg_sensor.concat("|data-");
+      msg_sensor.concat(sensorType[i]);
+      msg_sensor.concat("=");
+      msg_sensor.concat(sensorValue[i]);
+    }
+  }
+
   if(msg_sensor.length()<SENSOR_STRING_MAX){
     msg_sensor.toCharArray(sensorUploadString, msg_sensor.length()+1);
   }else{
@@ -743,16 +792,13 @@
 {
   Blynk.virtualWrite(SENSOR_ID_SOUND_BLYNK, sensorValue[SENSOR_ID_SOUND]);
 }
-#endif
-#if APP_ID==2
+#elif APP_ID==2
 BLYNK_READ(SENSOR_ID_DUST_BLYNK)
 {
   Blynk.virtualWrite(SENSOR_ID_DUST_BLYNK, sensorValue[SENSOR_ID_DUST]);
 }

-#endif
-
-#if APP_ID==3
+#elif APP_ID==3
 BLYNK_READ(SENSOR_ID_BAROMETER_BLYNK)
 {
   Blynk.virtualWrite(SENSOR_ID_BAROMETER_BLYNK, sensorValue[SENSOR_ID_BAROMETER]);
@@ -906,6 +952,18 @@
       msg_tmp.concat("|device=");
       msg_tmp.concat(DEVICE_TYPE);
       msg_tmp.concat(sensorUploadString);
+      // v0.7.0, added for future integration with backend DB
+
+      msg_tmp.concat("|gps-loc=");
+      msg_tmp.concat(str_GPS_location);
+      msg_tmp.concat("|gps-fix=");
+      msg_tmp.concat(str_GPS_quality);
+      msg_tmp.concat("|gps-num=");
+      msg_tmp.concat(str_GPS_satellite);
+      msg_tmp.concat("|gps-alt=");
+      msg_tmp.concat(str_GPS_altitude);
+/*
+      // the following content is kept in v0.7.0, but should be removed in the next version
       // default gps result, must have.
       msg_tmp.concat("|gps=");
       if(FMT_OPT==0){
@@ -914,7 +972,8 @@
         msg_tmp.concat((char*)GPS_FIX_INFOR);

       }
-      //msg_tmp.concat("|gpgga=");
+*/
+//msg_tmp.concat("|gpgga=");
       //msg_tmp.concat((char*)info.GPGGA);
       //msg_tmp.concat("|gpgsa=");
       //msg_tmp.concat((char*)info.GPGSA);
@@ -940,7 +999,7 @@
           msg_tmp.toCharArray(msg, msg_tmp.length()); // the last char will be NULL, design to replace \n
       }else{
         msg[0]=0;
-        Serial.println("MSG buffer overflow!");
+        Serial.println("MSG buffer overflow! Length = " + msg_tmp.length());
       }

         break;
@@ -1167,7 +1226,8 @@
     second    = (GPGGAstr[tmp + 4] - '0') * 10 + (GPGGAstr[tmp + 5] - '0');

     sprintf(buff_tmp, "\tUTC timer %2d-%2d-%2d", hour, minute, second);
-    sprintf(utcstr,"%d:%d:%d",hour,minute,second);
+    // sprintf(utcstr,"%d:%d:%d",hour,minute,second);
+    sprintf(utcstr,"%02d:%02d:%02d",hour,minute,second); // force each number to have two digits
     Serial.println(buff_tmp);

     tmp = getComma(2, GPGGAstr);
@@ -1176,10 +1236,26 @@
     longitude = getDoubleNumber(&GPGGAstr[tmp]);
     sprintf(buff_tmp, "\tlatitude = %10.4f, longitude = %10.4f", latitude, longitude);
     Serial.println(buff_tmp);
+    //// the legacy geospatial format for MongoDB v2.4 and before
+    //sprintf(str_GPS_location,"[ %5.6f , %5.6f ]", latitude/100, longitude/100);
+    //// follow GeoJSON format
+    sprintf(str_GPS_location,"{ type:\"Point\",  coordinates: [%5.6f , %5.6f ] }", latitude/100, longitude/100);
+
+    tmp = getComma(6, GPGGAstr);
+    num = getIntNumber(&GPGGAstr[tmp]);
+    sprintf(buff_tmp, "\tGPS fix quality = %d", num);
+    sprintf(str_GPS_quality,"%d",num);

     tmp = getComma(7, GPGGAstr);
     num = getIntNumber(&GPGGAstr[tmp]);
     sprintf(buff_tmp, "\tsatellites number = %d", num);
+    sprintf(str_GPS_satellite,"%d",num);
+
+    tmp = getComma(9, GPGGAstr);
+    num = getIntNumber(&GPGGAstr[tmp]);
+    sprintf(buff_tmp, "\taltitude above mean sea level = %d meters", num);
+    sprintf(str_GPS_altitude,"%d",num);
+
     if(num>0 || GPS_SIGNAL_NOCHECK ) {
       gps_ready=1;
     }else{
@@ -1225,7 +1301,8 @@
     year    = (GPRMCstr[tmp + 4] - '0') * 10 + (GPRMCstr[tmp + 5] - '0');

     sprintf(buff_tmp, "\tDate(DD/MM/YY):%d/%d/%d", day, month, year);
-    sprintf(datestr,"%d/%d/%d",day,month,year);
+    // sprintf(datestr,"%d/%d/%d",day,month,year);
+    sprintf(datestr,"20%02d-%02d-%02d",year,month,day);  // use the UTC format for datestr
     Serial.println(buff_tmp);
   }
   else


Don't pulse error led if avrdude enters programming mode twice

--- build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
+++ build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
@@ -581,12 +581,8 @@
       empty_reply();
       break;
     case 'P':
-      if (pmode) {
-        pulse(LED_ERR, 3);
-      }
-      else {
+      if (!pmode)
         start_pmode();
-      }
       empty_reply();
       break;
     case 'U': // set address (word)


Whitespace and brackets. Variable names.

--- dimmertask.ino
+++ dimmertask.ino
@@ -4,12 +4,8 @@

   TickType_t xLastWakeTime;

-  if ( defaultTimersLoaded() )
-  {
-    ESP_LOGI( TAG, "Default timers loaded." );
-  }
-  else
-  {
+  if ( defaultTimersLoaded() ) ESP_LOGI( TAG, "Default timers loaded." );
+  else {
     ESP_LOGI( TAG, "No timers loaded." );
     setEmptyTimers();
   }
@@ -20,51 +16,46 @@
   channel[ 2 ].pin = LED2_PIN;
   channel[ 3 ].pin = LED3_PIN;
   channel[ 4 ].pin = LED4_PIN;
-  for ( uint8_t channelNumber = 0; channelNumber < NUMBER_OF_CHANNELS; channelNumber++ )
-  {
+  for ( uint8_t num = 0; num < NUMBER_OF_CHANNELS; num++ ) {
     char NVSKeyName[32];

-    snprintf( NVSKeyName, sizeof( NVSKeyName ), "channelname%i", channelNumber );
-    snprintf( channel[ channelNumber ].name, sizeof( channel[ channelNumber ].name ), preferences.getString( NVSKeyName, "channelname" ).c_str() );
+    snprintf( NVSKeyName, sizeof( NVSKeyName ), "channelname%i", num );
+    snprintf( channel[ num ].name, sizeof( channel[ num ].name ), preferences.getString( NVSKeyName, "channelname" ).c_str() );

-    snprintf( NVSKeyName, sizeof( NVSKeyName ), "channelcolor%i", channelNumber );
-    snprintf( channel[ channelNumber ].color, sizeof( channel[ channelNumber ].color ), preferences.getString( NVSKeyName, "#fffe7a" ).c_str() );
+    snprintf( NVSKeyName, sizeof( NVSKeyName ), "channelcolor%i", num );
+    snprintf( channel[ num ].color, sizeof( channel[ num ].color ), preferences.getString( NVSKeyName, "#fffe7a" ).c_str() );

-    snprintf( NVSKeyName, sizeof( NVSKeyName ), "channelminimum%i", channelNumber );
-    channel[ channelNumber ].minimumLevel  = preferences.getFloat( NVSKeyName, 0  );
+    snprintf( NVSKeyName, sizeof( NVSKeyName ), "channelminimum%i", num );
+    channel[ num ].minimumLevel  = preferences.getFloat( NVSKeyName, 0  );

-    ledcAttachPin( channel[channelNumber].pin, channelNumber);
+    ledcAttachPin( channel[num].pin, num);
   }

   setupDimmerPWMfrequency( preferences.getDouble( "pwmfrequency", LEDC_MAXIMUM_FREQ ),
                            preferences.getUInt( "pwmdepth", LEDC_NUMBER_OF_BIT ) );
+  leds.setState( LIGHTS_AUTO );

-  leds.setState( LIGHTS_AUTO );
+  ESP_LOGI( TAG, "Lights running after %.1f seconds.", millis() / 1000.0 );

   xLastWakeTime = xTaskGetTickCount();

-  ESP_LOGI( TAG, "Lights running after %.1f seconds.", millis() / 1000.0 );
+  while (1) {

-  while (1)
-  {
-    if ( leds.state() != LIGHTS_AUTO )
-    {
-      uint16_t pwmValue = ( leds.state() == LIGHTS_OFF ) ? 0 : ledcMaxValue;
+    if ( leds.state() != LIGHTS_AUTO ) {
+      lightState_t currentState = leds.state();
+      uint16_t pwmValue = ( currentState == LIGHTS_OFF ) ? 0 : ledcMaxValue;
       float percentage = ( pwmValue == 0 ) ? 0 : 100;
-      for ( uint8_t channelNumber = 0; channelNumber < NUMBER_OF_CHANNELS; channelNumber++ )
-      {
-        channel[channelNumber].currentPercentage = percentage;
-        ledcWrite( channelNumber, pwmValue );
+      for ( uint8_t num = 0; num < NUMBER_OF_CHANNELS; num++ ) {
+        channel[num].currentPercentage = percentage;
+        ledcWrite( num, pwmValue );
       }
+      while ( leds.state() == currentState ) delay( 100 );
     }
-    else
-    {
+    else {
       struct timeval microSecondTime;
-
       gettimeofday( &microSecondTime, NULL );

       struct tm *localTime;
-
       localTime = localtime( &microSecondTime.tv_sec );

       suseconds_t milliSecondsToday = ( localTime->tm_hour       * 3600000U ) +
@@ -72,49 +63,43 @@
                                       ( localTime->tm_sec        * 1000U ) +
                                       ( microSecondTime.tv_usec  / 1000U );

-      if ( milliSecondsToday ) /* to solve flashing at 00:00:000 due to the fact that the first timer has no predecessor */
-      {
-        for ( uint8_t channelNumber = 0; channelNumber < NUMBER_OF_CHANNELS; channelNumber++ )
-        {
+      if ( milliSecondsToday ) { /* to solve flashing at 00:00:000 due to the fact that the first timer has no predecessor */
+        for ( uint8_t num = 0; num < NUMBER_OF_CHANNELS; num++ ) {
           uint8_t thisTimer = 0;

-          while ( channel[channelNumber].timer[thisTimer].time * 1000U < milliSecondsToday )
-          {
+          while ( channel[num].timer[thisTimer].time * 1000U < milliSecondsToday )
             thisTimer++;
-          }

           float newPercentage;

           /* only do a lot of math if really neccesary */
-          if ( channel[channelNumber].timer[thisTimer].percentage != channel[channelNumber].timer[thisTimer - 1].percentage )
-          {
+          if ( channel[num].timer[thisTimer].percentage != channel[num].timer[thisTimer - 1].percentage ) {
             newPercentage = mapFloat( milliSecondsToday,
-                                      channel[channelNumber].timer[thisTimer - 1].time * 1000U,
-                                      channel[channelNumber].timer[thisTimer].time * 1000U,
-                                      channel[channelNumber].timer[thisTimer - 1].percentage,
-                                      channel[channelNumber].timer[thisTimer].percentage );
+                                      channel[num].timer[thisTimer - 1].time * 1000U,
+                                      channel[num].timer[thisTimer].time * 1000U,
+                                      channel[num].timer[thisTimer - 1].percentage,
+                                      channel[num].timer[thisTimer].percentage );
           }
-          else
-          {
+          else {
             /* timers are equal so no math neccesary */
-            newPercentage = channel[channelNumber].timer[thisTimer].percentage;
+            newPercentage = channel[num].timer[thisTimer].percentage;
           }

           /* check if channel has a minimum set */
-          if ( !MOON_SIMULATOR && newPercentage < channel[channelNumber].minimumLevel )
-            newPercentage = channel[channelNumber].minimumLevel;
+          if ( !MOON_SIMULATOR && newPercentage < channel[num].minimumLevel )
+            newPercentage = channel[num].minimumLevel;

           /* calculate moon light */
-          if ( MOON_SIMULATOR && newPercentage < ( channel[channelNumber].minimumLevel * moonData.percentLit ) )
-            newPercentage = channel[channelNumber].minimumLevel * moonData.percentLit;
+          if ( MOON_SIMULATOR && newPercentage < ( channel[num].minimumLevel * moonData.percentLit ) )
+            newPercentage = channel[num].minimumLevel * moonData.percentLit;

           /* done, set the channel */
-          channel[channelNumber].currentPercentage = newPercentage;
-          ledcWrite( channelNumber, mapFloat( channel[channelNumber].currentPercentage,
-                                              0,
-                                              100,
-                                              0,
-                                              ledcMaxValue ) );
+          channel[num].currentPercentage = newPercentage;
+          ledcWrite( num, mapFloat( channel[num].currentPercentage,
+                                    0,
+                                    100,
+                                    0,
+                                    ledcMaxValue ) );
         }
       }
     }
@@ -122,81 +107,61 @@
   }
 }

-bool defaultTimersLoaded()
-{
+bool defaultTimersLoaded() {
   //find 'default.aqu' on selected storage and if present load the timerdata from this file
   //return true on success
   //return false on error

-  if ( !FFat.exists( defaultTimerFile ) )
-  {
+  if ( !FFat.exists( defaultTimerFile ) ) {
     ESP_LOGI( TAG, "No default timer file found. [%s]", defaultTimerFile );
     return false;
   }

   File f = FFat.open( defaultTimerFile, "r" );
-
-  if ( !f.available() )
-  {
+  if ( !f.available() ) {
     ESP_LOGI( TAG, "Error opening default timer file. [%s]", defaultTimerFile );
     return false;
   }
-  String lineBuf;
   byte currentTimer = 0;
-  byte thisChannel;
-  while ( f.position() < f.size() )
-  {
-    lineBuf = f.readStringUntil( '\n' );
-    if ( lineBuf.indexOf( "[" ) > -1 )
-    {
-      String thisChannelStr;
-      thisChannelStr = lineBuf.substring( lineBuf.indexOf("[") + 1, lineBuf.indexOf("]") );
-      thisChannel = thisChannelStr.toInt();
+  uint8_t chan;
+  //String data;
+  while ( f.position() < f.size() ) {
+    String data = f.readStringUntil( '\n' );
+    if ( 0 == data.indexOf( "[" ) ) {
+      chan = data.substring( 1, 3 ).toInt();
       currentTimer = 0;
     }
-    else if ( currentTimer < MAX_TIMERS - 1 )
-    {
-      String thisPercentage;
-      String thisTime;
-      thisTime = lineBuf.substring( 0, lineBuf.indexOf(",") );
-      thisPercentage = lineBuf.substring( lineBuf.indexOf(",") + 1 );
-      channel[thisChannel].timer[currentTimer].time = thisTime.toInt();
-      channel[thisChannel].timer[currentTimer].percentage = thisPercentage.toInt();
+    else if ( currentTimer < MAX_TIMERS - 1 ) {
+      channel[chan].timer[currentTimer].time = data.substring( 0, data.indexOf(",") ).toInt();
+      channel[chan].timer[currentTimer].percentage = data.substring( data.indexOf(",") + 1 ).toInt();
       currentTimer++;
-      channel[thisChannel].numberOfTimers = currentTimer;
+      channel[chan].numberOfTimers = currentTimer;
     }

   }
   f.close();
   //add the 24:00 timers ( copy of timer percentage no: 0 )
-  for ( thisChannel = 0; thisChannel < NUMBER_OF_CHANNELS; thisChannel++ )
-  {
-    channel[thisChannel].timer[channel[thisChannel].numberOfTimers].time = 86400;
-    channel[thisChannel].timer[channel[thisChannel].numberOfTimers].percentage = channel[thisChannel].timer[0].percentage;
+  for (chan = 0; chan < NUMBER_OF_CHANNELS; chan++ ) {
+    channel[chan].timer[channel[chan].numberOfTimers].time = 86400;
+    channel[chan].timer[channel[chan].numberOfTimers].percentage = channel[chan].timer[0].percentage;
     currentTimer++;
-    channel[thisChannel].numberOfTimers = currentTimer;
+    channel[chan].numberOfTimers = currentTimer;
   }
   return true;
 }

-void setEmptyTimers()
-{
-  for ( byte channelNumber = 0; channelNumber < NUMBER_OF_CHANNELS; channelNumber++)
-  {
-    channel[channelNumber].timer[0].time = 0;
-    channel[channelNumber].timer[0].percentage = 0;
-    channel[channelNumber].timer[1].time = 86400;
-    channel[channelNumber].timer[1].percentage = 0;
-    channel[channelNumber].numberOfTimers = 1;
+void setEmptyTimers() {
+  for ( uint8_t num = 0; num < NUMBER_OF_CHANNELS; num++) {
+    channel[num].timer[0] = {0, 0};
+    channel[num].timer[1] = {86400, 0};
+    channel[num].numberOfTimers = 1;
   }
 }

-void setupDimmerPWMfrequency( const double frequency, const uint8_t numberOfBits )
-{
+void setupDimmerPWMfrequency( const double frequency, const uint8_t numberOfBits ) {
   /* Setup timers and pwm bit depth */
-  for ( uint8_t channelNumber = 0; channelNumber < NUMBER_OF_CHANNELS; channelNumber++ )
-  {
-    ledcActualFrequency = ledcSetup( channelNumber, frequency, numberOfBits );
+  for ( uint8_t num = 0; num < NUMBER_OF_CHANNELS; num++ ) {
+    ledcActualFrequency = ledcSetup( num, frequency, numberOfBits );
   }
   ledcMaxValue = ( 0x00000001 << numberOfBits ) - 1;
   ledcNumberOfBits = numberOfBits;


#164 player sketch small change.

#164 player sketch small change.

--- examples/Widgets/Player/Player.ino
+++ examples/Widgets/Player/Player.ino
@@ -50,6 +50,7 @@
      //do something
   }

+  Blynk.setProperty(V5, "label", action);
   Serial.print(action);
   Serial.println();
 }


moved SD card write to correct place in code to fix double writes

--- code/testing/test_receiver_RFMTEMP/test_receiver_RFMTEMP.ino
+++ code/testing/test_receiver_RFMTEMP/test_receiver_RFMTEMP.ino
@@ -12,13 +12,11 @@
 #define SERIAL_BAUD 9600
 #define ACK_TIME    50  // # of ms to wait for an ack

-
 /*==============|| DS3231_RTC ||==============*/
 DS3231  rtc(SDA, SCL);

 /*==============|| SD ||==============*/
 const int chipSelect = 4;
-

 /*==============|| RFM69 ||==============*/
 RFM69 radio;
@@ -26,13 +24,12 @@
 const bool promiscuousMode = false; //set to 'true' to sniff all packets on the same network

 typedef struct {
-  int nodeId; //store this nodeId
+  int nodeID; //store this nodeId
   float temp;
   float voltage;
 }
 Payload;
-Payload theData;
-
+Payload data_rcv;

 void setup() {
   Serial.begin(9600);
@@ -51,85 +48,72 @@
 }

 void loop() {
-
   /*==============|| RADIO Recieve ||==============*/
-  if (radio.receiveDone()) {
-    radioReceive();
-    writeDataToCard();
-    if (radio.ACKRequested()) {
-      ACKsend();
-    }
-    Blink(LED,3);
-  }
+	if (radio.receiveDone()) {
+		if(radio.DATALEN != sizeof(Payload)) {
+			Serial.println("Invalid payload received!!");
+			writeDataToCard(00,99.99,99.99,thisUnixTime());
+		}
+		else {
+			data_rcv = *(Payload*)radio.DATA; //assume radio.DATA actually contains our struct and not something else
+			printData();
+			writeDataToCard(data_rcv.nodeID, data_rcv.temp, data_rcv.voltage, thisUnixTime());
+		}
+		if (radio.ACKRequested()) {
+			radio.sendACK();
+			if (ackCount++%3==0) delay(3);
+		}
+		Blink(LED,1);
+	}
 }

-void radioReceive() {
-  if(radio.DATALEN != sizeof(Payload)) {
-    Serial.println("Invalid payload received, not matching Payload struct!");
-  }
-  else {
-    theData = *(Payload*)radio.DATA; //assume radio.DATA actually contains our struct and not something else
-    Serial.print(theData.nodeId);
-    Serial.print(", RFM_temp: ");
-    Serial.print(theData.temp);
-    Serial.print(", Battery Voltage: ");
-    Serial.print(theData.voltage);
-    Serial.print(", time: ");
-    Serial.print(theUnixTime());
-    Serial.println();
-  }
+long thisUnixTime(){
+  return rtc.getUnixTime(rtc.getTime());
 }

-void ACKsend(){
-  //  byte theNodeID = radio.SENDERID;
-  radio.sendACK();
-  //Serial.print(" - ACK sent.");
-  // When a node requests an ACK, respond to the ACK
-  // and also send a packet requesting an ACK (every 3rd one only)
-  // This way both TX/RX NODE functions are tested on 1 end at the GATEWAY
-  if (ackCount++%3==0) {
-    //   Serial.print(" Pinging node ");
-    //Serial.print(theNodeID);
-    //Serial.print(" - ACK...");
-    delay(3); //need this when sending right after reception .. ?
-    //    if (radio.sendWithRetry(theNodeID, "ACK TEST", 8, 0))  // 0 = only 1 attempt, no retries
-    // Serial.print("ok!");
-    // else Serial.print("nothing");
-  }
+void writeDataToCard(int id, float t, float v, long utm) {
+	String fileName = String(String(id) + ".csv");
+	char __fileName[fileName.length()+1];
+	fileName.toCharArray(__fileName, sizeof(__fileName));
+	File dataFile = SD.open(__fileName, FILE_WRITE);
+	if(dataFile) {
+		dataFile.print(id);
+		dataFile.print(", ");
+		dataFile.print(t);
+		dataFile.print(", ");
+		dataFile.print(v);
+		dataFile.print(", ");
+		dataFile.print(utm);
+		dataFile.println();
+		dataFile.close();
+	}
+	else {
+		Blink(LED, 5);
+		Serial.print("Error opening ");
+		Serial.println(fileName);
+	}
 }
+
+void printData(){
+    Serial.print(data_rcv.nodeID);
+    Serial.print(", RFM_temp: ");
+    Serial.print(data_rcv.temp);
+    Serial.print(", Battery Voltage: ");
+    Serial.print(data_rcv.voltage);
+    Serial.print(", time: ");
+    Serial.print(thisUnixTime());
+    Serial.println();
+}
+
 void Blink(byte PIN, int DELAY_MS) {
   pinMode(PIN, OUTPUT);
   digitalWrite(PIN,HIGH);
   delay(DELAY_MS);
   digitalWrite(PIN,LOW);
 }
-long theUnixTime(){
-  return rtc.getUnixTime(rtc.getTime());
-}
-void writeDataToCard() {
-  String fileName = String(String(theData.nodeId) + ".csv");
-  char __fileName[fileName.length()+1];
-  fileName.toCharArray(__fileName, sizeof(__fileName));
-  File dataFile = SD.open(__fileName, FILE_WRITE);
-  if(dataFile) {
-    dataFile.print(theData.nodeId);
-    dataFile.print(", ");
-    dataFile.print(theData.temp);
-    dataFile.print(", ");
-    dataFile.print(theData.voltage);
-    dataFile.print(", ");
-    dataFile.print(theUnixTime());
-    dataFile.println();
-    dataFile.close();
-    Serial.println("printed data to file");
-  }
-  else {
-    Serial.print("Error opening ");
-    Serial.println(fileName);
-  }
-}

+


Playing with snap circuts mock up

Playing with snap circuts mock up

--- examples/cvseq_test/cvseq_test.ino
+++ examples/cvseq_test/cvseq_test.ino
@@ -1,6 +1,13 @@
 #include <CvSeq.h>

 #define LED_PIN 13
+#define OUT_PIN_1 3
+
+/*
+    To play around with the Sequencer, wire a photo resitor to A0
+    and an LED + speaker to pin 3
+*/
+

 CvSeq seq(
     2,  // int top_active
@@ -10,9 +17,10 @@
 );

 void setup() {
+    // put your setup code here, to run once:
     pinMode(LED_PIN, OUTPUT);
+    pinMode(OUT_PIN_1, OUTPUT);

-    // put your setup code here, to run once:
     pinMode(5, OUTPUT);
     pinMode(6, OUTPUT);
     Serial.begin(9600);
@@ -53,12 +61,21 @@
         }
     }

+    // With only one input wired up, use 8 step, ignore secondary
+    seq.setTwoEights();
+
     int note = seq.step();
+    int val = map(note, 900, 1023, 0, 240);
+    /*
     Serial.println(
         "Step: " + String(seq.getStep()) +
         " Primary: " + String(note) +
+        " Primary Note: " + String(val) +
         " Secondary: " + String(seq.getSecondary())
     );
+    */
+
+    analogWrite(OUT_PIN_1, val);
     // TODO Tempo factor
-    delay(500);
+    delay(300);
 }


Add wait section for arduino Leonardo serial port

--- examples/1-Calibration/AutomatedTesting/AutomatedTesting.ino
+++ examples/1-Calibration/AutomatedTesting/AutomatedTesting.ino
@@ -6,7 +6,7 @@
 #include <EEPROM.h>
 #include "pins_arduino.h"

-/***************************************************
+/*******************************************************
 / Example provided by MINDS-i
 / Try checking out our arduino resource guide at
 / http://mindsieducation.com/programming-resources
@@ -19,7 +19,7 @@
 / QTI Sensors
 / Ping Sensors
 / And reading/clearing EEPROM
-/***************************************************/
+/*******************************************************/

 const int dQTIs[3] = {A0, A1, A2};
 const int dPing[3] = {9 , 10, 11};
@@ -54,7 +54,8 @@

 void setup() {
   Serial.begin(9600);
-  Serial.println("\nEnter the character for what you want to do.");
+  while(!Serial) /*nop*/; //wait for leonardo to connect to PC
+  delay(500);
   menu();
   Serial.flush();
 }
@@ -109,8 +110,9 @@

 void menu() {
   Serial.println(
+    "\nEnter the character for what you want to do."
     "\n(S)elf test; (Q)TIs; (P)ings; (D)igitals;"
-    "(A)nalogs; (E)EPROM; (M)otor; (R)adio");
+    " (A)nalogs; (E)EPROM; (M)otor; (R)adio");
 }

 void selfTest() {


updated ScanNetworks to include RSSI and encryption (really this time!)

--- WiFi/examples/ScanNetworks/ScanNetworks.ino
+++ WiFi/examples/ScanNetworks/ScanNetworks.ino
@@ -24,19 +24,19 @@

   // attempt to connect using WEP encryption:
   Serial.println("Initializing Wifi...");
-  //WiFi.begin("no network");
   printMacAddress();
+

   // scan for existing networks:
   Serial.println("Scanning available networks...");
-  scanNetworks();
+  listNetworks();
 }

 void loop() {
   delay(10000);
   // scan for existing networks:
   Serial.println("Scanning available networks...");
-  scanNetworks();
+  listNetworks();
 }

 void printMacAddress() {
@@ -59,19 +59,20 @@
   Serial.println(mac[0],HEX);
 }

-void scanNetworks() {
+void listNetworks() {
   // scan for nearby networks:
   Serial.println("** Scan Networks **");
   byte numSsid = WiFi.scanNetworks();

   // print the list of networks seen:
-  Serial.print("SSID List:");
+  Serial.print("number of available networks:");
   Serial.println(numSsid);
-  Serial.println("#\tNetwork:\tRSSI:\tEncryption:");
+
+  Serial.println("#\tName\tRSSI\tencryptionType:");
   // print the network number and name for each network found:
   for (int thisNet = 0; thisNet<numSsid; thisNet++) {
     Serial.print(thisNet);
-    Serial.print(")\t");
+    Serial.print("\t");
     Serial.print(WiFi.SSID(thisNet));
     Serial.print("\t");
     Serial.print(WiFi.RSSI(thisNet));


Pequeña corrección

Pequeña corrección

--- ARDUINO/sleep_example_routine_temp_light/sleep_example_routine_temp_light.ino
+++ ARDUINO/sleep_example_routine_temp_light/sleep_example_routine_temp_light.ino
@@ -14,10 +14,10 @@
 // VARIABLES

 int var = 0;
-int Tmp = 0;
-int light = 0;
-int t_aux = 0;
-int l_aux =  0;
+float Tmp = 0;
+float light = 0;
+float t_aux = 0;
+float l_aux =  0;

 void setup() {

@@ -47,8 +47,7 @@
    delay(2000);                   //tiempo de espera
    t_aux=analogRead(T_PIN);       //lectura de T analogica 0-1023

-   Tmp = (125*t_aux)>>8; //10mV -> 1 ºC, con eso escalamos
-
+   Tmp = 5*100*t_aux/1024; //10mV -> 1 ºC, con eso escalamos

   //COM: puerto serie de los datos de T
   Serial.print("Temperature: ");