Modify so each colour gets turned off randomly before we move on to the next

--- Xmas2013/randomActsOfColour/randomActsOfColour.ino
+++ Xmas2013/randomActsOfColour/randomActsOfColour.ino
@@ -27,13 +27,13 @@
 const int NCOLOURS = sizeof(COLOURS)/sizeof(int);

 // Storage for bitmap of lights 7x8 bits = 56 (we need 50)
+const int bulbBytes = 7;
 #ifdef TWO_STRINGS
-byte bulbs1[7];
-byte bulbs2[7];
+byte bulbs1[bulbBytes];
+byte bulbs2[bulbBytes];
 #else
-byte bulbs[7];
+byte bulbs[bulbBytes];
 #endif
-const int bulbBytes = 7;

 // Macros to work out which bit of which byte to set..
 #define GETBIT int bit = bulb % 8
@@ -56,10 +56,22 @@
   bulbs[ind] |= 1 << bit;
 }

-bool bulbUnset(byte bulbs[], const int bulb) {
+void unSetBulb(byte bulbs[], const int bulb) {
+  GETBIT;
+  GETIND;
+  bulbs[ind] &= ~(1 << bit);
+}
+
+bool bulbIsUnset(byte bulbs[], const int bulb) {
   GETBIT;
   GETIND;
   return (bulbs[ind] & (1 << bit)) == 0;
+}
+
+bool bulbIsSet(byte bulbs[], const int bulb) {
+  GETBIT;
+  GETIND;
+  return (bulbs[ind] & (1 << bit)) > 0;
 }

 int countBits(byte bulbs[]) {
@@ -96,13 +108,13 @@

 void loop() {
   #ifdef TWO_STRINGS
-    // Set first colour
+    // Randomly switch on to current colour
     while ( countBits(bulbs1) < LIGHT_COUNT ||
             countBits(bulbs2) < LIGHT_COUNT ) {

       // Set the bulb on first string
       int bulb = random(LIGHT_COUNT);
-      if ( bulbUnset(bulbs1, bulb) ) {
+      if ( bulbIsUnset(bulbs1, bulb) ) {
         setBulb(bulbs1, bulb);
         lights1.set_color(bulb, G35::MAX_INTENSITY, COLOURS[colour]);
         delay(BETWEEN_BULBS);
@@ -110,7 +122,7 @@

       // Set the bulb on second string
       bulb = random(LIGHT_COUNT);
-      if ( bulbUnset(bulbs2, bulb) ) {
+      if ( bulbIsUnset(bulbs2, bulb) ) {
         setBulb(bulbs2, bulb);
         lights2.set_color(bulb, G35::MAX_INTENSITY, COLOURS[colour]);
         delay(BETWEEN_BULBS);
@@ -118,26 +130,48 @@
     }
     delay(AFTER_STRING);

-    // Clear the strings
-    lights1.fill_color(0, LIGHT_COUNT, G35::MAX_INTENSITY, COLOR_BLACK);
-    lights2.fill_color(0, LIGHT_COUNT, G35::MAX_INTENSITY, COLOR_BLACK);
-    clearBulbs(bulbs1);
-    clearBulbs(bulbs2);
+    // Randomly switch off
+    while ( countBits(bulbs1) > 0 ||
+            countBits(bulbs2) > 0 ) {
+
+      // Set the bulb on first string
+      int bulb = random(LIGHT_COUNT);
+      if ( bulbIsSet(bulbs1, bulb) ) {
+        unSetBulb(bulbs1, bulb);
+        lights1.set_color(bulb, G35::MAX_INTENSITY, COLOR_BLACK);
+        delay(BETWEEN_BULBS);
+      }
+
+      // Set the bulb on second string
+      bulb = random(LIGHT_COUNT);
+      if ( bulbIsSet(bulbs2, bulb) ) {
+        unSetBulb(bulbs2, bulb);
+        lights2.set_color(bulb, G35::MAX_INTENSITY, COLOR_BLACK);
+        delay(BETWEEN_BULBS);
+      }
+    }
   #else
-    // Set first colour
+    // Randomly switch on to current colour
     while ( countBits(bulbs) < LIGHT_COUNT ) {
       int bulb = random(LIGHT_COUNT);
-      if ( bulbUnset(bulbs, bulb) ) {
+      if ( bulbIsUnset(bulbs, bulb) ) {
         setBulb(bulbs, bulb);
         lights.set_color(bulb, G35::MAX_INTENSITY, COLOURS[colour]);
         delay(BETWEEN_BULBS);
       }
     }
     delay(AFTER_STRING);
+
+    // Randomly switch off again...
+    while ( countBits(bulbs) > 0 ) {
+      int bulb = random(LIGHT_COUNT);
+      if ( bulbIsSet(bulbs, bulb) ) {
+        unSetBulb(bulbs, bulb);
+        lights.set_color(bulb, G35::MAX_INTENSITY, COLOR_BLACK);
+        delay(BETWEEN_BULBS);
+      }
+    }

-    // Clear the string
-    lights.fill_color(0, LIGHT_COUNT, G35::MAX_INTENSITY, COLOR_BLACK);
-    clearBulbs(bulbs);
   #endif

   colour++;


re-zeroes every z level to prevent drift

--- arrowprint_firmware/arrowprint_firmware.ino
+++ arrowprint_firmware/arrowprint_firmware.ino
@@ -10,7 +10,7 @@
  */
 #include <aJSON.h>

-String version = "5.0";
+String version = "5.1";

@@ -19,21 +19,21 @@
  *    CONFIGURATION
  *  =======================================================================================
  */
-
+int cmd = 0;
 //int hotheadtarget = 160;    //160 DEFAULT
 int hotheadtarget = 10;    //160 DEFAULT

 //physical movement scale (bigger == more);
 double tablexsteps    = 23000;
-double tableysteps    = 33000;
-double tablezsteps    = 203205;    //234000 (100mm) from top (STEPS FROM TABLE SURFACE TO TOP) 0,0,0 is FAR LEFT BOTTOM
+double tableysteps    = 23000;
+double tablezsteps    = 349100;    //234000 (100mm) from top (STEPS FROM TABLE SURFACE TO TOP) 0,0,0 is FAR LEFT BOTTOM
 double tableesteps  = -1000000;

 //measured (1000 = 1mm)
-double tablexdistance = 200.000;    //in microns (158mm )
-double tableydistance = 200.000;    //in microns (200mm)
-double tablezdistance = 70.000;    //in microns (96mm)
-double tableedistance = 310.000;    //in microns (96mm)
+double tablexdistance = 134.765625;    //in microns (158mm )
+double tableydistance = 134.765625;    //in microns (200mm)
+double tablezdistance = 61.913;    //in microns (96mm)
+double tableedistance = 920.000;    //in microns (96mm)

 // Motor pins
@@ -46,7 +46,7 @@
 double stepperXdestPosition = 0;
 double stepperXtimer = 0;
 int    stepperXtoggle = 0;
-double stepperXspeed = 60;
+double stepperXspeed = 110;

 int motorpinYstep = 26;
 int motorpinYdir  = 27;
@@ -54,7 +54,7 @@
 double stepperYdestPosition = 0;
 double stepperYtimer = 0;
 int    stepperYtoggle = 0;
-double stepperYspeed = 120;  //slower for more power
+double stepperYspeed = 110;  //slower for more power

 int motorpinZstep = 30;
 int motorpinZdir  = 31;
@@ -62,7 +62,7 @@
 double stepperZdestPosition = 0;
 double stepperZtimer = 0;
 int    stepperZtoggle = 0;
-double stepperZspeed = 60;
+double stepperZspeed = 110;

 int motorpinEstep = 28;
 int motorpinEdir  = 29;
@@ -70,7 +70,7 @@
 double stepperEdestPosition = 0;
 double stepperEtimer = 0;
 int    stepperEtoggle = 0;
-double stepperEspeed = 120;
+double stepperEspeed = 110;

 // Motor Zero switch pins
@@ -93,18 +93,18 @@
 // INTERNAL DO NOT CHANGE BELOW
 //latest position in microns (1000 = 1mm)

-double lastx = 0;
-double lasty = 0;
-double lastz = 0;
-double laste = 0;
+double lastx = 0.0;
+double lasty = 0.0;
+double lastz = 0.0;
+double laste = 0.0;

 // =========================================================================================

 void setup() {
-  analogReadResolution(16);
-  analogWriteResolution(16);
+  analogReadResolution(12);
+  analogWriteResolution(12);
   Serial.begin(115200);
   Serial.print("{ \"log\" : \"Connecting...\"}");
   //ZERO SWITCHES
@@ -195,6 +195,41 @@
 }

 //=======================================================================================
+
+
+void zeroplane() {
+      /////////////////////////////////////////////////////////// X LEFT RIGHT
+
+    while (digitalRead(xZeropin) != xZeroNC) {
+      stepperXdestPosition = stepperXdestPosition - 32;
+      while (stepperXdistanceToGo() != 0) {
+        stepperXrun();
+      }
+    }
+
+    stepperXcurrPosition = -2000;
+    //moves to zero
+    stepperXdestPosition = 0;
+    lastx = 0;
+    while (stepperXdistanceToGo() != 0) {
+      stepperXrun();
+    }
+    ////////////////////////////////////////////////////////////// Y TABLE FRONT BACK
+    while (digitalRead(yZeropin) != yZeroNC) {
+      stepperYdestPosition = stepperYdestPosition + 32;
+      while (stepperYdistanceToGo() != 0) {
+        stepperYrun();
+      }
+    }
+    //moves to 0
+    stepperYcurrPosition = tableysteps+10000;
+    stepperYdestPosition = 0;
+    lasty = 0;
+    while (stepperYdistanceToGo() != 0) {
+      stepperYrun();
+    }
+}
+
 // START ZEROAXIS()
 void zeroaxis() {
   /*
@@ -213,8 +248,9 @@

     stepperZcurrPosition = tablezsteps + 6400;

-    //moves a little off switch
-    stepperZdestPosition = tablezsteps -30000;
+    //moves to zero
+    stepperZdestPosition = 0;
+    lastz = 0;
     while (stepperZdistanceToGo() != 0) {
       stepperZrun();
     }
@@ -227,12 +263,14 @@
       }
     }

-    stepperXcurrPosition = -1000;
-    //moves a little off switch (0)
-    stepperXdestPosition = tablexsteps;
+    stepperXcurrPosition = -2000;
+    //moves to zero
+    stepperXdestPosition = 0;
+    lastx = 0;
     while (stepperXdistanceToGo() != 0) {
       stepperXrun();
     }
+
     Serial.print("{ \"log\" : \"X axis zero success\"}");
     ////////////////////////////////////////////////////////////// Y TABLE FRONT BACK
     Serial.print("{ \"log\" : \"Attempting to zero Y axis\"}");
@@ -243,20 +281,22 @@
       }
     }
     //moves to 0
-    stepperYcurrPosition = tableysteps+1000;
+    stepperYcurrPosition = tableysteps+10000;
     stepperYdestPosition = 0;
+    lasty = 0;
     while (stepperYdistanceToGo() != 0) {
       stepperYrun();
     }
     ////////////////////////////////////////////////////////////// E zero
     Serial.print("{ \"log\" : \"Attempting to test E axis\"}");
-    stepperEdestPosition = 6400;  //1 rotation
+    stepperEdestPosition = 0;  //1 rotation
     while (stepperEdistanceToGo() != 0) {
         stepperErun();
       }
     //moves to 0
     stepperEcurrPosition = 0;
     stepperEdestPosition = 0;
+    laste = 0;
     Serial.print("{ \"log\" : \"Extruder stepper axis zero success\"}");

 }
@@ -266,19 +306,8 @@
 void line(double x, double y, double z, double e) {

   //DISTANCESTEPS
-
-   double deltax = lastx - x;
-   double deltay = lasty - y;
-   double deltaz = lastz - z;
-   double deltae = laste - e;
-
-   double distance = pow(deltax,2) + pow(deltay,2) + pow(deltaz, 2) + pow(deltae, 2);
-   distance = sqrt(distance);
-
-  ///
-
-//   double steps = 25;
-    double steps = round(distance)*5;
+   double distance = sqrt( pow((float)(x - lastx),2) + pow( (float)(y - lasty),2) + pow( (float)(z - lastz), 2) + pow( (float)(e - laste), 2));
+   double steps = round(distance*500);

         //calculate new step positions from micron position
    double nx = tablexsteps*(x/tablexdistance);
@@ -320,26 +349,29 @@
    lasty = y;
    lastz = z;
    laste = e;
-
-   for (int i = 0; i < steps; i++) {
+
+   for (int i = 0; i <= steps; i++) {
      double newx = cx + (dx*i);
      double newy = cy + (dy*i);
      double newz = cz + (dz*i);
      double newe = ce + (de*i);

-     stepperXdestPosition = newx;
-     stepperYdestPosition = newy;
-     stepperZdestPosition = newz;
-     stepperEdestPosition = newe;
+     stepperXdestPosition = round(newx);
+     stepperYdestPosition = round(newy);
+     stepperZdestPosition = round(newz);
+     stepperEdestPosition = round(newe);

      while ((stepperXdistanceToGo() != 0) || (stepperYdistanceToGo() != 0) || (stepperZdistanceToGo() != 0) || (stepperEdistanceToGo() != 0)) {
        ///GET THESE INTO THE MAIN LOOP
        // NEED TO REFACTOR EVENT LOOP
-       stepperXrun();
-       stepperYrun();
-       stepperZrun();
-       stepperErun();
+
+         stepperXrun();
+         stepperYrun();
+         stepperZrun();
+         stepperErun();
+
+
        }
    }

@@ -394,6 +426,7 @@
       if (jsonpz) {
         char* tempz = jsonpz->valuestring;
         g1z = atof(tempz);
+        zeroplane();
       }

       aJsonObject *jsonpe = aJson.getObjectItem(msg, "e");
@@ -410,9 +443,9 @@
   if (cmd == "G92") {
       aJsonObject *jsonpe = aJson.getObjectItem(msg, "e");
       if (jsonpe) {
-        stepperEcurrPosition = 0.0;
-        stepperEdestPosition = 0.0;
-        laste = 0.0;
+        stepperEcurrPosition = 0.0f;
+        stepperEdestPosition = 0.0f;
+        laste = 0.0f;
       }
     }///END G92


Fix Wave example

Fix Wave example


Arduino Repeater: Re-write much to allow toggle flags for Maxell, use #defines to save ram.

--- arduino_repeater/arduino_repeater.ino
+++ arduino_repeater/arduino_repeater.ino
@@ -11,54 +11,65 @@
 #include "RFM69.h"
 #include "LowPower.h"

-//*************Node ID Setup ****************/
-char id[] = "P5";
-char location_string[] = "50.9387,-1.3979";
+//************* Node ID Setup ****************/
+char id[] = "P01";
+char location_string[] = "50.9375,-1.3982";
 uint8_t rfm_power = 20; // dBmW

-//*************Pin Setup ****************/
-int batt_pin = 0; //ADC 0 - measure battery voltage
+//************* Sensors ****************/
+// Battery Voltage Measurement - Also enables zombie mode
+#define ENABLE_BATTV_SENSOR // Comment out to disable, also disables zombie mode
+#define BATTV_PIN 0 //ADC 0 - Battery Voltage, scaled to 1.1V
+#define BATTV_FUDGE 0.935
+// RFM Temperature Sensor - Not very accurate and sometimes glitchy
+#define ENABLE_RFM_TEMPERATURE // Comment out to disable
+#define RX_TEMP_FUDGE 5.0 // Temperature offset when in RX due to self-heating

-//*************Misc Setup ****************/
+//************* Power Saving ****************/
+#ifdef ENABLE_BATTV_SENSOR
+  #define ENABLE_ZOMBIE_MODE // Comment this out to disable
+#endif
+uint8_t zombie_mode; // Stores current status: 0 - Full Repeating, 1 - Low Power shutdown, (beacon only)
+#define ZOMBIE_THRESHOLD 3.65
+
+//************* Misc Setup ****************/
 byte num_repeats = '3'; //The number of hops the message will make before stopping
-float repeat_threshold = 3.65; // The voltage at which the node will switch between repeating and zombie modes
-int zombie_mode = 1;
-float slow_freq_threshold = 3.6;
-float rx_temp_offset = 5.0; // Temperature offset when in RX due to self-heating
-
 float battV=0.0;
-int n, count = 1, data_interval = 4;
-byte data_count = 97; // 'a'
+uint8_t n, count = 1, data_interval = 10;
+uint8_t data_count = 97; // 'a'
 char data[64], string_end[] = "]";

 // Singleton instance of the radio
 RFM69 rf69(9.3); // parameter: RFM temperature calibration offset (degrees as float)

 int gen_Data(){
-
-  byte rfmTemp = rf69.readTemp();
-  while(rfmTemp>100) {
-    rfmTemp = rf69.readTemp();
-  }
-  if(zombie_mode==0) {
-    rfmTemp-=rx_temp_offset;
+  if(data_count=='a' or data_count=='z') {
+      sprintf(data, "%c%cL%s", num_repeats, data_count, location_string);
+  } else {
+      sprintf(data, "%c%c", num_repeats, data_count);
   }

+  #ifdef ENABLE_RFM_TEMPERATURE
+  sprintf(data,"%sT%d",data,sampleRfmTemp());
+  #endif
+
+  #ifdef ENABLE_BATTV_SENSOR
   battV = sampleBattv();
-  char tempStr[14]; //make buffer large enough for 7 digits
   char* battStr;
-  battStr = dtostrf(battV,7,2,tempStr);
-  // Strip leading space
+  char tempStrB[14]; //make buffer large enough for 7 digits
+  battStr = dtostrf(battV,7,2,tempStrB);
   while( (strlen(battStr) > 0) && (battStr[0] == 32) )
   {
      strcpy(battStr,&battStr[1]);
   }
-  if(data_count=='a' or data_count=='z') {
-    n=sprintf(data, "%c%cL%sT%dV%sZ%d[%s]", num_repeats, data_count, location_string, rfmTemp, battStr, zombie_mode, id);
-  } else {
-    n=sprintf(data, "%c%cT%dV%sZ%d[%s]", num_repeats, data_count, rfmTemp, battStr, zombie_mode, id);
-  }
-  return n;
+  sprintf(data,"%sV%s",data,battStr);
+  #endif
+
+  #ifdef ENABLE_ZOMBIE_MODE
+  sprintf(data,"%sZ%d",data,zombie_mode);
+  #endif
+
+  return sprintf(data,"%s[%s]",data,id);
 }

 void setup()
@@ -73,6 +84,19 @@

   int packet_len = gen_Data();
   rf69.send((uint8_t*)data, packet_len, rfm_power);
+
+  #ifdef ENABLE_ZOMBIE_MODE
+  if(battV > ZOMBIE_THRESHOLD) {
+    rf69.setMode(RFM69_MODE_RX);
+    zombie_mode=0;
+  } else {
+    rf69.setMode(RFM69_MODE_SLEEP);
+    zombie_mode=1;
+  }
+  #else
+  rf69.setMode(RFM69_MODE_RX);
+  zombie_mode=0;
+  #endif
 }

 void loop()
@@ -80,8 +104,8 @@
   count++;
   if(zombie_mode==0) {
     rf69.setMode(RFM69_MODE_RX);
-    for(int i=0;i<32;i++) {
-      LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
+    for(int i=0;i<64;i++) {
+      LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF);
       if(rf69.checkRx()) {
         uint8_t buf[64];
         uint8_t len = sizeof(buf);
@@ -123,6 +147,8 @@
       }
     }
   } else {
+    // Sample Sensors here..
+
     // Sleep for 8 seconds
     rf69.setMode(RFM69_MODE_SLEEP);
     LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
@@ -138,23 +164,35 @@
     int packet_len = gen_Data();
     rf69.send((uint8_t*)data, packet_len, rfm_power);

-    if(battV > slow_freq_threshold) {
-      data_interval = random(15, 20) + count;
-      if(battV > repeat_threshold && zombie_mode==1) {
+    data_interval = random(10, 15) + count;
+    #ifdef ENABLE_ZOMBIE_MODE
+    if(battV > ZOMBIE_THRESHOLD && zombie_mode==1) {
         rf69.setMode(RFM69_MODE_RX);
         zombie_mode=0;
-      } else if (battV < repeat_threshold && zombie_mode==0) {
+    } else if (battV < ZOMBIE_THRESHOLD && zombie_mode==0) {
         rf69.setMode(RFM69_MODE_SLEEP);
         zombie_mode=1;
-      }
     }
-    else {
-      data_interval = random(25, 30) + count;
-    }
+    #endif
   }
 }

+#ifdef ENABLE_RFM_TEMPERATURE
+int8_t sampleRfmTemp() {
+    int8_t rfmTemp = rf69.readTemp();
+    while(rfmTemp>100) {
+        rfmTemp = rf69.readTemp();
+    }
+    if(zombie_mode==0) {
+        rfmTemp-=RX_TEMP_FUDGE;
+    }
+    return rfmTemp;
+}
+#endif
+
+#ifdef ENABLE_BATTV_SENSOR
 float sampleBattv() {
   // External 4:1 Divider
-  return ((float)analogRead(batt_pin)*1.1*4)/1023.0;
+  return ((float)analogRead(BATTV_PIN)*1.1*4*BATTV_FUDGE)/1023.0;
 }
+#endif


Sign changes after experiments.

Sign changes after experiments.

--- software/Arduino/ServoController/ServoController.ino
+++ software/Arduino/ServoController/ServoController.ino
@@ -3,7 +3,7 @@
  * and rotating a stepper motor. Accepts correction factors via serial *
  * at 115200 baud.                                                     *
  * Project: Eclipse Tracking (2017)                                    *
- * @Version 4.0 (5/13/2017)                                            *
+ * @Version 4.0 (5/27/2017)                                            *
  * @Author Max Bowman / Jeremy Seeman / George Moe                     *
  ***********************************************************************/
 #include <Stepper.h>
@@ -15,7 +15,7 @@
 // ================ SYSTEM PARAMETERS ===================
 // Sample rates
 int motorUpdateRate = 50; // gyro sample rate
-int calibrationSamples = 1000;
+int calibrationSamples = 500;

 // Initial calibration value
 float calibratedOffset = 0;
@@ -68,14 +68,15 @@

   // Accept corrections from serial
   if (Serial.available() == 4) {
-    int correctionFactor = 0;
-    byte negative = 0;
-    if (Serial.read() == '1') negative = 1;
+    float correctionFactor = 0;
+    bool negative = false;
+    if (Serial.read() == '1') negative = true;
     for (int i = 100; i >= 1; i /= 10) {
-      correctionFactor += (Serial.read() - '0') * i;
+      correctionFactor += (float)(Serial.read() - '0') * i;
     }
     if (negative) correctionFactor = -correctionFactor;
-    rotateStepperBy(-correctionFactor);
+    rotateStepperBy(correctionFactor);
+    positionChange = 0; // reset gyro based corrections
   }

   // Update orientation data with measurements from gyro
@@ -88,8 +89,8 @@
   // Update motor position
   if(update_flag) {
     // Update stepper position (Z/AZM)
-    float degreesActuallyCorrected = rotateStepperBy(positionChange);
-    positionChange -= degreesActuallyCorrected;
+    float degreesActuallyCorrected = rotateStepperBy(-positionChange);
+    positionChange += degreesActuallyCorrected;
     // Reset flag
     update_flag = false;
   }
@@ -138,6 +139,8 @@
     imu.readGyro();
     float z = imu.calcGyro(imu.gz);
     zSum += z;
+    if (i % 23 == 0)
+      blinkLED(20, 1);
     delay(10);
   }
   return zSum / calibrationSamples;


Corrected version for AHRS Version (Arduino code)

--- 3rdParties/razor-9dof-ahrs/Arduino/Razor_AHRS/Razor_AHRS.ino
+++ 3rdParties/razor-9dof-ahrs/Arduino/Razor_AHRS/Razor_AHRS.ino
@@ -166,8 +166,8 @@
 // HARDWARE OPTIONS
 /*****************************************************************/
 // Select your hardware here by uncommenting one line!
-#define HW__VERSION_CODE 10125 // SparkFun "9DOF Razor IMU" version "SEN-10125" (HMC5843 magnetometer)
-//#define HW__VERSION_CODE 10736 // SparkFun "9DOF Razor IMU" version "SEN-10736" (HMC5883L magnetometer)
+//#define HW__VERSION_CODE 10125 // SparkFun "9DOF Razor IMU" version "SEN-10125" (HMC5843 magnetometer)
+#define HW__VERSION_CODE 10736 // SparkFun "9DOF Razor IMU" version "SEN-10736" (HMC5883L magnetometer)
 //#define HW__VERSION_CODE 10183 // SparkFun "9DOF Sensor Stick" version "SEN-10183" (HMC5843 magnetometer)
 //#define HW__VERSION_CODE 10321 // SparkFun "9DOF Sensor Stick" version "SEN-10321" (HMC5843 magnetometer)
 //#define HW__VERSION_CODE 10724 // SparkFun "9DOF Sensor Stick" version "SEN-10724" (HMC5883L magnetometer)


Update arduino sketch to use reset pin.

Update arduino sketch to use reset pin.

--- scripts/mt_loader_usb/mt_loader_usb.ino
+++ scripts/mt_loader_usb/mt_loader_usb.ino
@@ -1,8 +1,8 @@

-#define BOARD_PWR    A4
+#define BOARD_RST    10
 #define BOARD_DETECT 7
-#define BOARD_BOOT   A0
+#define BOARD_BOOT   A1

 #define DEBOUNCE_TIME 250
 #define DETECT_TIME 500
@@ -10,12 +10,12 @@

 void setup()
 {
-  pinMode(BOARD_PWR, OUTPUT);
+  pinMode(BOARD_RST, INPUT);
   pinMode(BOARD_DETECT, INPUT);
   pinMode(BOARD_BOOT, OUTPUT);

   digitalWrite(BOARD_BOOT, LOW);
-  digitalWrite(BOARD_PWR, LOW);
+  digitalWrite(BOARD_RST, LOW);

   Serial.begin(9600);
 }
@@ -50,13 +50,12 @@

 void board_power(boolean boot)
 {
-  digitalWrite(BOARD_PWR, LOW);
-  digitalWrite(BOARD_BOOT, boot ? HIGH : LOW);
-  delay(1000);
-  digitalWrite(BOARD_PWR, HIGH);
+  pinMode(BOARD_BOOT, boot ? INPUT : OUTPUT);
+  pinMode(BOARD_RST, OUTPUT);
+  delay(100);
+  pinMode(BOARD_RST, INPUT);

-  if (!board_detect(true))
-    digitalWrite(BOARD_PWR, LOW);
+  board_detect(true);
 }

 boolean board_detect(boolean connect)


Added tests

Added tests

--- firefighter/firefighter.ino
+++ firefighter/firefighter.ino
@@ -193,15 +193,30 @@
   }

   if(btn){
-    Serial.println(pulseRight);
-  //      driveToWhite()
-    definedStartSearch();
+//    Serial.println(pulseRight);
+//    definedStartSearch();
+    Serial.println("====================================");
+    Serial.print("F: ");
+    Serial.println(frontUltrasonic.getDistance());
+    Serial.print("L: ");
+    Serial.println(leftUltrasonic.getDistance());
+    Serial.print("R: ");
+    Serial.println(rightUltrasonic.getDistance());
+    Serial.print("B: ");
+    Serial.println(backUltrasonic.getDistance());
+    delay(300);
   }
   else{
     hDrive(0.0, 0.0, 0.0);
   }

   delay(100);
+}
+
+void drivetrainCheck() {
+  hDrive(0.3, 0.0, 0.0); delay(300); hDrive(-0.3, 0.0, 0.0); delay(300);
+  hDrive(0.0, 0.3, 0.0); delay(300); hDrive(0.0, -0.3, 0.0); delay(300);
+  hDrive(0.0, 0.0, 0.3); delay(300); hDrive(0.0, 0.0, -0.3); delay(300);
 }

 void driveToWhite() {
@@ -295,4 +310,20 @@

   if(!directionLeft)  pulseLeft++;
   else  pulseLeft--;
-}+}
+
+double getAngle() {
+  return ((pulseLeft - pulseRight) * 12.5 / 700) / 8;
+}
+
+double getPercentError(double actual, double target) {
+  return abs(actual - target) / target;
+}
+
+void turnToAngle(double targetAngle) {
+  while (abs(getAngle()) < abs(targetAngle)) {
+    hDrive(0.0, getPercentError(getAngle(), targetAngle), 0.0);
+  }
+  hDrive(0.0, 0.0, 0.0);
+}
+


Minor led fix

Minor led fix

--- led_engine_advanced_buttons/led_engine_advanced_buttons.ino
+++ led_engine_advanced_buttons/led_engine_advanced_buttons.ino
@@ -14,7 +14,7 @@
 LP55231 led;
 uint8_t turnOn = 0;

-int latestProgram = 0;
+uint8_t latestProgram = 0;

 void setup()
@@ -298,12 +298,14 @@
   delay(50);
   int statusA5 = analogRead(A5);
   if(statusA5<300){
+    int nextProgram = 0;
     if(statusA5<150)//left button
-      serialControl((uint8_t)(latestProgram+6)%7+48);
+      nextProgram = (latestProgram+4)%6+1;
     else if(statusA5<220)//right button
-      serialControl((uint8_t)(latestProgram+1)%7+48);
+      nextProgram = (latestProgram)%6+1;
     else //middle button
-      ;
+      ;
+    serialControl(nextProgram+48);
     if(turnOn)
     {
       led.engineControl(turnOn, LOAD); //set selected engines to load mode
@@ -331,10 +333,8 @@
       led.setCurrent(1);
       led.resetCode(); //reset opcode
     }
-  if(serialData == '0'){
+  if(serialData == '0')
     testLeds();
-    latestProgram = 0;
-  }
   else if(serialData == '1'){
     opcodeHeartBeat();
     latestProgram = 1;


Update for Particle Core and Photon

Update for Particle Core and Photon

--- firmware/examples/RFID_UART.ino
+++ firmware/examples/RFID_UART.ino
@@ -17,6 +17,8 @@
 RFIDdata tag;

 void setup() {
+	Serial1.begin(9600);	//Done here to prevent SeeedRFID constructor system crash
+
 	Serial.begin(57600);
 	Serial.println("Hello, double bk!");
 }


add space

add space

--- invPendulum/invPendulum.ino
+++ invPendulum/invPendulum.ino
@@ -61,7 +61,7 @@
      if (command1.substring(i,i+1) == " "){
         string1 = command1.substring(pos-i,i-1);

-     }
+     }

     }


fixed debug mode

fixed debug mode

--- Arduino_Thermostat/Arduino_Thermostat.ino
+++ Arduino_Thermostat/Arduino_Thermostat.ino
@@ -91,7 +91,7 @@
   temp1 = temps1->getTemp();

   // following block is only to decrease display rate durig debug
-  #ifdef DEBUG
+  #ifdef DEBUG_MODE
   if (temp1 != oldtemp1){
     dp("Temp=");
     dpln(temp1);


added a kind-of-testing-harness for the particle.

--- particle/examples/local-compile/local-compile.ino
+++ particle/examples/local-compile/local-compile.ino
@@ -1,17 +1,20 @@
 // This #include statement was automatically added by the Spark IDE.
 #include "tentacle-particle.h"

-/*#define server "tentacle.octoblu.com"
-#define port 80*/
-
-
-IPAddress server(54,186,61,91);
+#define server "tentacle.octoblu.com"
 #define port 80
+
+
+IPAddress localServer(192, 168, 0, 104);
+#define localPort 8111

 static const char uuid[]  = "ff12c403-04c7-4e63-9073-2e3b1f8e4450";
 static const char token[] = "28d2c24dfa0a5289799a345e683d570880a3bc41";

 TCPClient conn;
+
+bool hasConnectedToServer = false;
+bool hasAuthenticated = false;

 TentacleArduino tentacle;
 Pseudopod pseudopod(conn, conn, tentacle);
@@ -19,19 +22,90 @@
 void setup() {
   Serial.begin(9600);
   Serial.println(F("The Day of the Tentacle has begun!"));
-  debugPhoton();
+  setupDebug();
+}
+
+void setupDebug() {
+  Spark.function("wifiInfo", wifiInfoCmd);
+  Spark.function("connect", connectToServerCmd);
+  Spark.function("connectlocal", connectToLocalServerCmd);
+  Spark.function("disconnect", disconnectFromServerCmd);
+  Spark.function("authenticate", authenticateCmd);
+  Spark.function("config", requestConfigCmd);
+  Spark.function("sendPins", sendPinsCmd);
+  Spark.function("dfu", dfuCmd);
+}
+
+int wifiInfoCmd(String cmd) {
+  wifiInfo();
+  return 0;
+}
+
+int connectToServerCmd(String cmd) {
   connectToServer();
+  return 0;
+}
+
+int connectToLocalServerCmd(String cmd) {
+  connectToLocalServer();
+  return 0;
+}
+
+int disconnectFromServerCmd(String cmd) {
+  disconnectFromServer();
+  return 0;
+}
+
+int authenticateCmd(String cmd) {
+  return authenticate();
+}
+
+int requestConfigCmd(String cmd) {
+  return pseudopod.requestConfiguration();
+}
+
+int sendPinsCmd(String cmd) {
+  return pseudopod.sendConfiguredPins();
+}
+
+
+int dfuCmd(String cmd) {
+  System.dfu();
+  return 0;
 }

 void loop() {
+  Serial.println(F("In loop."));
+
+  if(!hasConnectedToServer) {
+    Serial.println(F("I haven't been told to connect yet. Waiting."));
+    delay(1000);
+    Serial.flush();
+    return;
+  }
+
+  if(!hasAuthenticated) {
+    Serial.println(F("I haven't been told to authenticate yet. Waiting."));
+    delay(1000);
+    Serial.flush();
+    return;
+  }
+
   if (!conn.connected()) {
+    Serial.println(F("I wasn't connected to the server!"));
     conn.stop();
     connectToServer();
   }
-  Serial.println(F("In loop."));
+
   Serial.flush();
   delay(2000);
   readData();
+
+  if(!pseudopod.isConfigured()) {
+    Serial.println(F("I'm not configured. Requesting configuration."));
+    delay(100);
+    pseudopod.requestConfiguration();
+  }

   if(pseudopod.shouldBroadcastPins() ) {
     delay(pseudopod.getBroadcastInterval());
@@ -44,7 +118,7 @@
 void readData() {

   while (conn.available()) {
-    Serial.println(F("Received message"));
+    Serial.println(F("!!!RECEIVED MESSAGE!!!!"));
     Serial.flush();

     if(pseudopod.readMessage() == TentacleMessageTopic_action) {
@@ -65,15 +139,44 @@
     delay(500);
   }

+  hasConnectedToServer = true;
+}
+
+void connectToLocalServer() {
+  Serial.println(F("Connecting to local server."));
+  Serial.flush();
+
+  while(!conn.connect(localServer, localPort)) {
+    Serial.println(F("Can't connect to local server."));
+    Serial.flush();
+    conn.stop();
+    delay(500);
+  }
+
+  hasConnectedToServer = true;
+}
+
+void disconnectFromServer() {
+  Serial.println(F("Disconnecting from server."));
+  Serial.flush();
+  conn.stop();
+
+  hasConnectedToServer = false;
+  hasAuthenticated = false;
+}
+
+int authenticate() {
   size_t authSize = pseudopod.authenticate(uuid, token);
   Serial.print(authSize);
   Serial.println(F(" bytes written for authentication"));
-}
-
-void debugPhoton() {
-  Serial.println(F("Waiting for slow humans."));
-  delay(2000);
-
+  Serial.flush();
+
+  hasAuthenticated = true;
+
+  return authSize;
+}
+
+void wifiInfo() {
   Serial.println(F("\n\nDebugging PHOTON"));

   Serial.print(F("\nWiFi Ready:\t"));
@@ -101,5 +204,5 @@
   Serial.println(WiFi.subnetMask());
   Serial.println(WiFi.gatewayIP());
   Serial.println(WiFi.SSID());
-
-}
+
+}


COH-80: WIP

COH-80: WIP

--- Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -351,7 +351,7 @@
 #else
   uint8_t key[16];
   if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key))
-    { OTV0P2BASE::serialPrintlnAndFlush("!TX key"); return(false); } // FAIL
+    { OTV0P2BASE::serialPrintlnAndFlush(F("!TX key")); return(false); } // FAIL
   const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEnc_ptr_t e = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS;
   uint8_t buf[OTRadioLink::SimpleSecureFrame32or0BodyTXBase::generateSecureBeaconMaxBufSize];
   const uint8_t bodylen = secureTXState.generateSecureBeaconRawForTX(buf, sizeof(buf), lenTXID, e, NULL, key); // 2 byte ID.
@@ -361,8 +361,8 @@
   // doing so may reuse IVs and destroy the cipher security.
   const bool success = (0 != bodylen) && PrimaryRadio.sendRaw(buf+1, bodylen-1);
 #if 1 && defined(DEBUG)
-  if(!success) { OTV0P2BASE::serialPrintlnAndFlush("!TX"); }
-  else { OTV0P2BASE::serialPrintlnAndFlush("TX alert"); }
+  if(!success) { OTV0P2BASE::serialPrintlnAndFlush(F("!TX")); }
+  else { OTV0P2BASE::serialPrintlnAndFlush(F("TX alert")); }
 #endif
   if(success) { return(true); } // Done!
 #endif // ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
@@ -490,8 +490,9 @@

   // If still waiting for a poll after a boost request,
   // arrange to send extra alerts about once every two minutes,
+  // no closer together than every about every 8 seconds,
   // randomly so as to minimise collisions with other regular traffic.
-  if(waitingForPollAfterBoostRequest && (sec == (OTV0P2BASE::randRNG8() & 0x3e)))
+  if(waitingForPollAfterBoostRequest && (sec == (OTV0P2BASE::randRNG8() & 0x38)))
     { sendCC1AlertByRFM23B(); }

   return(false); // No human interaction this tick...
@@ -737,12 +738,12 @@
           // Non-secure: send raw frame as-is.
           // Send at default power...  One going missing won't hurt that much.
           if(!PrimaryRadio.sendRaw(txbuf, bodylen))
-            { OTV0P2BASE::serialPrintlnAndFlush("!TX fail"); return; } // FAIL
+            { OTV0P2BASE::serialPrintlnAndFlush(F("!TX fail")); return; } // FAIL
 #else
           // Secure: wrap frame in encrypted layer...
           uint8_t key[16];
           if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key))
-            { OTV0P2BASE::serialPrintlnAndFlush("!TX key"); return; } // FAIL
+            { OTV0P2BASE::serialPrintlnAndFlush(F("!TX key")); return; } // FAIL
           const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEnc_ptr_t e = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS;
           uint8_t buf[OTRadioLink::SecurableFrameHeader::maxSmallFrameSize];

@@ -756,7 +757,7 @@

-          OTV0P2BASE::serialPrintlnAndFlush("!TX not impl"); // FAIL
+          OTV0P2BASE::serialPrintlnAndFlush(F("!TX not impl")); // FAIL
 #endif // !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
           }
         }
@@ -851,7 +852,7 @@
       oldDropped = dropped;
       }
 #endif
-#if 0 && defined(DEBUG) && !defined(ENABLE_TRIMMED_MEMORY)
+#if 1 && defined(DEBUG) && !defined(ENABLE_TRIMMED_MEMORY)
     // Filtered out messages are not an error.
     const uint8_t filtered = PrimaryRadio.getRXMsgsFilteredRecent();
     static uint8_t oldFiltered;
@@ -1140,7 +1141,7 @@
           // Secure: wrap frame in encrypted layer...
           uint8_t key[16];
           if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key))
-            { OTV0P2BASE::serialPrintlnAndFlush("!TX key"); return(false); } // FAIL
+            { OTV0P2BASE::serialPrintlnAndFlush(F("!TX key")); return(false); } // FAIL
           const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEnc_ptr_t e = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS;
           uint8_t buf[OTRadioLink::SecurableFrameHeader::maxSmallFrameSize];

@@ -1155,10 +1156,10 @@

-          OTV0P2BASE::serialPrintlnAndFlush("!TX not impl"); // FAIL
+//          OTV0P2BASE::serialPrintlnAndFlush(F("!TX not impl")); // FAIL
 #endif // !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
           // Fall-through is failure...
-          DEBUG_SERIAL_PRINT_FLASHSTRING("!TX fail");
+          OTV0P2BASE::serialPrintlnAndFlush(F("!TX fail"));
           }
         }
       }


Fixed various bugs in squareRoutine. Still prototype!

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -429,21 +429,22 @@
 }
 /*---------------------------------------------------------------------------------------*/
 //squareRoutine
-void squareRoutine(unsigned long seconds, unsigned long &results) {
+void squareRoutine(unsigned long sides, unsigned long &results) {
   Serial.println("Starting square routine...");
   results = HIGH;
-  long straightSpeed = 2500;
-  long turnSpeed = 1250;
-  unsigned long startTime = millis();
-  unsigned long loopTime;
-  seconds = seconds * 1000;
-  while(millis() < (startTime + seconds)){
+  long straightSpeed = 2500;        //mmPs
+  long turnSpeed = 1250;            //mmPs
+  sides = sides * 1000;             //convert side length to mm
+  unsigned long sideSec = sides / straightSpeed;  //calculate seconds per side at set speed
+  sideSec = sideSec * 1000          //convert to ms
+  unsigned long loopTime;           //start time of while loops for throttle
+  for(int i = 0; i < 4; i++){
     //steer(LEFT_TURN_OUT);
     steer(STRAIGHT_TURN_OUT);
     delay(1000);

     loopTime = millis();
-    while (millis() < (loopTime + 2000)) {
+    while (millis() < (loopTime + sideSec)) {
       Throttle_PID(straightSpeed);
     }

@@ -451,7 +452,7 @@
     delay(1000);

     float turnDist = TURN_RADIUS_CM * PI / 2 * 10; //turnDist == 1/4 turn circumference in mm
-    long turnSec = (long)turnDist / turnSpeed * 1000; //turnSec == time for 90-degree turn at 1250 mm/s
+    unsigned long turnSec = (long)turnDist / turnSpeed * 1000; //turnSec == time for 90-degree turn at 1250 mmPs

     loopTime = millis();
     while (millis() < (loopTime + turnSec)) {


added usb communication feedback server

added usb communication feedback server


alarm set working, with animations for wakeup and > 12 hrs

--- NeoPixelNightLight/NeoPixelNightLight.ino
+++ NeoPixelNightLight/NeoPixelNightLight.ino
@@ -1,4 +1,4 @@
-#define DEBUG
+//#define DEBUG
 #include <EEPROM.h>

 // RTC
@@ -112,10 +112,10 @@
   pinMode(MODE_SWITCH_PIN,INPUT_PULLUP);

   EEPROM.get(MODE_INDEX,mode);
+  if ( mode < 0 || mode >= sizeof(modes)/sizeof(char*))
+    mode = 0;
   Serial.print(F("Got mode from eeprom ") );
-  Serial.println(mode);
-  if ( mode < 0 )
-    mode = 0;
+  Serial.println(modes[mode]);

   int32_t wakeUnixTime;
   EEPROM.get(WAKE_INDEX,wakeUnixTime);
@@ -137,7 +137,7 @@
   if ( rtcRunning )
     return rtc.now();
   else
-    return compileTime.unixtime() + millis()/1000;
+    return compileTime.unixtime() + millis()/50;  // 1000 for close to real time
 }

 /*******************************************************************************
@@ -294,48 +294,81 @@
 }

 int prevHours = -1;
+int nextWake = 0;
+unsigned long lastWakeChange = 0;

 /*******************************************************************************
 *******************************************************************************/
 void nightlight(DateTime current, bool forceChange)
 {
-  // how many hours until wakey?
+  // how many minutes until wakey?
   double currentMin = 60.0*current.hour() + current.minute();
   double wakeyMin = 60.0*wakeTime.hour() + wakeTime.minute();

+  bool show = forceChange || checkColorChange();
+
   double diffMin = wakeyMin - currentMin;
-  if ( diffMin < 0 )
+  if ( diffMin <= 0 )
+  {
+    // for 15 minutes, animate
+    if ( diffMin > -15 )
+    {
+      if ( lastWakeChange == 0 || millis() - lastWakeChange > 100 )
+      {
+        lastWakeChange = millis();
+        for ( int i = 0; i < NEOPIXEL_LEDS; i++ )
+          strip.setPixelColor(i,Wheel(colorValue));
+        strip.setPixelColor(nextWake++ % NEOPIXEL_LEDS,0);
+        strip.show();
+        prevHours = -1;
+      }
+      DEBUG_PRINT("Wake UP! since diff min is ");
+      DEBUG_PRINTLN(diffMin);
+      return;
+    }
+
     diffMin = wakeyMin + (24.0*60)-currentMin; // remains of today + until wakey
-  int newHours = (diffMin / 60)+.5;
+  }
+  lastWakeChange = 0;
+
+  int newHours = 1.5 + (diffMin / 60); // last light 30 minutes
+
+
   if ( newHours > 12 )
-    newHours = 11; // so can tell difference between this and backlight
-
-  bool show = forceChange || checkColorChange();
-
-  if ( prevHours != newHours || show )
-  {
+  {
+    clearPixels();
+    for ( int i = 0; i < NEOPIXEL_LEDS; i+=4 )
+      strip.setPixelColor(i,Wheel(colorValue));
+
+    prevHours = newHours;
+    show = true;
+  }
+  else if ( prevHours != newHours || show )
+  {
+    clearPixels();
     show = true;
-    if ( prevHours >= 0 )
-      strip.setPixelColor(prevHours,0);
     for ( int i = 0; i < abs(newHours); i++ )
       strip.setPixelColor(i,Wheel(colorValue));
-    DEBUG_PRINT( F("PreHours "));
+    DEBUG_PRINT( F("PrevHours "));
     DEBUG_PRINT( prevHours );
     DEBUG_PRINT( F(" newHours "));
     DEBUG_PRINTLN( newHours );
     prevHours = newHours;
   }

-  if ( millis() % 1000 == 0 )
-  {
-    DEBUG_PRINT( F("Wakey - current: "));
+  if ( millis() % 1000 == 0 || show )
+  {
+    printTime(current);
+    DEBUG_PRINT( F(" (WakeyMin - currentMin) =  ("));
     DEBUG_PRINT( (int)wakeyMin );
-    DEBUG_PRINT( F("min - "));
+    DEBUG_PRINT( F(" - "));
     DEBUG_PRINT( (int)currentMin );
-    DEBUG_PRINT( F("min and diff is "));
+    DEBUG_PRINT( F(") and diff is "));
     DEBUG_PRINT( (int)diffMin );
     DEBUG_PRINT( F("min and show is "));
-    DEBUG_PRINTLN( show );
+    DEBUG_PRINT( show );
+    DEBUG_PRINT( F(" and forceChange is "));
+    DEBUG_PRINTLN( forceChange );
   }

   if ( show )


Report uptime

Report uptime

--- examples/Hello/Hello.ino
+++ examples/Hello/Hello.ino
@@ -27,6 +27,9 @@
 IotsaOtaMod otaMod(application);
 #endif

+uint32_t bootTime;
+uint32_t lastMessageTime;
+
 //
 // Hello "name" module. Greets visitors to the /hello page, and allows
 // them to change the name by which they are greeted.
@@ -45,6 +48,7 @@
   	rv += "\" that is currently greeted.";
   }
   rv += "
";
+  rv += "
Last power cycle " + String(millis()/1000) + "s, last boot time " + String((millis()-bootTime)/1000) + "s.
";
   return rv;
 }

@@ -80,4 +84,9 @@
 void loop(void){
   application.loop();
   // Add your loop code here.
+  if (millis() > lastMessageTime + 600000) {
+    IotsaSerial.print("Uptime (minutes): ");
+    IotsaSerial.println(millis()-lastMessageTime / 60000);
+    lastMessageTime = millis();
+  }
 }


Winterzeit

Winterzeit

--- firmware/application.ino
+++ firmware/application.ino
@@ -29,7 +29,7 @@
 HttpClient* httpClient;

 void setup() {
-	Time.zone(+2.0); // DST / Sommerzeit // TODO: detect DST
+	Time.zone(+1.0); // +1.0/+2.0 Winer / Sommerzeit // TODO: detect DST
 	Serial.begin(9600);
 	pinMode(activityLed, OUTPUT);


lcd button switch case

lcd button switch case


Update ServoArduino.ino

Update ServoArduino.ino

Primeira versão do Sketch para o arduino com controle do servo, comunicação serial e com a leitura dos dados da Bussola.
Ainda não esta 100% funcional


Update Relay.ino

Update Relay.ino


Cursor positioning for manual receiver IP entry.


added control for remot ESP-Relay

added control for remot ESP-Relay

--- ESP_Relay/ESP_Relay.ino
+++ ESP_Relay/ESP_Relay.ino
@@ -20,7 +20,7 @@

 #define udp_port 8981
 #define description "Living Room"
-#define maxRemoteEsps 20
+#define maxRemoteEsps 9

 //*****************************************************************************
 // Array of remote ESP8266
@@ -52,7 +52,7 @@

 //*****************************************************************************
 // State
-char relayState[5] = "1010";
+char relayState[5] = "0000";
 char current[5] = "1250";

 //*****************************************************************************
@@ -115,7 +115,9 @@
   message += ".";
   message += ip[3];
   message += "
";
-
+  message += "
";
+
+  //Remote ESP-Relays
   for( int i=0; i < maxRemoteEsps; i++){
     if(strcmp("",remote_esps[i].name) != 0){
       message += remote_esps[i].name;
@@ -124,25 +126,58 @@
       message += remote_esps[i].relayState;
       message += "
";
       //check relay state
-      if (relayState[0] == '0'){
+      // /001 -> 0 = 1ESP-Relay 0=first relay(0,1,2 or 3) 1=ON
+      if (remote_esps[i].relayState[0] == '0'){
+        message += "";
         message += svg_relayOff;
+        message += "";
       }else{
+        message += "";
         message += svg_relayOn;
-      }
-      if (relayState[1] == '0'){
+        message += "";
+      }
+      if (remote_esps[i].relayState[1] == '0'){
+        message += "";
         message += svg_relayOff;
+        message += "";
       }else{
+        message += "";
         message += svg_relayOn;
-      }
-      if (relayState[2] == '0'){
+        message += "";
+      }
+      if (remote_esps[i].relayState[2] == '0'){
+        message += "";
         message += svg_relayOff;
+        message += "";
       }else{
+       message += "";
         message += svg_relayOn;
-      }
-      if (relayState[3] == '0'){
+        message += "";
+      }
+      if (remote_esps[i].relayState[3] == '0'){
+        message += "";
         message += svg_relayOff;
+        message += "";
       }else{
+        message += "";
         message += svg_relayOn;
+        message += "";
       }
       message += "
";
       message += "\nCurrent: ";
@@ -159,10 +194,11 @@
       message += "
";
     }
   }
-
+
   server.send(200, "text/html", message);
   digitalWrite(LED, 1);
 }
+
 void handleRoot() {
   buildHtml();
 }
@@ -173,65 +209,82 @@
   buildHtml();
 }
 void relay1Off(){
-  digitalWrite(pinRelay1, LOW);
+  digitalWrite(pinRelay1, LOW);
   relayState[0] = '0';
   buildHtml();
 }

 void relay2On(){
-  digitalWrite(pinRelay2, HIGH);
+  digitalWrite(pinRelay2, HIGH);
   relayState[1] = '1';
   buildHtml();
 }
 void relay2Off(){
   digitalWrite(pinRelay2, LOW);
-  relayState[1] = '0';
+  relayState[1] = '0';
   buildHtml();
 }

 void relay3On(){
-  digitalWrite(pinRelay3, HIGH);
-  relayState[2] = '1';
+  digitalWrite(pinRelay3, HIGH);
+  relayState[2] = '1';
   buildHtml();
 }
 void relay3Off(){
-  digitalWrite(pinRelay3, LOW);
-  relayState[2] = '0';
+  digitalWrite(pinRelay3, LOW);
+  relayState[2] = '0';
   buildHtml();
 }

 void relay4On(){
-  digitalWrite(pinRelay4, HIGH);
-  relayState[3] = '1';
+  digitalWrite(pinRelay4, HIGH);
+  relayState[3] = '1';
   buildHtml();
 }
 void relay4Off(){
-  digitalWrite(pinRelay4, LOW);
-  relayState[3] = '0';
-  buildHtml();
-}
-
+  digitalWrite(pinRelay4, LOW);
+  relayState[3] = '0';
+  buildHtml();
+}

 void handleNotFound(){
   digitalWrite(LED, 1);
-  String message = "File Not Found\n\n";
-  message += "URI: ";
-  message += server.uri();
-  message += "\nMethod: ";
-  message += (server.method() == HTTP_GET)?"GET":"POST";
-  message += "\nArguments: ";
-  message += server.args();
-  message += "\n";
-  for (uint8_t i=0; i<server.args(); i++){
-    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
-  }
-  server.send(404, "text/plain", message);
+  Serial.println(server.uri());
+  // which ESP-Relay
+  if (isdigit(server.uri()[1])){
+    int i = server.uri()[1] - '0';
+    Serial.print("Set ");
+    Serial.print(remote_esps[i].name);
+
+    // which Relay
+    if (isdigit(server.uri()[2])){
+      int n = server.uri()[2] - '0';
+      Serial.print(" Relay ");
+        Serial.print( n + 1 );
+
+        // which state
+        if (isdigit(server.uri()[3])){
+          int remoteState = server.uri()[3] - '0';
+          Serial.print(" to ");
+          Serial.println( remoteState );
+          Serial.print(remote_esps[i].ip);
+          Serial.print(remote_esps[i].udpPort);
+
+          udp.beginPacket(remote_esps[i].ip, udp_port);
+          udp.write("3;");
+          udp.write(n + '0');
+          udp.write(remoteState + '0');
+          udp.endPacket();
+        }
+    }
+  }
+  buildHtml();
   digitalWrite(LED, 0);
 }
 void udpBroadcast(){
   digitalWrite(LED, 0);
   Serial.println ( "Hello Broadcast send" );
-
+
   // transmit broadcast package
   udp.beginPacket(broadcastIp, udp_port);
   udp.write("1");
@@ -259,7 +312,7 @@
     }
     Serial.print("Contents:");
     Serial.println(packetBuffer);
-
+
     // Reply to broadcast
     if ( packetBuffer[0] == '1' ){
       Serial.println("Sending UDP response");
@@ -273,7 +326,51 @@
       udp.write(current);
       // Add relay data and current
       udp.endPacket();
-    }
+    }
+
+    // Reply to broadcast
+    if ( packetBuffer[0] == '3' ){
+      Serial.println("Remote Control");
+      Serial.println(packetBuffer[2]);
+      switch ( packetBuffer[2] - '0' ) {
+        case 0:
+          Serial.println(" Set Relay 1");
+          if(packetBuffer[3] == '0'){
+            relay1Off();
+          } else {
+            relay1On();
+          }
+          break;
+        case 1:
+         Serial.println(" Set Relay 2");
+          if(packetBuffer[3] == '0'){
+            relay2Off();
+          } else {
+            relay2On();
+          }
+          break;
+        case 2:
+          Serial.println(" Set Relay 3");
+          if(packetBuffer[3] == '0'){
+            relay3Off();
+          } else {
+            relay3On();
+          }
+          break;
+        case 3:
+         Serial.println(" Set Relay 4");
+          if(packetBuffer[3] == '0'){
+            relay4Off();
+          } else {
+            relay4On();
+          }
+          break;
+        default:
+          // if nothing else matches, do the default
+          // default is optional
+        break;
+      }
+    }

     // Receiving broadcast respons
     if ( packetBuffer[0] == '2' ){
@@ -281,19 +378,19 @@
       // parse data and add/update remote_esps
       int field = 0;
       int offset = 2; // 2 becauss packet starts with "2,"
-
+
       char nameBuffer[255];
       char relayBuffer[5];
       char currentBuffer[5];
-
+
       for( int i=2; i < packetSize; i++){
         Serial.print(packetBuffer[i]);
-
+
         if( packetBuffer[i] == ';' ){
           offset = i + 1;
           field = field + 1;
         }
-
+
         switch ( field ) {
           case 0:
             nameBuffer[i-offset] = packetBuffer[i];
@@ -307,18 +404,18 @@
             currentBuffer[i-offset] = packetBuffer[i];
             currentBuffer[i-offset+1] = '\0';
             break;
-          default:
+          default:
             // if nothing else matches, do the default
             // default is optional
           break;
         }
       }
-
+
       Serial.println("");
       Serial.println(nameBuffer);
       Serial.println(relayBuffer);
       Serial.println(currentBuffer);
-
+
       int updateEntry = -1;
       for( int i=0; i < maxRemoteEsps; i++){
         // if name exists in array
@@ -330,22 +427,22 @@
           updateEntry = i;
         }
       }
-
+
       Serial.print("Update entry: ");
       Serial.println(updateEntry);
-
+
       strcpy(remote_esps[updateEntry].name, nameBuffer);
       remote_esps[updateEntry].ip = udp.remoteIP();
       remote_esps[updateEntry].udpPort = udp.remotePort();
       strcpy(remote_esps[updateEntry].relayState, relayBuffer);
       remote_esps[updateEntry].current = atoi(currentBuffer);
-
+
       // Print updated data
       Serial.println(remote_esps[updateEntry].name);
       Serial.println(remote_esps[updateEntry].ip);
       Serial.println(remote_esps[updateEntry].udpPort);
       Serial.println(remote_esps[updateEntry].current);
-    }
+    }
   }
   digitalWrite(LED, 1);
 }
@@ -385,7 +482,7 @@
   udp.begin(udp_port);
   broadcastIp = WiFi.localIP();
   broadcastIp[3] = 255;
-
+
   Serial.println ( "" );
   Serial.print ( "UDP Server started on Port: " );
   Serial.println ( udp_port );
@@ -402,14 +499,14 @@
   server.on("/3Off", relay3Off);
   server.on("/4ON", relay4On);
   server.on("/4Off", relay4Off);
-
+
   server.onNotFound(handleNotFound);
   server.begin();
-
+
   digitalWrite ( LED, LOW );
   delay(500);
   digitalWrite ( LED, HIGH );
-
+
   udpBroadcasTimer.setInterval(5000,udpBroadcast);
 }


DHT22 Test - Temperatura y Humedad

DHT22 Test - Temperatura y Humedad

--- LM4F_E010/LM4F_E010.ino
+++ LM4F_E010/LM4F_E010.ino
@@ -12,7 +12,7 @@
  * Description:     Este ejemplo se basa en la libreria de Adafruit para el
  *                  sensor de temperatura y humedad DHT22, cuando sepulsa SW1
  *                  la Stellaris envia los datos al monitor serial y realiza
- *                  un blink en el LED Azul, si se vuelve a pulsar SW1 el
+ *                  un blink en el LED Azul, cuando se vuelve a pulsar SW1 el
  *                  envio se detiene y tambien el blink.
  *******************************************************************************
  * Rev.         Date            Comment


[MC34063/BuckConverter] rm unnecessary sketch


Check body size before updating char array

--- http_test.ino
+++ http_test.ino
@@ -17,7 +17,7 @@
 // Number of milliseconds to wait if no data is available before trying again
 const int kNetworkDelay = 200;
 // If Content-Length isn't given this is used for the max body length
-const int fallbackContentLength = 1024;
+const int kFallbackContentLength = 1024;

 void setup() {
   Serial.begin(9600);
@@ -78,7 +78,9 @@
           if (http.available())
           {
             c = http.read();
-            body[i] = c;
+            // Let's make sure this character will fit into our char array
+            if (i <= bodyLen)
+              body[i] = c;
             i++;
             // We read something, reset the timeout counter
             timeoutStart = millis();


TODO-844: moved xtal check down

TODO-844: moved xtal check down

--- V0p2_Main/V0p2_Main.ino
+++ V0p2_Main/V0p2_Main.ino
@@ -354,78 +354,10 @@
 //    DEBUG_SERIAL_PRINT(fastDigitalRead(BUTTON_LEARN_L)); DEBUG_SERIAL_PRINTLN();
 //    DEBUG_SERIAL_PRINT(fastDigitalRead(BUTTON_LEARN2_L)); DEBUG_SERIAL_PRINTLN(); // AKA WINDOW SWITCH
 #endif
-#endif // select user-facing boards.
+#endif // Select user-facing boards.

 #if defined(ENABLE_WAKEUP_32768HZ_XTAL)
-  // Check that the 32768Hz async clock is actually running having done significant CPU-intensive work.
-  const uint8_t laterSCT = OTV0P2BASE::getSubCycleTime();
-  if(laterSCT == earlySCT)
-    {
-#if defined(ENABLE_WAKEUP_32768HZ_XTAL)
-    // Allow extra time for 32768Hz crystal to start reliably, see: http://www.atmel.com/Images/doc1259.pdf
-#if 0 && defined(DEBUG)
-    DEBUG_SERIAL_PRINTLN_FLASHSTRING("Sleeping to let 32768Hz clock start...");
-#endif
-    // Time spent here should not be a whole multiple of basic cycle time to avoid a spuriously-stationary async clock reading!
-    // Allow several seconds to start.
-    // Attempt to capture some entropy while waiting, implicitly from oscillator start-up time if nothing else.
-    for(uint8_t i = 255; (--i > 0) && (earlySCT == OTV0P2BASE::getSubCycleTime()); )
-      {
-      OTV0P2BASE::addEntropyToPool(OTV0P2BASE::clockJitterWDT() ^ OTV0P2BASE::noisyADCRead(), 1); // Conservatively hope for at least 1 bit from combined sources!
-      OTV0P2BASE::nap(WDTO_15MS); // Ensure lower mount of ~3s until loop finishes.
-      OTV0P2BASE::captureEntropy1(); // Have other fun, though likely largely ineffective at this stage.
-      }
-#endif
-    const uint8_t latestSCT = OTV0P2BASE::getSubCycleTime();
-    if(latestSCT == earlySCT)
-      {
-#if 0 && defined(DEBUG)
-      DEBUG_SERIAL_PRINTLN_FLASHSTRING("32768Hz clock may not be running!");
-#endif
-      panic(F("Xtal")); // Async clock not running.
-      }
-    }
-//  posPOST(2, F("slow RTC clock OK"));
-#if 1 // Probationary Xtal sanity check
-  // Test low frequency oscillator vs main clock oscillator.
-  // Tests clock frequency with 15 ms nap in between for up to 30 cycles and panics if not within bounds.
-  // As of 2016-02-16, all working REV7s give count >= 120 and that fail to program via bootloader give count <= 119
-  // REV10 gives 119-120 (only one tested though)
-  {
-    static const uint8_t optimalLFClock = 122; // might be optimal...
-    static const uint8_t errorLFClock = 4; // max drift from allowed value
-    uint8_t count = 0;
-    for(uint8_t i = 0; ; i++) {
-      ::OTV0P2BASE::nap(WDTO_15MS);
-      ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
-      // wait for edge on xtal counter
-      // start counting cycles
-      // on next edge, stop
-          const uint8_t t0 = TCNT2;
-          while(t0 == TCNT2) {}
-          const uint8_t t01 = TCNT0;
-          const uint8_t t1 = TCNT2;
-          while(t1 == TCNT2) {}
-          const uint8_t t02 = TCNT0;
-          count = t02-t01;
-      }
-      // Check end conditions
-      if((count < optimalLFClock+errorLFClock) & (count > optimalLFClock-errorLFClock)) { break; }
-      if(i > 30) { panic(F("xtal")); }
-      // Capture some entropy from the (chaotic?) clock wobble, but don't claim any.  (TODO-800)
-      OTV0P2BASE::addEntropyToPool(count, 0);
-//      // Also perturb the PRNG with essentially the same data (which is one reason not to claim entropy above).
-//      OTV0P2BASE::seedRNG8(count, i, TCNT2);
-    }
-    // optionally print value to debug
-#if 0 && defined(DEBUG)
-    DEBUG_SERIAL_PRINT_FLASHSTRING("Xtal freq check: ");
-    DEBUG_SERIAL_PRINT(count);
-    DEBUG_SERIAL_PRINTLN();
-#endif
-  }
-#endif // Probationary Xtal sanity check
-
+  if(!::OTV0P2BASE::HWTEST::check32768HzOsc()) { panic(F("Xtal")); } // Async clock not running correctly.
 #else
   DEBUG_SERIAL_PRINTLN_FLASHSTRING("(No xtal.)");
 #endif


Signed-off-by: Roar Fredriksen <Roar Fredriksen>

--- examples/BlinkOnMqttMessage/BlinkOnMqttMessage.ino
+++ examples/BlinkOnMqttMessage/BlinkOnMqttMessage.ino
@@ -1,9 +1,9 @@
 #include <iotecoclient.h>

-#define APP_NAME    "GarageDoor"
-#define WLAN_SSID       "Roar_Etne"
-#define WLAN_PASS       "monoLi10"
-#define AIO_SERVER      "192.168.10.203"
+#define APP_NAME    "mySEnsorApp"
+#define WLAN_SSID       "myAccessPoint"
+#define WLAN_PASS       "myAPPassword"
+#define AIO_SERVER      "myMQTTAddress"
 #define AIO_SERVERPORT  1883
 const int version[] = { 1, 0, 0, 0 };


Time revisions

Time revisions

--- Arduino_HVAC_Controller/Networked_HVAC_Controller/Networked_HVAC_Controller.ino
+++ Arduino_HVAC_Controller/Networked_HVAC_Controller/Networked_HVAC_Controller.ino
@@ -397,7 +397,7 @@
 // Returns:       An unsigned long representing time in hours and minutes
 // Description:   TODO ____________________________________________________
 // ----------------------------------------------------------------------------------------
-unsigned long get_time()
+char* get_time()
 {
   sendNTPpacket(timeServer); // send an NTP packet to a time server
   unsigned long epoch;
@@ -424,7 +424,7 @@
     epoch = secsSince1900 - seventyYears - (5 * 3600);

   }
-  return epoch;
+  return timeString;
 }

 // ----------------------------------------------------------------------------------------


motors_controller renamed to stepper_motors_controller

--- jenny5-firmware/jenny5-firmware.ino
+++ jenny5-firmware/jenny5-firmware.ino
@@ -8,7 +8,7 @@
 #include "infrared_sensors_controller.h"
 //#include "MemoryFree.h"

-t_motors_controller motors_controller;
+t_stepper_motors_controller stepper_motors_controller;
 t_potentiometers_controller potentiometers_controller;
 t_ultrasonic_sensors_controller ultrasonic_sensors_controller;
 t_infrared_sensors_controller infrared_sensors_controller;
@@ -29,14 +29,7 @@
 void setup()
 {
   first_start = 0;
-  strcpy(firmware_version, "2016.02.01.1");
-
-  //motors_controller.set_num_motors(2);
-
- // ultrasonic_sensors_controller.set_num_sensors(1);
-
-  //potentiometers_control = new t_potentiometers_controller(4, potentiometers_pins, potentiometer_limits);
-  //infrared_sensors_control = new t_infrared_sensors_controller (2, infrared_pins);
+  strcpy(firmware_version, "2016.02.09.0");

   current_buffer[0] = 0;

@@ -86,7 +79,7 @@
         int motor_index, num_steps;
         int num_read = sscanf(tmp_str + i + 1, "%d%d", &motor_index, &num_steps);
         if (num_read == 2){
-          motors_controller.move_motor(motor_index, num_steps);
+          stepper_motors_controller.move_motor(motor_index, num_steps);
           is_command_running = 1;
           i += 4;
         }
@@ -122,7 +115,7 @@
         if (tmp_str[i] == 'D' || tmp_str[i] == 'd'){// disables motor
           int motor_index;
           sscanf(tmp_str + i + 1, "%d", &motor_index);
-          motors_controller.disable_motor(motor_index);
+          stepper_motors_controller.disable_motor(motor_index);
           sprintf(serial_out, "D%d#", motor_index);
           i += 2;
         }
@@ -130,7 +123,7 @@
           if (tmp_str[i] == 'L' || tmp_str[i] == 'l'){// locks motor
             int motor_index;
             sscanf(tmp_str + i + 1, "%d", &motor_index);
-            motors_controller.lock_motor(motor_index);
+            stepper_motors_controller.lock_motor(motor_index);
             sprintf(serial_out, "L%d#", motor_index);
             i += 2;
           }
@@ -138,7 +131,7 @@
           if (tmp_str[i] == 'H' || tmp_str[i] == 'h'){// go home
             int motor_index;
             sscanf(tmp_str + i + 1, "%d", &motor_index);
-            motors_controller.go_home(motor_index, &potentiometers_controller);
+            stepper_motors_controller.go_home(motor_index, &potentiometers_controller);
             sprintf(serial_out, "H%d#", motor_index);
             is_command_running = 1;
             i += 2;
@@ -149,7 +142,7 @@
               int motor_index;
               int motor_speed, motor_acceleration;
               sscanf(tmp_str + i + 2, "%d%d%d", &motor_index, &motor_speed, &motor_acceleration);
-              motors_controller.set_motor_speed_and_acceleration(motor_index, motor_speed, motor_acceleration);
+              stepper_motors_controller.set_motor_speed_and_acceleration(motor_index, motor_speed, motor_acceleration);
               i += 5;
             }
             else
@@ -164,7 +157,7 @@
           if (tmp_str[i] == 'A' || tmp_str[i] == 'a'){// attach sensors to motors
             int motor_index, num_sensors;
             sscanf(tmp_str + i + 1, "%d%d", &motor_index, &num_sensors);
-            motors_controller.set_num_attached_sensors(motor_index, num_sensors);
+            stepper_motors_controller.set_num_attached_sensors(motor_index, num_sensors);
             // now I have to add sensors one by one
             int j = i + 4;
             i += 4;
@@ -172,7 +165,7 @@
               if (tmp_str[j] == 'P' || tmp_str[j] == 'p'){
                 int sensor_index;
                 sscanf(tmp_str + j + 1, "%d", &sensor_index);
-                motors_controller.add_sensor(motor_index, POTENTIOMETER, sensor_index);
+                stepper_motors_controller.add_sensor(motor_index, POTENTIOMETER, sensor_index);
                 i += 2;
               }
               j++;
@@ -185,7 +178,7 @@
               int motor_index;
               float motor_speed, motor_acceleration;
               sscanf(tmp_str + i + 2, "%d", &motor_index);
-              motors_controller.get_motor_speed_and_acceleration(motor_index, &motor_speed, &motor_acceleration);
+              stepper_motors_controller.get_motor_speed_and_acceleration(motor_index, &motor_speed, &motor_acceleration);
               sprintf(serial_out, "MP%d %d %d#", motor_index, (int)motor_speed, (int)motor_acceleration);
               i += 4;
             }
@@ -221,18 +214,18 @@
          else
            if (tmp_str[i] == 'C' || tmp_str[i] == 'c'){// create something
              if (tmp_str[i + 1] == 'M' || tmp_str[i + 1] == 'm'){// create a list of motors
-               if (!motors_controller.is_motor_running()){
+               if (!stepper_motors_controller.is_motor_running()){
                  int num_motors = 0;

                  int num_consumed = 0;
                  sscanf(tmp_str + i + 3, "%d%n", &num_motors, &num_consumed);

                  int num_consumed_total = 3 + num_consumed;
-                 motors_controller.set_num_motors(num_motors);
+                 stepper_motors_controller.set_num_motors(num_motors);
                  for (int k = 0; k < num_motors; k++){
                    int _step_pin, _dir_pin, _enable_pin;
                    sscanf(tmp_str + i + num_consumed_total, "%d%d%d%n", &_dir_pin, &_step_pin, &_enable_pin, &num_consumed);
-                   motors_controller.set_motor_pins(k, _dir_pin, _step_pin, _enable_pin);
+                   stepper_motors_controller.set_motor_pins(k, _dir_pin, _step_pin, _enable_pin);
                    num_consumed_total += num_consumed + 1;
                  }

@@ -381,7 +374,7 @@
         }
     }
   }
-  motors_controller.run_motors(&potentiometers_controller, serial_out);
+  stepper_motors_controller.run_motors(&potentiometers_controller, serial_out);
   if (serial_out[0])
     Serial.write(serial_out);


Update rx5808-pro-diversityGc9n.ino

Update rx5808-pro-diversityGc9n.ino


using array

using array

--- _08-lg-ac-ir/_08-lg-ac-ir-nano/_08-lg-ac-ir-nano.ino
+++ _08-lg-ac-ir/_08-lg-ac-ir-nano/_08-lg-ac-ir-nano.ino
@@ -19,6 +19,10 @@
 // 1 : mid
 // 2 : high
 // 3 : rotate
+
+const int AC_FLOW_TOWER[4] = {0, 4, 6, 12}
+const int AC_FLOW_WALL[4]  = {0, 2, 4, 5}
+

 int AC_AIR_ACLEAN  = 0;
 // 0 : off
@@ -90,9 +94,14 @@
   int AC_MSBITS4 = 0;
   int AC_MSBITS5 = temperature - 15;
   int AC_MSBITS6 ;
-
-
-
+
+  if ( AC_TYPE == 0) {
+    AC_MSBITS6 = AC_FLOW_TOWER[air_flow];
+  } else {
+    AC_MSBITS6 = AC_FLOW_WALL[air_flow]
+  }
+
+/*
   if ( AC_TYPE == 0) {
     if ( air_flow == 0 ) {
       AC_MSBITS6 = 0;
@@ -121,6 +130,7 @@
     }

   }
+*/

   int AC_MSBITS7 = (AC_MSBITS3 + AC_MSBITS4 + AC_MSBITS5 + AC_MSBITS6) & B00001111;


Remove old import

Remove old import

--- home-node/home-node.ino
+++ home-node/home-node.ino
@@ -2,7 +2,7 @@
 #define MAX_HANDLERS 8
 #define CONFIG_TOPIC_PREFIX "config/"

-#include <system.h>
+
 #include <MQTTClient.h>
 #include <ESP8266WiFi.h>
 #include <ArduinoJson.h>


Add comments and fix whitespace

Add comments and fix whitespace

--- humidity1/humidity1.ino
+++ humidity1/humidity1.ino
@@ -1,24 +1,26 @@
 #include <limits.h>  // For ULONG_MAX

-static const int VCCPin = 9;
-static const int analogPin = 0;
-static const int tempPin = 4;
-static const float Re = 50.3; // kOhm
-//static const float Vref = 5.0 * 15 / (15 + 51);
-static const float Vref = 5.0;
-static const float Vm = 2.5;
+static const int VCCPin = 9;  // Digital, Power pin to drive the 1kHz square wave
+static const int humidityPin = 0;  // Analog, Humidity sensor reading pin
+static const int tempPin = 4;  // Analog, Temperature sensor reading pin

+static const float Re = 50.3;  // Reference resistor R1, kOhm, measured
+static const float Vref = 5.0;  // Voltage high reference (Vcc high)
+static const float Vm = 2.5;  // Voltage middle reference (capacitors are charged to this on average)

+// Fitted parameters for Resitance->Humidity conversion of CM-R
+// at 25C
 static float a = 2.76366367;
 static float b = -32.40924966;
 static float c = 102.93566686;

+// Helper variables
 int val = 0;
 int count = 0;
 unsigned long t;
 boolean level = LOW;
 unsigned long nowt;
-static unsigned long microwait = 500;
+static unsigned long microwait = 500;  // Half length of 1kHz period in microsecond
 unsigned long deltat;

 void setup() {
@@ -31,8 +33,9 @@
 }

 void loop() {
-  float temp, hum, res;
-
+  float temperature, humidity, resistance;
+
+  // Get the elapsed time
   nowt = micros();
   if (nowt >= t) {
     deltat = nowt - t;
@@ -41,62 +44,70 @@
     // Taking care of micros overflow that should happen every 70 minutes or so
     deltat = ULONG_MAX - t + nowt;
   }
+
+  // If half a period is elapsed, switch the output level of VCC to get the square wave
   if (deltat > microwait) {
     digitalWrite(VCCPin, level);
     if (level == HIGH) {
-      if (count == 400) {
-        res = GetResistance();
+      // After every this many switching, do a weather reading
+      // count set empirically to approx. 1 times every second (Leonardo)
+      if (count == 935) {
+
+        // Read resistor value
+        resistance = GetResistance();

         digitalWrite(VCCPin, LOW);
         delay(50);
-        temp = GetTemperature();
+        temperature = GetTemperature();
         digitalWrite(VCCPin, HIGH);
-
-        hum = GetHumidity(res, temp);
-        Serial.print("H,");  // Device identifier
-        Serial.print(hum);
+
+        // Do the conversion from resistance->humidity
+        humidity = GetHumidity(resistance);
+
+        // Send data over the serial connection
+        Serial.print("H,");  // Device identifier message header
+        Serial.print(humidity);
         Serial.print(",");
-        Serial.print(res);
+        Serial.print(resistance);
         Serial.print(",");
-        Serial.print(temp);
+        Serial.print(temperature);
         Serial.println();
-        count = 0;
+        count = 0;  // restart counter
       } else {
-        count++;
+        count++;  // count up till have to measure values again
       }
     }
-    level = !level;
+    level = !level;  // switch the levels
     t = nowt;
   }
 }

 // Output resistance in kOhm
 float GetResistance(void) {
-  float resistance, volt;
+  float resistance, voltage;
   int val;

-  val = analogRead(analogPin);
-  volt = val * 5.0 / 1024;
+  val = analogRead(humidityPin);
+  voltage = val * 5.0 / 1024;

-  if (volt < Vm) {
+  if (voltage < Vm) {
     resistance = -1;
   }
-  else if (volt > Vref) {
+  else if (voltage > Vref) {
     resistance = -2;
   }
   else {
     // if in range, calculate resistance value
-    resistance = Re / ((Vref-Vm)/(volt-Vm) - 1);
+    resistance = Re / ((Vref-Vm)/(voltage-Vm) - 1);
   }
   return (resistance);
 }

-// Rewrite these into two functions so can retrive the resistance
-// separately and use temperature to get correct value;
-float GetHumidity(float resistance, float temperature) {
+// Convert resistance value into humidity value using the polinomial parameters
+float GetHumidity(float resistance) {
   float humidity;

-  if (resistance < 0) {
+  if (resistance <= 0) {
      // this means there was some error in the resistance measurement
      if (resistance == -1) {
        humidity = 0.0;
@@ -107,21 +118,28 @@
      }
   }
   else {
+    // positive resistance reading
     float reslog = log10(resistance);
     humidity = a * reslog*reslog + b * reslog + c;
+
+    // set limits correctly
     if (humidity > 100.0) {
       humidity = 100.0;
     }
     else if (humidity < 0.0) {
       humidity = 0.0;
     }
+
   }
   return (humidity);
 }

+// Temperature reading from voltage and LM335 conversion factor
 float GetTemperature(void) {
-  float temperature;
-  temperature = analogRead(tempPin) * 5.0 / 1024.0 / 0.01;
+  float temperature, voltage;
+  voltage = analogRead(tempPin) * 5.0 / 1024.0;
+  // LM335 has 10mV/K conversion
+  temperature = voltage / 0.01;
   return (temperature);
 }


Update timer_overflow_interrupt.ino

Update timer_overflow_interrupt.ino

--- interrupts/timer_overflow_interrupt.ino
+++ interrupts/timer_overflow_interrupt.ino
@@ -46,7 +46,7 @@
   TCCR1A = 0; // reset timer/counter control register A for Timer1
   TCCR1B = 0; // reset timer/counter control register B for Timer1

-  TCNT1 = TIMER_PRELOAD; // timer/counter
+  TCNT1 = TIMER_PRELOAD; // preload Timer Counter 1
   TCCR1B |= (1 << CS12); // clock select (Timer1, bit2 -> 1/256 prescale)
   TIMSK1 |= (1 << TOIE1); // enable the timer overflow interrupt (TOIE1) in the
                           // timer interrupt mask for Timer1 (TIMSK1)


misc changes to battery module

misc changes to battery module


Debugging should be off in release.

Debugging should be off in release.

--- esp8266/esp8266.ino
+++ esp8266/esp8266.ino
@@ -55,9 +55,9 @@
 //#define HTTP_DEBUG_ON
 //#define MDNS_DEBUG_ON
 //#define STAT_DEBUG_ON
-#define INPT_DEBUG_ON
-#define WIFI_DEBUG_ON
-#define FILE_DEBUG_ON
+//#define INPT_DEBUG_ON
+//#define WIFI_DEBUG_ON
+//#define FILE_DEBUG_ON
 //#define FILE_SERVE_ON	// Useful when debuggig to see SPIFF files from a browser

 //
@@ -65,7 +65,6 @@
 //

 #define MAX_COOKIES 10
-#define DEBUG_ON

 //


[modified] main ino file to test eeprom writing

--- arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
+++ arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
@@ -32,17 +32,32 @@
 	//Setting the test pin high enables direct writing of internal registers and stops transactions with External EEPROM
 	pga.enableTestPin();

-	util::WriteToMultiRegisters(&pga, regData, regToWriteTo, (sizeof(regData)/sizeof(int)));
-	util::ReadFromMultRegisters(&pga, regToReadFrom, (sizeof(regToReadFrom)/sizeof(int)));
-	Serial.print("Status of writing to the ADS internal register:");
-	Serial.println(ads.write(ADSREG));
-	delay(1000);
+	eeprom.read(0x00);
+	Serial.println(eeprom.getRecData());
+	eeprom.write(0x00, 0x12);
+	Serial.println(eeprom.getRecData());
+	eeprom.read(0x02);
+	Serial.println(eeprom.getRecData());
+	eeprom.write(0x02, 0x13);
+	Serial.println(eeprom.getRecData());
+	eeprom.read(0x01);
+	Serial.println(eeprom.getRecData());
+	eeprom.write(0x01, 0x14);
+	Serial.println(eeprom.getRecData());
+
+
+
+	// util::WriteToMultiRegisters(&pga, regData, regToWriteTo, (sizeof(regData)/sizeof(int)));
+	// util::ReadFromMultRegisters(&pga, regToReadFrom, (sizeof(regToReadFrom)/sizeof(int)));
+	// Serial.print("Status of writing to the ADS internal register:");
+	// Serial.println(ads.write(ADSREG));
+	// delay(1000);

 }

 void loop(){
 	// util::printMenu();
-	util::ReadADSData(&ads, ADSData);
-	util::ReadErrorREG(&pga);
+	// util::ReadADSData(&ads, ADSData);
+	// util::ReadErrorREG(&pga);
 }


works better-er

works better-er

--- button_multichannel_rf1/button_multichannel_rf1.ino
+++ button_multichannel_rf1/button_multichannel_rf1.ino
@@ -519,7 +519,7 @@

 int* senseResults;

-#define smoothedSenseSize 25
+#define smoothedSenseSize 20
 int smoothedSenseHistory[channelCount][smoothedSenseSize];
 int smoothedSenseIter = 0;

@@ -531,7 +531,7 @@
 int smoothedSampleTemp[smoothedSenseSize - smoothedTouchWindow];

 int channelMean[] = {0, 0, 0, 0};
-int chanThreshold[] = {5,5,5,5};
+int chanThreshold[] = {9,9,9,9};

 void loop() {
     senseResults = senseAll(1500, true);
@@ -555,19 +555,30 @@
       int tempVal = 0;
       sort(senseHistoryTemp, senseSize);

-      for (int i = 10; i < 13; i++) {
+      for (int i = 0; i < 2; i++) {
         tempVal += senseHistoryTemp[i];
       }

-      smoothedSenseHistory[channel][smoothedSenseIter] = tempVal / 3;
+      smoothedSenseHistory[channel][smoothedSenseIter] = tempVal / 2;

       Serial.print(smoothedSenseHistory[channel][smoothedSenseIter]);
       Serial.print(", ");
+
+
+//    if(senseHistoryIter==0  && channel == 2){
+//      for(int i=0; i<25; i++){
+//        Serial.print(senseHistoryTemp[i]);
+//        Serial.print(", ");
+//      }
+//      Serial.println();
+//
+//    }
+
     }

     for (int channel = 0; channel < channelCount; channel++) {
-      channelMean[channel] = (channelMean[channel] * 3 +
-                              smoothedSenseHistory[channel][(smoothedSenseIter + 1 + smoothedSenseSize) % smoothedSenseSize]) / 4;
+      channelMean[channel] = (channelMean[channel] * 2 +
+                              smoothedSenseHistory[channel][(smoothedSenseIter + 1 + smoothedSenseSize) % smoothedSenseSize]) / 3;
       Serial.print(", ");
       Serial.print(smoothedSenseHistory[channel][smoothedSenseIter] - channelMean[channel]);
       Serial.print(", ");
@@ -586,6 +597,7 @@
     }

     Serial.println();
+

     if (isTouched && switchedCount == 0) {


Set initial value of switch characateristic

--- libraries/CurieBle/examples/LED/LED.ino
+++ libraries/CurieBle/examples/LED/LED.ino
@@ -42,6 +42,8 @@
   blePeripheral.addAttribute(ledService);
   blePeripheral.addAttribute(switchCharacteristic);

+  switchCharacteristic.setValue(0);
+
   // begin initialization
   blePeripheral.begin();


Swapped front and back sensor

Swapped front and back sensor

--- src/AccidentDetector/AccidentDetectorAdvanced.ino/AccidentDetectorAdvanced.ino.ino
+++ src/AccidentDetector/AccidentDetectorAdvanced.ino/AccidentDetectorAdvanced.ino.ino
@@ -8,10 +8,10 @@
 float xold, yold, zold;

 //3. Pinns
-#define triggerInput_front 7
-#define echoOutput_front 6
-#define triggerInput_back 4
-#define echoOutput_back 3
+#define triggerInput_front 4
+#define echoOutput_front 3
+#define triggerInput_back 7
+#define echoOutput_back 6
 #define critical_distance 20
 #define critical_gyro_up 1.20
 #define critical_gyro_down 0.80
@@ -34,7 +34,17 @@
   Serial.println(accidentState);
   switch (accidentState) {
     case 1:
-    Serial.println("201 - Back sensor!");
+      Serial.println("201 - Back sensor!");
+      break;
+    case 2:
+      Serial.println("202 - Front sensor!");
+      break;
+    case 3:
+      Serial.println("203 - Both sensors!");
+      break;
+    case 4:
+      Serial.println("204 - Gyro reacted!");
+      break;
     case 5:
       Serial.println("205 - BACK HIT!");
       Serial.println("205 - BACK HIT!");


Update gsm example

Update gsm example

--- examples/Boards_GSM/SIM800_SIM900/SIM800_SIM900.ino
+++ examples/Boards_GSM/SIM800_SIM900/SIM800_SIM900.ino
@@ -33,18 +33,23 @@
 // If you want override this value, uncomment and set this option:
 //#define BLYNK_HEARTBEAT 30

+// Select your modem:
+#define TINY_GSM_MODEM_SIM800
+//#define TINY_GSM_MODEM_SIM900
+//#define TINY_GSM_MODEM_M590
+
 #include <TinyGsmClient.h>
 #include <BlynkSimpleSIM800.h>

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

 // Your GPRS credentials
 // Leave empty, if missing user or pass
-char apn[]  = "YourAPN";
-char user[] = "";
-char pass[] = "";
+const char apn[]  = "YourAPN";
+const char user[] = "";
+const char pass[] = "";

 // Hardware Serial on Mega, Leonardo, Micro
 #define SerialAT Serial1
@@ -67,6 +72,7 @@

   // Restart takes quite some time
   // To skip it, call init() instead of restart()
+  Serial.println("Initializing modem...");
   modem.restart();

   // Unlock your SIM card with a PIN


Use SPI library.

Use SPI library.

--- build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
+++ build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
@@ -43,6 +43,7 @@
 // - The SPI functions herein were developed for the AVR910_ARD programmer
 // - More information at http://code.google.com/p/mega-isp

+#include "SPI.h"
 #include "pins_arduino.h"
 #define RESET     SS

@@ -67,12 +68,17 @@

 void setup() {
   Serial.begin(9600);
+  SPI.setDataMode(0);
+  SPI.setBitOrder(MSBFIRST);
+  // Clock Div can be 2,4,8,16,32,64, or 128
+  SPI.setClockDivider(SPI_CLOCK_DIV128);
   pinMode(LED_PMODE, OUTPUT);
   pulse(LED_PMODE, 2);
   pinMode(LED_ERR, OUTPUT);
   pulse(LED_ERR, 2);
   pinMode(LED_HB, OUTPUT);
   pulse(LED_HB, 2);
+
 }

 int error = 0;
@@ -96,7 +102,7 @@
   uint16_t pagesize;
   uint16_t eepromsize;
   uint32_t flashsize;
-}
+}
 parameter;

 parameter param;
@@ -164,33 +170,13 @@
   }
 }

-void spi_init() {
-  uint8_t x;
-  SPCR = 0x53;
-  x = SPSR;
-  x = SPDR;
-}
-
-void spi_wait() {
-  do {
-  } while (!(SPSR & (1 << SPIF)));
-}
-
-uint8_t spi_send(uint8_t b) {
-  uint8_t reply;
-  SPDR = b;
-  spi_wait();
-  reply = SPDR;
-  return reply;
-}
-
 uint8_t spi_transaction(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
   uint8_t n;
-  spi_send(a);
-  n = spi_send(b);
+  SPI.transfer(a);
+  n = SPI.transfer(b);
   //if (n != a) error = -1;
-  n = spi_send(c);
-  return spi_send(d);
+  n = SPI.transfer(c);
+  return SPI.transfer(d);
 }

 void empty_reply() {
@@ -259,25 +245,19 @@
 }

 void start_pmode() {
-  spi_init();
-  // following delays may not work on all targets...
+  SPI.begin();
+  digitalWrite(RESET, HIGH);
   pinMode(RESET, OUTPUT);
-  digitalWrite(RESET, HIGH);
-  pinMode(SCK, OUTPUT);
   digitalWrite(SCK, LOW);
-  delay(50);
+  delay(20);
   digitalWrite(RESET, LOW);
-  delay(50);
-  pinMode(MISO, INPUT);
-  pinMode(MOSI, OUTPUT);
   spi_transaction(0xAC, 0x53, 0x00, 0x00);
   pmode = 1;
 }

 void end_pmode() {
-  pinMode(MISO, INPUT);
-  pinMode(MOSI, INPUT);
-  pinMode(SCK, INPUT);
+  SPI.end();
+  digitalWrite(RESET, HIGH);
   pinMode(RESET, INPUT);
   pmode = 0;
 }


Cosmetic fixes, formatting.

Cosmetic fixes, formatting.

A few fixes to make:
pending, added time output for better diagnostics: Double-check 5 minute solar panel timeout, seems not to last 5 minutes?
--done (hopefully). Fix formatting for negative numbers (000-77)
--done. Serial output of what time solar is disabled/enabled
--done. Multiply both INA readings by 2 (350mA -> 700mA)
--done. reset count of ina readings to zero each minute. Note it gets about 4,200 readings per minute.
--done. Remove ethernet's client.read() --> serial because it makes copy/paste difficult.
--done. Serial output on 35s wait for enableEthernet();
--done. remove wd= from wind direction ADC

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

  */
-const String wxVersion = "L14cB1"; // jjj
+const String wxVersion = "L16eB1"; // jjj
 const String wxOwner = "-DJ-";
 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 L13gB1 2017/09/26 INA219a smoothing) starting at ms ";
+const bool enableEthDump2Serial = false;  //Set to false to suppress spitting Ethernet output to serial. Sometimes unprintable characters mess up the terminal.
+const String startupMessage = "UM Weather Station (ver L16eB1 2017/09/27 more smoothing, text fixing) starting at ms ";
 //#define FOURMINUTEDAY              // Switch from day to night every four minutes for DEBUG

@@ -209,18 +210,25 @@
 //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;
+const int ina219a_MMAcount = 2048;
+
+float ina219b_volts;
+float ina219b_current;
+float ina219b_MMAcurrentSum;
+float ina219b_MMAcurrentAvg;
+float ina219b_MMAvoltSum;
+float ina219b_MMAvoltAvg;
+const int ina219b_MMAcount = 128;
+
 float shuntvoltage = 0;
 float busvoltage = 0;
 float current_mA = 0;
 float loadvoltage = 0;
+float ina219_MMAtemp;
 unsigned int ina219a_MMAmillis = 0;
 unsigned int ina219a_MMAloops = 0;

@@ -325,7 +333,17 @@

   // 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++) {
+  Serial.println();
+  Serial.print("Ubiquiti startup delay, 25 seconds:    ");
+  for (int i=25; i>0; i--) {
+
+    // Count down the seconds on Serial. Character 8 is the backspace.
+    Serial.write(8);
+    if (i > 9) {
+      Serial.write(8);
+    }
+    Serial.print(i);
+
     wdt_reset();
     delay(1000);
   }
@@ -335,12 +353,22 @@

   // 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++) {
+  Serial.println();
+  Serial.print("Ethernet startup delay, 5 more seconds:    ");
+  for (int i=5; i>0; i--) {
+
+    // Count down the seconds on Serial. Character 8 is the backspace.
+    Serial.write(8);
+    if (i > 9) {
+      Serial.write(8);
+    }
+    Serial.print(i);
+
     wdt_reset();
     delay(1000);
   }

-  Ethernet.begin(mac, ip, dnsServer, gateway, subnet); // jjj Eth must be initialized after each power up
+  Ethernet.begin(mac, ip, dnsServer, gateway, subnet); // Eth must be initialized after each power up

 }

@@ -701,7 +729,7 @@
     // give the Ethernet shield a second to initialize:
     delay(1000);
     Serial.print(millis());
-    Serial.print(F("ms: Started Ethernet (watchdog enabled). Local IP is "));
+    Serial.print(F("ms: Started Ethernet (and watchdog enabled). Local IP is "));
     Serial.println(Ethernet.localIP());

     // Request the date & time from RTC or NTP
@@ -710,9 +738,9 @@
       // If we have a working RTC, let's just use it. Every few minutes we'll check for NTP too.
       Serial.println(F("RTC selected as time source."));
       setSyncProvider(RTC.get);
-      setSyncInterval(300);           // Update system time with the RTC because it actually slews pretty fast; 4 second an hour is typical.
+      setSyncInterval(300);           // Update system time often because it actually slews pretty fast; 4 second an hour is typical.
     } else {
-      // 0 Means the RTC didn't work, set NTP as the sync provider, with an agressive Sync Interval because we depend on it.
+      // 0 Means the RTC didn't work, set NTP as the sync provider, with an initially agressive Sync Interval because we depend on it.
       Serial.print(F("No RTC? Sending NTP packet at "));
       Serial.println(millis());
       setSyncProvider(getNtpTime);    // Use the time library's setSyncProvider to check periodically for time
@@ -965,10 +993,12 @@
       *  B A T T E R Y   P R O T E C T I O N
       * * * * * * * * * * * * * * * * * * * * * * * * */

-      if (ina219b_current > 350) {
+      if (ina219b_current > 700) {

         // Charging too fast. Poor man's slowdown: turn off the solar panel for a bit. 8-o
-        Serial.println(F("Pausing Solar Panels because charge rate was > 350ma (==700ma because INA reports half real value)"));
+        Serial.println();
+        Serial.print(hour()); Serial.print(":"); Serial.print(minute()); Serial.print(":"); Serial.print(second());
+        Serial.println(F(": Pausing Solar Panels because charge rate was > 350ma (==700ma because INA reports half real value)"));
         pauseSolar = true;
         pauseSolarStartTime = now();
         disableSolar();
@@ -979,7 +1009,9 @@
         if (pauseSolar) {
           if ( (pauseSolarStartTime + pauseSolarMinutes * 60) > now() ) {
             //It's been enough minutes with the Panels off. Turn them back on.
-            Serial.println(F("RESUMING Solar Panels: it's been long enough with them turned off"));
+            Serial.println();
+            Serial.print(hour()); Serial.print(":"); Serial.print(minute()); Serial.print(":"); Serial.print(second());
+            Serial.println(F(": RESUMING Solar Panels, it's been long enough with them turned off"));
             pauseSolar = false;
             enableSolar();
           }
@@ -999,10 +1031,10 @@
       if (second() == 0) {
     //if (true) {  // for STRESS TEST we go once a second.
         // Once a minute, on zero seconds (by NTP/RTC time, not since boot time), upload the weather.
-        ShowSockStatus();   //DEBUG: print IP Socket status on serial.
-        //printWeather();     //DEBUG: print a slightly different weather string on serial.
+        //printWeather();      //DEBUG: print a slightly different weather string on serial.
         Serial.println(getWeatherString());
         uploadWeather();
+        ina219a_MMAloops = 0;  //Reset to zero after upload (even if not successful)
       }
       if ((second() == 25) and (minutes == 55)) {
         //refresh DHCP once an hour if we're using it. NTP/RTC second() so we don't do it same time as an upload. Runtime minutes so it's after an hour of running.
@@ -1017,7 +1049,7 @@
     **/
     //if (justBooted) Serial.println(getWeatherString());               // print every second for the first 15 secs after booting.
     //else if (seconds % 10 == 0) Serial.println(getWeatherString());   // then every 10 seconds
-    if (justBooted and seconds % 3 == 0) printWeather();                // print every second for the first 15 secs after booting.
+    if (justBooted and seconds % 3 == 0) Serial.println(getWeatherString());                // print every second for the first 15 secs after booting.
     else if (0) { // print the seconds on serial
       Serial.write(8);
       if (second() > 9) {
@@ -1041,7 +1073,7 @@
       if (client.available()) {
         ethLastMillis = millis();
         char c = client.read();
-        Serial.print(c);
+        if (enableEthDump2Serial) Serial.print(c);
       } else {
         break;
       }
@@ -1072,25 +1104,46 @@
   } //END if(!ethStopped)

-  //INA 219 averaging. Shoot for maybe 80-120 readings a second?
+  //INA 219 averaging. Gets about 60-70 readings a second at time of writing.
   if (ina219a_MMAmillis + 8 < millis()) {

     shuntvoltage = ina219a.getShuntVoltage_mV();
     busvoltage = ina219a.getBusVoltage_V();
-    ina219a_MMAtemp = busvoltage + (shuntvoltage / 1000);
+    ina219_MMAtemp = busvoltage + (shuntvoltage / 1000.0);

     ina219a_MMAvoltSum -= ina219a_MMAvoltAvg;
-    ina219a_MMAvoltSum += ina219a_MMAtemp;
+    ina219a_MMAvoltSum += ina219_MMAtemp;
     ina219a_MMAvoltAvg  = ina219a_MMAvoltSum / ina219a_MMAcount;
     ina219a_volts = ina219a_MMAvoltAvg;

-    ina219a_MMAtemp = ina219a.getCurrent_mA();
+    ina219_MMAtemp = ina219a.getCurrent_mA();
     ina219a_MMAcurrentSum -= ina219a_MMAcurrentAvg;
-    ina219a_MMAcurrentSum += ina219a_MMAtemp;
+    ina219a_MMAcurrentSum += ina219_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_current = ina219a_MMAcurrentAvg * -2.0; // * -2.0 because a resistor was added and this one's wired backwards for convenience.

     ina219a_MMAloops++;
+
+    if (ina219a_MMAloops % 10 == 0) {
+      //Smooth the battery's INA 1/10th as often as the Panel, since the battery doesn't get as buffeted by PWM
+
+      shuntvoltage = ina219b.getShuntVoltage_mV();
+      busvoltage = ina219b.getBusVoltage_V();
+      ina219_MMAtemp = busvoltage + (shuntvoltage / 1000.0);
+
+      ina219b_MMAvoltSum -= ina219b_MMAvoltAvg;
+      ina219b_MMAvoltSum += ina219_MMAtemp;
+      ina219b_MMAvoltAvg  = ina219b_MMAvoltSum / ina219b_MMAcount;
+      ina219b_volts = ina219b_MMAvoltAvg;
+
+      ina219_MMAtemp = ina219b.getCurrent_mA();
+      ina219b_MMAcurrentSum -= ina219b_MMAcurrentAvg;
+      ina219b_MMAcurrentSum += ina219_MMAtemp;
+      ina219b_MMAcurrentAvg  = ina219b_MMAcurrentSum / ina219b_MMAcount;
+      ina219b_current = ina219b_MMAcurrentAvg * 2.0; // double because a resistor was added
+
+
+    }

   }

@@ -1113,8 +1166,8 @@
   }
   sunriseDay = day();
   Serial.println();
-  Serial.print("Sunrise today is  "); Serial.print(sunrise); Serial.println(" minutes after midnight.");
-  Serial.print("Sunset  today is " ); Serial.print(sunset);  Serial.println(" minutes after midnight.");
+  Serial.print("Sunrise today is at  "); Serial.print(sunrise / 60); Serial.print(":"); Serial.println(sunrise % 60);
+  Serial.print("Sunset  today is at " ); Serial.print(sunset  / 60); Serial.print(":"); Serial.println(sunset  % 60);
   Serial.print("  Took "); Serial.print(micros() - usTemp);  Serial.println("us to calculate.");
   Serial.println();
 }
@@ -1140,15 +1193,17 @@
 // Turns on solar panels, allows battery charging and solar powering of peripherals.
 // NOTE if this is disabled, everything runs on battery power, even in daytime.
 void enableSolar() {
-  Serial.println("Solar panel ENABLED via enableSolar();");
+  Serial.print(hour()); Serial.print(":"); Serial.print(minute()); Serial.print(":"); Serial.print(second());
+  Serial.println(" - Solar panel ENABLED via enableSolar();");
   pinMode(PIN_SOLAR_DISABLE, INPUT);                 // prepares Solar Panel control pin
-  digitalWrite(PIN_SOLAR_DISABLE, SOLAR_ENABLED);     // turns Solar Panel on
+  //digitalWrite(PIN_SOLAR_DISABLE, SOLAR_ENABLED);     // turns Solar Panel on

 }

 // Turns off solar panels. Use this carefully, it makes everything battery powered.
 void disableSolar() {
-  Serial.println("Solar panel DISABLED via disableSolar();");
+  Serial.print(hour()); Serial.print(":"); Serial.print(minute()); Serial.print(":"); Serial.print(second());
+  Serial.println(" - Solar panel DISABLED via disableSolar();");
   pinMode(PIN_SOLAR_DISABLE, OUTPUT);                  // prepares Solar Panel control pin
   digitalWrite(PIN_SOLAR_DISABLE, SOLAR_DISABLED);     // turns Solar Panel off

@@ -1249,37 +1304,6 @@
       pressure = myPressure.readPressure();
       if (oldPressure == 0) oldPressure = pressure; //First time, let's not have a "delta" of the current pressure.
     }
-
-    //Get voltage and current from INA219 sensors
-    float current_mA = 0;
-    float avg_plus = 0;
-    float avg_minus = 0;
-
-    // INA219 AAAAAA
-    // 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();
-    loadvoltage = busvoltage + (shuntvoltage / 1000);
-
-    avg_plus  = loadvoltage / VOLTAGE_AVG_SIZE;
-    avg_minus = ina219b_volts / VOLTAGE_AVG_SIZE;
-    ina219b_volts = ina219b_volts - avg_minus + avg_plus;
-
-    avg_plus = current_mA / VOLTAGE_AVG_SIZE;
-    avg_minus = ina219b_current / VOLTAGE_AVG_SIZE;
-    ina219b_current = ina219b_current -avg_minus + avg_plus;
-
-
-    /* //Diagnostic printout for INA219 sensor
-    Serial.print("Bus: "); Serial.print(busvoltage); Serial.print(" V, ");
-    Serial.print("Shunt: "); Serial.print(shuntvoltage); Serial.print(" mV, ");
-    Serial.print("Load: "); Serial.print(loadvoltage); Serial.print(" V, ");
-    Serial.print("Current: "); Serial.print(current_mA); Serial.print(" mA, ");
-    Serial.print("Power: "); Serial.print(current_mA / 1000 * loadvoltage); Serial.println(" W"); */
-

     //Calc dewptf

@@ -1586,10 +1610,13 @@
   logOneLine(ina219a_MMAloops);
   byte uploadStatus = 90; //90 = haven't tried stopping the client yet.

+  ShowSockStatus();   //DEBUG: print IP Socket status on serial.
+
   // Preemptively close any open connections, to keep sockets available.
   client.stop();
   while (client.available()) { //read return from socket
-    Serial.write(client.read());
+    char c = client.read();
+    if (enableEthDump2Serial) Serial.write(c);
   }

   uploadStatus = 100; //100 = stopped client, but haven't tried connecting.
@@ -1668,13 +1695,13 @@

   // 3: Wind speed, mph, 1 minute average
   weatherString += String(charComma);
-  if (windSpeedAvg < 9.5) weatherString += String('0');
-  weatherString += String(windSpeedAvg, 2);
+  if (windSpeedAvg < 9.95) weatherString += String('0');
+  weatherString += String(windSpeedAvg, 1);

   // 4: wind speed, mph, 5 minute max (gust)
   weatherString += String(charComma);
   if (windgustmph_5m < 9.5) weatherString += String('0');
-  weatherString += String(windgustmph_5m, 1);
+  weatherString += String(windgustmph_5m, 0);

   // 5: wind direction, 1 minute average
   weatherString += String(charComma);
@@ -1734,11 +1761,6 @@
 //    weatherString += String(0.0, 2);
   weatherString += String(wxVersion);

-  // 11: wind speed, mph, instant (instead of 24h rain)
-  //weatherString += String(charComma);
-  //if (windspeedmph < 10) weatherString += String('0');
-  //weatherString += String(windspeedmph, 1);
-
   // 12: temperature in the enclosure or 2nd sensor if we get one. In Celcius for Jimmy.
   weatherString += String(charComma);
   if (tempc) {
@@ -1749,7 +1771,7 @@

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

   // 14 (was 12c): humidity, %, inside BB bme280b, instant (for checking dewpoint eventually)
   weatherString += String(charComma);
@@ -1757,10 +1779,19 @@

   // 15: Current on ina219 sensor A (Solar Panel / CC @ 12v maybe?)
   weatherString += String(charComma);
-  if (ina219a_current < 1000) weatherString += "0";
-  if (ina219a_current < 100)  weatherString += "0";
-  if (ina219a_current < 10)   weatherString += "0";
-  weatherString += String(ina219a_current, 0);
+  if (ina219a_current < 0) {
+    //negative numbers. There's a better way using dtostrf(), but that pads with spaces not zeros right? Can't have spaces.
+    weatherString += String("-");
+    if (ina219a_current > -10)  weatherString += "0";
+    if (ina219a_current > -100) weatherString += "0";
+    weatherString += String(ina219a_current * -1, 0);
+  } else {
+    //positive numbers
+    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");

   // 16: Voltage on ina219 sensor A (Solar Panel @ 12v maybe?)
@@ -1777,10 +1808,19 @@

   // 17: Current on ina219 sensor B (after buck to 5v maybe?)
   weatherString += String(charComma);
-  if (ina219b_current < 1000) weatherString += "0";
-  if (ina219b_current < 100)  weatherString += "0";
-  if (ina219b_current < 10)   weatherString += "0";
-  weatherString += String(ina219b_current, 0);
+  if (ina219b_current < 0) {
+    //negative numbers. There's a better way using dtostrf(), but that pads with spaces not zeros right? Can't have spaces.
+    weatherString += String("-");
+    if (ina219b_current > -10)  weatherString += "0";
+    if (ina219b_current > -100) weatherString += "0";
+    weatherString += String(ina219b_current * -1, 0);
+  } else {
+    //positive numbers
+    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");

   // 18: Voltage on ina219 sensor A (after buck to 5v maybe?)
@@ -1806,7 +1846,7 @@
   //weatherString += String(days);
   //weatherString += String(".");
   //if (hours < 10) weatherString += String('0');
-  weatherString += String(hours);
+  weatherString += String(hours + (days * 24));
   weatherString += String(":");
   if (minutes < 10) weatherString += String('0');
   weatherString += String(minutes);
@@ -1828,7 +1868,6 @@
   // 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=");
     weatherString += String(winddirRaw);
   }
   if (true) {


horloge_cycles_ultradiens.ino optimisation mémoire

--- files/horloge_cycles_ultradiens/horloge_cycles_ultradiens.ino
+++ files/horloge_cycles_ultradiens/horloge_cycles_ultradiens.ino
@@ -290,11 +290,11 @@
   display.setTextColor( WHITE );
   display.setTextSize( 2 );
   display.setCursor( 25, 0 );
-  display.print( "HORLOGE" );
+  display.print( F( "HORLOGE" ) );
   display.setCursor( 20, 19 );
-  display.print( "A CYCLES" );
+  display.print( F( "A CYCLES" ) );
   display.setCursor( 5, 40 );
-  display.print( "ULTRADIENS" );
+  display.print( F( "ULTRADIENS" ) );
   display.display();

   // Initialisation du carillon
@@ -381,7 +381,7 @@

   // Préparation de l’affichage du séparateur
   display.setCursor( 76, 0 );
-  display.print( ":" );
+  display.print( F( ":" ) );

   // Préparation de l’affichage des minutes
   display.setCursor( 86, 0 );
@@ -414,7 +414,7 @@
     display.print( cycleAtt, 0 );
     display.setCursor( display.getCursorX() + 3, 21 );
   #endif
-  display.print( char( 37 ) ); // signe %
+  display.print( F( "%" ) );

   // Préparation de l’affichage de la courbe du cycle
   prepareCourbeCycle( frac16eJourPx );


updated imu mag calibration

updated imu mag calibration

--- sandbox/Razor_AHRS/Razor_AHRS.ino
+++ sandbox/Razor_AHRS/Razor_AHRS.ino
@@ -188,8 +188,8 @@
 // Magnetometer (extended calibration mode)
 // uses extended magnetometer calibration (compensates hard & soft iron errors)
 #define CALIBRATION__MAGN_USE_EXTENDED true
-const float magn_ellipsoid_center[3] = {-2.08620, -14.2146, -274.974};
-const float magn_ellipsoid_transform[3][3] = {{0.844458, 0.0428071, 0.0123553}, {0.0428071, 0.936638, 0.0203989}, {0.0123553, 0.0203989, 0.988038}};
+const float magn_ellipsoid_center[3] = {130.747, -60.8511, -58.9468};
+const float magn_ellipsoid_transform[3][3] = {{0.922284, 0.0152275, 0.00369525}, {0.0152275, 0.952080, -0.0175593}, {0.00369525, -0.0175593, 0.993517}};

 // Gyroscope
 // "gyro x,y,z (current/average) = .../OFFSET_X  .../OFFSET_Y  .../OFFSET_Z


Changed I2C address for Port motor shield

Set Port BGA motor shield I2C reference back to 0x60, the default.  Prior had another address, as the shield in use had a modified address.

--- Arduino/Ard_PortBGAs_r18/Ard_PortBGAs_r18.ino
+++ Arduino/Ard_PortBGAs_r18/Ard_PortBGAs_r18.ino
@@ -173,7 +173,7 @@

 // 0x70 is the "all call" which means all motor shields connected to this Ardwill be commanded, regardless of their I2C ID.  Works as long as it's not more than one motor shield for each Arduino.
 // (If we ever stack multiple motor shields, will have to address individually)
-Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x78);
+Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x60);
 // Select which 'port' M1, M2, M3 or M4. In this case, M1,2,4
 Adafruit_DCMotor *myMotorB4A = AFMS.getMotor(1);
 Adafruit_DCMotor *myMotorB2A = AFMS.getMotor(2);