CamelCase all functions and globals

CamelCase all functions and globals

Signed-off-by: Mark Knoop <f1b5a91d4d6ad523f2610114591c007e75d15084@markknoop.com>

--- src/sketch.ino
+++ src/sketch.ino
@@ -69,8 +69,8 @@
 float startPitch;
 float midPitch;
 float endPitch;
-boolean dir;
-boolean recentre;
+boolean Dir;
+boolean reCentre;
 boolean newData = false;
 volatile boolean alarmState = false;

@@ -110,8 +110,8 @@
     startPitch = 72;
     midPitch = 48;
     endPitch = 60;
-    dir = true;
-    recentre = true;
+    Dir = true;
+    reCentre = true;
 }

 void sendReady() {
@@ -129,7 +129,7 @@
     return (pitch / 2.0) + 36;
 }

-void onestep(unsigned long pulseTime) {
+void oneStep(unsigned long pulseTime) {
     digitalWrite(stepPin, HIGH);
     delayMicroseconds(pulseWidth);
     digitalWrite(stepPin, LOW);
@@ -142,7 +142,7 @@

 void findSensor(int pulse) {
     while(digitalRead(sensorPin) == LOW) {
-        onestep(pulse);
+        oneStep(pulse);
         if (alarmState) return;
     }
 }
@@ -155,15 +155,15 @@
     digitalWrite(dirPin, dir);
     delayMicroseconds(pulseWidth);
     for (int i=0; i<accelSteps; i++) {
-        onestep(map(i, 0, accelSteps, startstoppulse, pulse));
+        oneStep(map(i, 0, accelSteps, startstoppulse, pulse));
         if (alarmState) return;
     }
     for (int i=0; i<fullspeedsteps; i++) {
-        onestep(pulse);
+        oneStep(pulse);
         if (alarmState) return;
     }
     for (int i=0; i<accelSteps; i++) {
-        onestep(map(i, 0, accelSteps, pulse, startstoppulse));
+        oneStep(map(i, 0, accelSteps, pulse, startstoppulse));
         if (i>(accelSteps - decelLook) && digitalRead(sensorPin)) break;
         if (alarmState) return;
     }
@@ -177,28 +177,28 @@
     digitalWrite(dirPin, dir);
     delayMicroseconds(pulseWidth);
     for (int i=0; i<accelSteps; i++) {
-        onestep(map(i, 0, accelSteps, max(maxPulse, startpulse), startpulse));
+        oneStep(map(i, 0, accelSteps, max(maxPulse, startpulse), startpulse));
         if (alarmState) return;
     }
     for (int i=0; i<glisssteps; i++) {
-        onestep(map(i, 0, glisssteps, startpulse, endpulse));
+        oneStep(map(i, 0, glisssteps, startpulse, endpulse));
         if (alarmState) return;
     }
     for (int i=0; i<accelSteps; i++) {
-        onestep(map(i, 0, accelSteps, endpulse, max(maxPulse, endpulse)));
+        oneStep(map(i, 0, accelSteps, endpulse, max(maxPulse, endpulse)));
         if (i>(accelSteps - decelLook) && digitalRead(sensorPin)) break;
         if (alarmState) return;
     }
     findSensor(max(maxPulse, endpulse));
 }

-int timedturn(int halfturns, unsigned long duration, bool dir) {
+int timedTurn(int halfturns, unsigned long duration, bool dir) {
     int fullspeedsteps = (halfTurnSteps * halfturns) - (accelSteps * 2);
     unsigned long pulse = ((duration * 1000L) - (maxPulse * accelSteps)) /
                           (accelSteps + fullspeedsteps);
-    int localAccelSteps = accelSteps;
+    int accelsteps = accelSteps;
     if (pulse > maxPulse) {
-        localAccelSteps = 0;
+        accelsteps = 0;
         fullspeedsteps = halfTurnSteps * halfturns;
         pulse = (duration * 1000L) / fullspeedsteps;
     } else {
@@ -206,24 +206,24 @@
     }
     digitalWrite(dirPin, dir);
     delayMicroseconds(pulseWidth);
-    for (int i=0; i<localAccelSteps; i++) {
-        onestep(map(i, 0, localAccelSteps, maxPulse, pulse));
+    for (int i=0; i<accelsteps; i++) {
+        oneStep(map(i, 0, accelsteps, maxPulse, pulse));
         if (alarmState) return 0;
     }
     for (int i=0; i<fullspeedsteps; i++) {
-        onestep(pulse);
-        if (alarmState) return 0;
-    }
-    for (int i=0; i<localAccelSteps; i++) {
-        onestep(map(i, 0, localAccelSteps, pulse, maxPulse));
-        if (i>(localAccelSteps - decelLook) && digitalRead(sensorPin)) break;
+        oneStep(pulse);
+        if (alarmState) return 0;
+    }
+    for (int i=0; i<accelsteps; i++) {
+        oneStep(map(i, 0, accelsteps, pulse, maxPulse));
+        if (i>(accelsteps - decelLook) && digitalRead(sensorPin)) break;
         if (alarmState) return 0;
     }
     findSensor(maxPulse);
     return pulse;
 }

-long _durationgliss(unsigned long duration, float startpitch, float endpitch,
+long _durationGliss(unsigned long duration, float startpitch, float endpitch,
         int sustainstart, int sustainend, bool dir, bool recentre) {
     int startsustainpulse = pitchToPulse(startpitch + glissAdd - 1);
     int startpulse = pitchToPulse(startpitch + glissAdd);
@@ -231,54 +231,54 @@
     int endsustainpulse = pitchToPulse(endpitch + glissAdd - 1);
     int accelsteps = map(startpitch, 48, 72, accelSteps-10, accelSteps+10);
     int decelsteps = map(endpitch, 48, 72, accelSteps-10, accelSteps+10);
-    unsigned long glissTime = ((duration - sustainstart) * 1000L) -
+    unsigned long glisstime = ((duration - sustainstart) * 1000L) -
         (((max(maxPulse, startpulse) + startpulse) * (accelsteps / 2)) +
          ((endpulse + max(maxPulse, endpulse)) * (decelsteps / 2)));
-    glissTime = max(0, (glissTime * durationGlissMul) + (durationGlissAdd * 1000L));
-    int glisssteps = glissTime / ((startpulse + endpulse) / 2);
+    glisstime = max(0, (glisstime * durationGlissMul) + (durationGlissAdd * 1000L));
+    int glisssteps = glisstime / ((startpulse + endpulse) / 2);
     int sustainstartsteps = (sustainstart * 1000L) / startpulse;
     int sustainendsteps = (sustainend * 1000L) / endpulse;
     digitalWrite(dirPin, dir);
     delayMicroseconds(pulseWidth);
     // accelerando
     for (int i=0; i<accelsteps; i++) {
-        onestep(map(i, 0, accelsteps, max(maxPulse, startsustainpulse), startsustainpulse));
+        oneStep(map(i, 0, accelsteps, max(maxPulse, startsustainpulse), startsustainpulse));
         if (alarmState) return 0;
     }
     // sustain start
     for (int i=0; i<sustainstartsteps; i++) {
-        onestep(startsustainpulse);
+        oneStep(startsustainpulse);
         if (alarmState) return 0;
     }
     // glissando
     for (int i=0; i<glisssteps; i++) {
-        onestep(map(i, 0, glisssteps, startpulse, endpulse));
+        oneStep(map(i, 0, glisssteps, startpulse, endpulse));
         if (alarmState) return 0;
     }
     // sustain end
     for (int i=0; i<sustainendsteps; i++) {
-        onestep(endsustainpulse);
+        oneStep(endsustainpulse);
         if (alarmState) return 0;
     }
     // decelerando
     for (int i=0; i<decelsteps; i++) {
-        onestep(map(i, 0, decelsteps, endsustainpulse, max(maxPulse, endsustainpulse)));
+        oneStep(map(i, 0, decelsteps, endsustainpulse, max(maxPulse, endsustainpulse)));
         if (alarmState) return 0;
     }
     if (recentre) findSensor(max(maxPulse, endsustainpulse));
-    return glissTime;
-}
-
-void durationturn(unsigned long duration, float pitch, bool dir, bool recentre) {
-    _durationgliss(duration, pitch, pitch, 0, 0, dir, recentre);
-}
-
-long durationgliss(unsigned long duration, float startpitch, float endpitch,
+    return glisstime;
+}
+
+void durationTurn(unsigned long duration, float pitch, bool dir, bool recentre) {
+    _durationGliss(duration, pitch, pitch, 0, 0, dir, recentre);
+}
+
+long durationGliss(unsigned long duration, float startpitch, float endpitch,
         bool dir, bool recentre, int sustain) {
-    return _durationgliss(duration, startpitch, endpitch, sustain, sustain, dir, recentre);
-}
-
-long doublegliss(int durationone, int durationtwo,
+    return _durationGliss(duration, startpitch, endpitch, sustain, sustain, dir, recentre);
+}
+
+long doubleGliss(int durationone, int durationtwo,
         float startpitch, float midpitch, float endpitch,
         int sustainstart, int sustainmid, int sustainend,
         bool dir, bool recentre) {
@@ -305,37 +305,37 @@
     delayMicroseconds(pulseWidth);
     // accelerando
     for (int i=0; i<accelsteps; i++) {
-        onestep(map(i, 0, accelsteps, max(maxPulse, startsustainpulse), startsustainpulse));
+        oneStep(map(i, 0, accelsteps, max(maxPulse, startsustainpulse), startsustainpulse));
         if (alarmState) return 0;
     }
     // sustain start
     for (int i=0; i<sustainstartsteps; i++) {
-        onestep(startsustainpulse);
+        oneStep(startsustainpulse);
         if (alarmState) return 0;
     }
     // glissando one
     for (int i=0; i<glissonesteps; i++) {
-        onestep(map(i, 0, glissonesteps, startpulse, midpulse));
+        oneStep(map(i, 0, glissonesteps, startpulse, midpulse));
         if (alarmState) return 0;
     }
     // sustain mid
     for (int i=0; i<sustainmidsteps; i++) {
-        onestep(midsustainpulse);
+        oneStep(midsustainpulse);
         if (alarmState) return 0;
     }
     // glissando two
     for (int i=0; i<glisstwosteps; i++) {
-        onestep(map(i, 0, glisstwosteps, midpulse, endpulse));
+        oneStep(map(i, 0, glisstwosteps, midpulse, endpulse));
         if (alarmState) return 0;
     }
     // sustain end
     for (int i=0; i<sustainendsteps; i++) {
-        onestep(endsustainpulse);
+        oneStep(endsustainpulse);
         if (alarmState) return 0;
     }
     // decelerando
     for (int i=0; i<decelsteps; i++) {
-        onestep(map(i, 0, decelsteps, endsustainpulse, max(maxPulse, endsustainpulse)));
+        oneStep(map(i, 0, decelsteps, endsustainpulse, max(maxPulse, endsustainpulse)));
         if (alarmState) return 0;
     }
     if (recentre) findSensor(max(maxPulse, endsustainpulse));
@@ -350,10 +350,10 @@
         Serial.print(" pitch ");
         Serial.print(startPitch, DEC);
         Serial.print(" direction ");
-        Serial.print(dir, DEC);
+        Serial.print(Dir, DEC);
         Serial.print(" time ");
         unsigned long starttime = millis();
-        turn(halfTurns, startPitch, dir);
+        turn(halfTurns, startPitch, Dir);
         Serial.println(millis() - starttime);
     } else if (style == 1) {
         // gliss
@@ -364,10 +364,10 @@
         Serial.print(" endpitch ");
         Serial.print(endPitch, DEC);
         Serial.print(" direction ");
-        Serial.print(dir, DEC);
+        Serial.print(Dir, DEC);
         Serial.print(" time ");
         unsigned long starttime = millis();
-        gliss(halfTurns, startPitch, endPitch, dir);
+        gliss(halfTurns, startPitch, endPitch, Dir);
         Serial.println(millis() - starttime);
     } else if (style == 2) {
         // timed turn
@@ -376,10 +376,10 @@
         Serial.print(" duration ");
         Serial.print(Duration, DEC);
         Serial.print(" direction ");
-        Serial.print(dir, DEC);
+        Serial.print(Dir, DEC);
         Serial.print(" time ");
         unsigned long starttime = millis();
-        int pulse = timedturn(halfTurns, Duration, dir);
+        int pulse = timedTurn(halfTurns, Duration, Dir);
         Serial.print(millis() - starttime);
         Serial.print(" pulse ");
         Serial.println(pulse, DEC);
@@ -390,12 +390,12 @@
         Serial.print(" pitch ");
         Serial.print(startPitch, DEC);
         Serial.print(" direction ");
-        Serial.print(dir, DEC);
+        Serial.print(Dir, DEC);
         Serial.print(" recentre ");
-        Serial.print(recentre, DEC);
+        Serial.print(reCentre, DEC);
         Serial.print(" time ");
         unsigned long starttime = millis();
-        durationturn(Duration, startPitch, dir, recentre);
+        durationTurn(Duration, startPitch, Dir, reCentre);
         Serial.println(millis() - starttime);
     } else if (style == 4) {
         // duration gliss
@@ -406,13 +406,13 @@
         Serial.print(" endpitch ");
         Serial.print(endPitch, DEC);
         Serial.print(" direction ");
-        Serial.print(dir, DEC);
+        Serial.print(Dir, DEC);
         Serial.print(" recentre ");
-        Serial.print(recentre, DEC);
+        Serial.print(reCentre, DEC);
         Serial.print(" time ");
         unsigned long starttime = millis();
-        long calcdur = durationgliss(Duration, startPitch, endPitch,
-                dir, recentre, sustainDuration);
+        long calcdur = durationGliss(Duration, startPitch, endPitch,
+                Dir, reCentre, sustainDuration);
         Serial.print(millis() - starttime);
         Serial.print(" calctime ");
         Serial.println(calcdur, DEC);
@@ -429,15 +429,15 @@
         Serial.print(" endpitch ");
         Serial.print(endPitch, DEC);
         Serial.print(" direction ");
-        Serial.print(dir, DEC);
+        Serial.print(Dir, DEC);
         Serial.print(" recentre ");
-        Serial.print(recentre, DEC);
+        Serial.print(reCentre, DEC);
         Serial.print(" time ");
         unsigned long starttime = millis();
-        long calcdur = doublegliss(midDuration, Duration,
+        long calcdur = doubleGliss(midDuration, Duration,
                 startPitch, midPitch, endPitch,
                 sustainDuration, sustainDuration, sustainDuration,
-                dir, recentre);
+                Dir, reCentre);
         Serial.print(millis() - starttime);
         Serial.print(" calctime ");
         Serial.println(calcdur, DEC);
@@ -451,27 +451,27 @@
             Serial.print(dur, DEC);
             Serial.print(" time ");
             unsigned long starttime = millis();
-            durationturn(dur, i, i % 2, false);
+            durationTurn(dur, i, i % 2, false);
             Serial.println(millis() - starttime);
             delay(500);
         }
     } else if (style == 7) {
         // arpeggio
-        durationturn(4000, 48, true, false);
+        durationTurn(4000, 48, true, false);
         delay(1500);
-        durationturn(1800, 52, true, false);
+        durationTurn(1800, 52, true, false);
         delay(1500);
-        durationturn(1800, 55, true, false);
+        durationTurn(1800, 55, true, false);
         delay(1500);
-        durationturn(4000, 60, true, false);
+        durationTurn(4000, 60, true, false);
         delay(1500);
-        durationturn(1800, 64, true, false);
+        durationTurn(1800, 64, true, false);
         delay(1500);
-        durationturn(1800, 67, true, false);
+        durationTurn(1800, 67, true, false);
         delay(1500);
-        durationturn(4000, 70, true, false);
+        durationTurn(4000, 70, true, false);
         delay(1500);
-        durationturn(4000, 72, true, false);
+        durationTurn(4000, 72, true, false);
     } else if (style == 8) {
         // show settings
         Serial.print("halfturns ");
@@ -487,19 +487,19 @@
         Serial.print(", endpitch ");
         Serial.println(endPitch, DEC);
         Serial.print("direction ");
-        Serial.print(dir, BIN);
+        Serial.print(Dir, BIN);
         Serial.print(", recentre ");
-        Serial.print(recentre, BIN);
+        Serial.print(reCentre, BIN);
         Serial.print(", sustain ");
         Serial.println(sustainDuration, DEC);
     } else {
         // show test styles
         Serial.println("203: 0xcb: turn");
         Serial.println("204: 0xcc: gliss");
-        Serial.println("205: 0xcd: timedturn");
-        Serial.println("206: 0xce: durationturn");
-        Serial.println("207: 0xcf: durationgliss");
-        Serial.println("208: 0xd0: doublegliss");
+        Serial.println("205: 0xcd: timedTurn");
+        Serial.println("206: 0xce: durationTurn");
+        Serial.println("207: 0xcf: durationGliss");
+        Serial.println("208: 0xd0: doubleGliss");
         Serial.println("209: 0xd1: scale");
         Serial.println("210: 0xd2: arpeggio");
         Serial.println("211: 0xd3: show settings");
@@ -517,24 +517,24 @@
             findSensor(maxPulse);
             sendReady();
         } else if (data == rTurn) {
-            turn(halfTurns, startPitch, dir);
+            turn(halfTurns, startPitch, Dir);
         } else if (data == rGliss) {
-            gliss(halfTurns, startPitch, endPitch, dir);
+            gliss(halfTurns, startPitch, endPitch, Dir);
         } else if (data == rTimedTurn) {
-            timedturn(halfTurns, Duration, dir);
+            timedTurn(halfTurns, Duration, Dir);
         } else if (data == rDurationTurn) {
-            durationturn(Duration, startPitch, dir, recentre);
+            durationTurn(Duration, startPitch, Dir, reCentre);
         } else if (data == rDurationGliss) {
-            durationgliss(Duration, startPitch, endPitch,
-                    dir, recentre, sustainDuration);
+            durationGliss(Duration, startPitch, endPitch,
+                    Dir, reCentre, sustainDuration);
         } else if (data == rForwards) {
-            dir = true;
+            Dir = true;
         } else if (data == rBackwards) {
-            dir = false;
+            Dir = false;
         } else if (data == rRecentre) {
-            recentre = true;
+            reCentre = true;
         } else if (data == rNoRecentre) {
-            recentre = false;
+            reCentre = false;
         } else if (data == rSetDuration) {
             for (byte d=0; d<rDurlength; d++) {
                 newDuration[d] = serialIncoming[++i];
@@ -544,10 +544,10 @@
         } else if (data == rReset) {
             defaults();
         } else if (data == rDoubleGliss) {
-            doublegliss(midDuration, Duration,
+            doubleGliss(midDuration, Duration,
                     startPitch, midPitch, endPitch,
                     sustainDuration, sustainDuration, sustainDuration,
-                    dir, recentre);
+                    Dir, reCentre);
         } else if (data == rSetSustain) {
             for (byte d=0; d<rDurlength; d++) {
                 newSustainDuration[d] = serialIncoming[++i];
@@ -592,23 +592,23 @@
     if (newData) processData();
     if (alarmState) toggleEnable();
     /*
-    durationturn(2000, 60, true, false);
+    durationTurn(2000, 60, true, false);
     delay(1000);
-    durationturn(2000, 67, true, false);
+    durationTurn(2000, 67, true, false);
     delay(1000);
-    durationturn(2000, 72, true, false);
+    durationTurn(2000, 72, true, false);
     delay(1000);
-    durationturn(1500, 60, true, false);
+    durationTurn(1500, 60, true, false);
     delay(500);
-    durationgliss(1500, 60, 72, true, false, 0);
+    durationGliss(1500, 60, 72, true, false, 0);
     delay(1500);
-    durationgliss(6000, 72, 55, true, false, 900);
+    durationGliss(6000, 72, 55, true, false, 900);
     delay(500);
-    durationgliss(6000, 55, 72, true, false, 900);
+    durationGliss(6000, 55, 72, true, false, 900);
     delay(500);
-    doublegliss(6000, 6000, 55, 67, 60, 500, 500, 500, true, false);
+    doubleGliss(6000, 6000, 55, 67, 60, 500, 500, 500, true, false);
     delay(500);
-    doublegliss(707, 707, 60, 72, 71, 50, 50, 50, true, false);
+    doubleGliss(707, 707, 60, 72, 71, 50, 50, 50, true, false);
     delay(1500);
     */
 }


Lower sustain pitch at end of gliss

Lower sustain pitch at end of gliss

Signed-off-by: Mark Knoop <f1b5a91d4d6ad523f2610114591c007e75d15084@markknoop.com>

--- src/sketch.ino
+++ src/sketch.ino
@@ -220,6 +220,7 @@
         bool recentre, bool accel, bool decel, int sustainstart, int sustainend) {
     int startpulse = pitchToPulse(startpitch);
     int endpulse = pitchToPulse(endpitch);
+    int endsustainpulse = pitchToPulse(endpitch - 1);
     int accelsteps = accelSteps * accel;
     int decelsteps = accelSteps * decel;
     unsigned long glissTime = ((duration - sustainstart) * 1000L) -
@@ -245,13 +246,13 @@
     }
     // sustain end
     for (int i=0; i<sustainendsteps; i++) {
-        onestep(map(i, 0, sustainendsteps, endpulse, endpulse));
+        onestep(map(i, 0, sustainendsteps, endsustainpulse, endsustainpulse));
     }
     // decelerando
     for (int i=0; i<decelsteps; i++) {
-        onestep(map(i, 0, decelsteps, endpulse, max(maxPulse, endpulse)));
-    }
-    if (recentre) findsensor(max(maxPulse, endpulse));
+        onestep(map(i, 0, decelsteps, endsustainpulse, max(maxPulse, endsustainpulse)));
+    }
+    if (recentre) findsensor(max(maxPulse, endsustainpulse));
     return glissTime;
 }


Working version before adding new debounce

Just in case :)

--- jacksclock12/jacksclock12.ino
+++ jacksclock12/jacksclock12.ino
@@ -2,7 +2,7 @@
 //
 //    Jack's 4:20 Clock
 //    Last Update: 9-7-2014
-//    Version 0.8
+//    Version 0.9
 //    Written for Arduino Uno Rev. 3
 //    Adafruit Hardware: Real Time Clock: DS1307, Neopixel (40 RGB-LED) Shield,
 //    7-Segment Display, 14-Segment Aphanumeric Display, Backlight Module
@@ -22,10 +22,11 @@
 int photoCellIn =       A1;      // Auto Dimming
 int nightLightIn =      A2;      // Backlight
 int clockLightIn =      A3;      // 7-Sebment
-int minPlusButton =     2;
-int hourPlusButton =    4;
-int reminderSwitchIn =  5;       // Switch: Reminder
-int dstLightOut =       6;       // Small LED indicating day light savings
+int minPlusButton =     2;       // Timekeeping
+int minMinusButton =    3;       // Timekeeping
+int hourPlusButton =    4;       // Timekeeping
+int hourMinusButton =   5;       // Timekeeping
+int reminderSwitchIn =  6;       // Switch: Reminder
 int uvLED =             7;       // LEDs: UV
 int neoPixel =          8;       // RGB-LED: Green
 int fourTwentyLED =     9;       // LED: Green
@@ -42,16 +43,17 @@
 int autoBrightAverage;           // Photo Cell
 long previousMillis;             // Timer
 int noteCounter;                 // Counts theme music notes
-int dstButtonCount;              // counter for the number of button presses
-int dstLastState;                // previous state of the button
-int hourButtonState;             // |
+int decimalTime;                 // Overall Clock Time
+int neoBrightness =      100;    // Neopixel Shield
+boolean running =        false;  // Colon ON/OFF
+
+// Hour Adjustment Variables
 int hourCount;                   // |
 int minuteCount;                 // | > For manual time adjustment
 int adjustedHour;                // |
 int adjustedMinute;              // |
-int decimalTime;                 // Overall Clock Time
-int neoBrightness =      100;    // Neopixel Shield
-boolean running =        false;  // Colon ON/OFF
+int dstButtonCount;              // counter for the number of button presses
+int dstLastState;                // previous state of dst button

 // Smoothing Variables:
 const int numReadings =  12;      // Number of readings to use (speeds/slows)
@@ -81,11 +83,12 @@
   pinMode (photoCellIn, INPUT);         // Photocell
   pinMode (minPlusButton, INPUT);       // Minute +
   pinMode (hourPlusButton, INPUT);      // Hour +
+  pinMode (minMinusButton, INPUT);      // Minute -
+  pinMode (hourMinusButton, INPUT);     // Hour -

   pinMode (fourTwentyLED, OUTPUT);      // Green LED
   pinMode (uvLED, OUTPUT);              // UV LED
   pinMode (neoPixel, OUTPUT);           // Neopixel
-  pinMode (dstLightOut, OUTPUT);        // DST LED

   Serial.begin(9600);
   Wire.begin();
@@ -104,15 +107,13 @@

 void loop()
 {
-  //  adjustTime();
-  disp.print(getDecimalTime());          // Show 12-Hour Time (7 Segment)
+  disp.print(getDecimalTime());              // Show 12-Hour Time (7 Segment)
   displayDay();                          // Show Weekday: 14 Segment
   blinkColon();                          // Blink Colon
   adjustBrightness();                    // Check Switch & Adjust brightness
   fourTwentyCheck();                     // Check if 4:20pm & Run Alarm
   reminderSwitch();                      // LED / Reminder
   dstHold();                             // Checks for Daylight Savings activation
-
 }

 // ================================================================================== //
@@ -126,25 +127,45 @@
   int decimalTime = now.hour() * 100 + now.minute();
   if (dstButtonCount == 1) decimalTime += 100;                // Plus/Minus 1 Hour
   if (hourCount > 0) decimalTime += adjustedHour;
-  if (minuteCount > 0) decimalTime += minuteCount;
+  if (minuteCount > 0) decimalTime += adjustedMinute;
+  int temporaryDelay = 100;
+
   if ((decimalTime > 1159) && !(decimalTime < 1259)) decimalTime -= 1200;

-  int hourButtonState = digitalRead(hourPlusButton);
-  if (hourButtonState == HIGH)
+  int hourPlusState = digitalRead(hourPlusButton);
+  if (hourPlusState == HIGH)
   {
     if (decimalTime > 1200) hourCount = 0;
     adjustedHour = hourCount * 100;
     hourCount++;
-    delay(400);
-  }
-
-  int minuteButtonState = digitalRead(minPlusButton);
-  if (minuteButtonState == HIGH)
+    delay(temporaryDelay);
+  }
+
+  int hourMinusState = digitalRead(hourMinusButton);
+  if (hourMinusState == HIGH)
+  {
+    if (decimalTime < 100) hourCount = 0;
+    adjustedHour = hourCount * -100;
+    hourCount++;
+    delay(temporaryDelay);
+  }
+
+  int minPlusState = digitalRead(minPlusButton);
+  if (minPlusState == HIGH)
   {
     if (now.minute() > 59) minuteCount = 0;
     adjustedMinute = minuteCount;
     minuteCount++;
-    delay(400);
+    delay(temporaryDelay);
+  }
+
+  int minMinusState = digitalRead(minMinusButton);
+  if (minMinusState == HIGH)
+  {
+    if (now.minute() < 1) minuteCount = 0;
+    adjustedMinute = minuteCount * -1;
+    minuteCount++;
+    delay(temporaryDelay);
   }
   return decimalTime;
 }
@@ -251,22 +272,17 @@
   alpha4.clear();
 }

+
 int dstHold()                                           // Holds button press
 {
   dstState = digitalRead(dstSwitchIn);
-
   if (dstState != dstLastState)
-    if (dstState == HIGH) dstButtonCount++;               // Compare the dstState to its previous state
+  if (dstState == HIGH) dstButtonCount++;               // Compare the dstState to its previous state
   dstLastState = dstState;                              // Save current state for next loop
-
-  if (dstButtonCount == 1) digitalWrite(dstLightOut, HIGH);
-  else
-  {
-    digitalWrite(dstLightOut, LOW);
-    dstButtonCount = 0;
-  }
-}
-
+
+  if (dstButtonCount == 1);
+  else dstButtonCount = 0;
+}

 // ================================================================================== //
@@ -306,7 +322,7 @@
       digitalWrite(uvLED, HIGH);
       delay(duration);
       digitalWrite(uvLED, LOW);
-    }
+    }
     noTone(piezoOut);
     noteCounter++;
   }
@@ -317,7 +333,7 @@
 {
   uint16_t i, j;
   int neoKnob = analogRead(neoLightIn);
-  int neoBrightness = map(neoKnob, 0, 1023, 1, 240);
+  int neoBrightness = map(neoKnob, 0, 1023, 1, 225);
   strip.setBrightness(neoBrightness);                        // Set Neopixel Brightness

   for (j = 0; j < 256 ; j++)                                 // *1 cycles of all colors on wheel


fixing initialization order, still must test error mode code

--- src/elm_clk.ino
+++ src/elm_clk.ino
@@ -441,16 +441,16 @@
 	if(timeStatus()!= timeSet)
 	{
 		Serial.println("Unable to sync with the RTC");
+		fsmState = ERROR_MODE;
 	} else
 	{
 		Serial.println("RTC has set the system time");
-		//fsmState = ERROR_MODE;
 	}

 	// default alarm settings, 08:30, disabled
 	pinMode(ALARM_PIN, INPUT_PULLUP);
-	//setRtcAlarm(8,30);
-	//disableRtcAlarm();
+	setRtcAlarm(8,30);
+	disableRtcAlarm();
 }

 void loop()
@@ -579,6 +579,7 @@
 		case ERROR_MODE:
 			if (oldFsmState != fsmState)
 			{
+				display.enableNumericDisplay();
 				display.writeMessage("ERRO");
 				Serial.println("Error detected, disabling buttons.");
 				Serial.println("Error detected, disabling RTC alarm.");


added initial pin state for relays to ensure that relays stay off during brown out.

--- ASC_Alexa_Sprinkler_Controller/ASC_Alexa_Sprinkler_Controller.ino
+++ ASC_Alexa_Sprinkler_Controller/ASC_Alexa_Sprinkler_Controller.ino
@@ -1,18 +1,18 @@
 /*
- * ===============================================================================================
- * Title: ASC - Alexa Sprinkler Controller
- * Description: ESP8266 Based, Arduino compatible, Alexa commandable, sprinkler controller.
- * Author: Ramsey Gill
- * License MIT
- * Homepage: https://hackaday.io/project/26850-alexa-enabled-sprinkler-controller
- * GitHub: https://github.com/ramseygill/alexa-sprinkler
- * ===============================================================================================
- * NOTES, Credit, Sources, and Props
- * NTP Library:https://github.com/arduino-libraries/NTPClient
- * Adafruit-MCP23017-Arduino-Library
- * Copyright (c) 2012, Adafruit Industries All rights reserved.
- * https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library/blob/master/license.txt
- */
+   ===============================================================================================
+   Title: ASC - Alexa Sprinkler Controller
+   Description: ESP8266 Based, Arduino compatible, Alexa commandable, sprinkler controller.
+   Author: Ramsey Gill
+   License MIT
+   Homepage: https://hackaday.io/project/26850-alexa-enabled-sprinkler-controller
+   GitHub: https://github.com/ramseygill/alexa-sprinkler
+   ===============================================================================================
+   NOTES, Credit, Sources, and Props
+   NTP Library:https://github.com/arduino-libraries/NTPClient
+   Adafruit-MCP23017-Arduino-Library
+   Copyright (c) 2012, Adafruit Industries All rights reserved.
+   https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library/blob/master/license.txt
+*/
 //------------------------------------------------------------------------------------------------
 //LIBRARIES
 //------------------------------------------------------------------------------------------------
@@ -60,7 +60,7 @@
 // You can specify the time server pool and the offset (in seconds, can be
 // changed later with setTimeOffset() ). Additionaly you can specify the
 // update interval (in milliseconds, can be changed using setUpdateInterval() ).
-NTPClient timeClient(ntpUDP,"0.us.pool.ntp.org", -25200, 60000);
+NTPClient timeClient(ntpUDP, "0.us.pool.ntp.org", -25200, 60000);

 //------------------------------------------------------------------------------------------------
@@ -72,15 +72,15 @@
   display.init();   // SSD12306 - OLED screen start I2C comms
   mcp.begin();      // MCP23017 - I/O Expander start I2C comms
   sensor0.begin();  // TMP102 - Temp Sensor start I2C comms
-
+
   //Flip Screen orientation in software, (pins on top)
   display.flipScreenVertically(); //SSD12306

   //CONFIGURE PIN USAGE
-  pinMode(alertPin,INPUT);  // Declare alertPin as an input TMP102
+  pinMode(alertPin, INPUT); // Declare alertPin as an input TMP102
   //set PORT A I/O expander pins to OUTPUTS for relay use
-  mcp.pinMode(relayPin_K1, OUTPUT);
-  mcp.pinMode(relayPin_K2, OUTPUT);
+  mcp.pinMode(relayPin_K1, OUTPUT);
+  mcp.pinMode(relayPin_K2, OUTPUT);
   mcp.pinMode(relayPin_K3, OUTPUT);
   mcp.pinMode(relayPin_K4, OUTPUT);
   mcp.pinMode(relayPin_K5, OUTPUT);
@@ -88,8 +88,19 @@
   mcp.pinMode(relayPin_K7, OUTPUT);
   mcp.pinMode(relayPin_K8, OUTPUT);

-  // FAUXMO DEVICES
-  // Each of these devices will appear in Alexa App.
+  //SET PIN INITIAL STATE
+  //Relay controller uses active low logic, setting each pin to HIGH on boot ensure that they remain off.
+  mcp.digitalWrite(relayPin_K1, HIGH);
+  mcp.digitalWrite(relayPin_K2, HIGH);
+  mcp.digitalWrite(relayPin_K3, HIGH);
+  mcp.digitalWrite(relayPin_K4, HIGH);
+  mcp.digitalWrite(relayPin_K5, HIGH);
+  mcp.digitalWrite(relayPin_K6, HIGH);
+  mcp.digitalWrite(relayPin_K7, HIGH);
+  mcp.digitalWrite(relayPin_K8, HIGH);
+
+  // FAUXMO DEVICES
+  // Each of these devices will appear in Alexa App.
   // Create a group from these devices "Front Yeard Sprinklers"
   // Each controller will have its own letter "A" followed by a zone "1"
   fauxmo.addDevice("Zone A1");
@@ -102,25 +113,25 @@
   fauxmo.addDevice("Zone A8");
   fauxmo.onMessage(callback); //function call for fauxmo state check.

-
-//------------TMP102 Setup----------------------------------------------------------
+
+  //------------TMP102 Setup----------------------------------------------------------
   // Initialize sensor0 settings
   // These settings are saved in the sensor, even if it loses power
-
+
   // set the number of consecutive faults before triggering alarm.
   // 0-3: 0:1 fault, 1:2 faults, 2:4 faults, 3:6 faults.
   sensor0.setFault(3);  // Trigger alarm immediately
-
+
   // set the polarity of the Alarm. (0:Active LOW, 1:Active HIGH).
   sensor0.setAlertPolarity(1); // Active HIGH
-
+
   // set the sensor in Comparator Mode (0) or Interrupt Mode (1).
   sensor0.setAlertMode(0); // Comparator Mode.
-
+
   // set the Conversion Rate (how quickly the sensor gets a new reading)
   //0-3: 0:0.25Hz, 1:1Hz, 2:4Hz, 3:8Hz
   sensor0.setConversionRate(2);
-
+
   //set Extended Mode.
   //0:12-bit Temperature(-55C to +128C) 1:13-bit Temperature(-55C to +150C)
   sensor0.setExtendedMode(0);
@@ -128,23 +139,23 @@
   //set T_HIGH, the upper limit to trigger the alert on
   sensor0.setHighTempF(77.0);  // set T_HIGH in F
   //sensor0.setHighTempC(29.4); // set T_HIGH in C
-
+
   //set T_LOW, the lower limit to shut turn off the alert
   sensor0.setLowTempF(76.0);  // set T_LOW in F
   //sensor0.setLowTempC(26.67); // set T_LOW in C
-//----------------------------------------------------------------------------------
-
-
-//------------USB Serial Comms Setup -----------------------------------------------
+  //----------------------------------------------------------------------------------
+
+
+  //------------USB Serial Comms Setup -----------------------------------------------
   Serial.begin(baudRate);                            //start UART serial comm at global deff baudrate
   Serial.println();                                  // add two blank lines
   Serial.println();
   Serial.println("ALEXA Sprinkler Controller V1.0"); //vanity title for serial window
-//----------------------------------------------------------------------------------
-
-//------------WiFi Setup------------------------------------------------------------
- wifiSetup();     // Function call to kick off WiFi setup.
-//----------------------------------------------------------------------------------
+  //----------------------------------------------------------------------------------
+
+  //------------WiFi Setup------------------------------------------------------------
+  wifiSetup();     // Function call to kick off WiFi setup.
+  //----------------------------------------------------------------------------------
 }

 //------------------------------------------------------------------------------------------------
@@ -153,7 +164,7 @@

 //UPDATE IP FUNCTION
 //------------------------------------------------------------------------------------------------
-void updateIP(){
+void updateIP() {
   String ipaddress = WiFi.localIP().toString(); // convert IP address array to string
   display.setTextAlignment(TEXT_ALIGN_LEFT);
   display.setFont(ArialMT_Plain_16);
@@ -163,7 +174,7 @@
 //UPDATE TIME FUNCTION
 //------------------------------------------------------------------------------------------------

-void updateTime(){
+void updateTime() {
   timeClient.update(); // Requests time update from NTP server
   String timeString = timeClient.getFormattedTime(); // convert time to string
   display.setTextAlignment(TEXT_ALIGN_LEFT);
@@ -174,65 +185,65 @@
 //UPDATE TEMP FUNCTION (SHITSHOW CODE, BUT IT WORKS)
 //------------------------------------------------------------------------------------------------

-void updateTemp(){
-
+void updateTemp() {
+
   float temperature;
-  String stringVal = "";
+  String stringVal = "";
   boolean alertPinState, alertRegisterState;

   // read temperature data and write to OLED screen
   temperature = sensor0.readTempF();
   //temperature = sensor0.readTempC();
-
+
   // convert temperature float to string
-  stringVal+=String(int(temperature))+ "."+String(getDecimal(temperature)); //combining both whole and decimal part in string with a fullstop between them
+  stringVal += String(int(temperature)) + "." + String(getDecimal(temperature)); //combining both whole and decimal part in string with a fullstop between them
   //Serial.print("stringVal: ");Serial.println(stringVal);              //display string value
-
-  char charVal[stringVal.length()+1];                      //initialise character array to store the values
-  stringVal.toCharArray(charVal,stringVal.length()+1);     //passing the value of the string to the character array
-
-  //Serial.print("charVal: ");
-  for(uint8_t i=0; i<sizeof(charVal);i++) //Serial.print(charVal[i]); //display character array
-
-  display.setTextAlignment(TEXT_ALIGN_LEFT);
+
+  char charVal[stringVal.length() + 1];                    //initialise character array to store the values
+  stringVal.toCharArray(charVal, stringVal.length() + 1);  //passing the value of the string to the character array
+
+  //Serial.print("charVal: ");
+  for (uint8_t i = 0; i < sizeof(charVal); i++) //Serial.print(charVal[i]); //display character array
+
+    display.setTextAlignment(TEXT_ALIGN_LEFT);
   display.setFont(ArialMT_Plain_16);
   display.drawString(0, 32, "TEMP:");
   display.drawString(80, 32, "F");
   display.drawString(48, 32, (stringVal));
-
+
   // Check for Alert
   alertPinState = digitalRead(alertPin); // read the Alert from pin
   alertRegisterState = sensor0.alert();   // read the Alert from register
-
+
   /*
-  // Print temperature and alarm state
-  Serial.print("Temperature: ");
-  Serial.print(temperature);
-
-  Serial.print("\tAlert Pin: ");
-  Serial.print(alertPinState);
-
-  Serial.print("\tAlert Register:  ");
-  Serial.println(alertRegisterState);
+    // Print temperature and alarm state
+    Serial.print("Temperature: ");
+    Serial.print(temperature);
+
+    Serial.print("\tAlert Pin: ");
+    Serial.print(alertPinState);
+
+    Serial.print("\tAlert Register:  ");
+    Serial.println(alertRegisterState);
   */
 }
 //function to extract decimal part of float (SUB ROUTINE OF TEMP UPDATE)
 long getDecimal(float val)
 {
   int intPart = int(val);
-  long decPart = 10*(val-intPart); //I am multiplying by 1000 assuming that the foat values will have a maximum of 3 decimal places.
-                                    //Change to match the number of decimal places you need
-  if(decPart>0)return(decPart);           //return the decimal part of float number if it is available
-  else if(decPart<0)return((-1)*decPart); //if negative, multiply by -1
-  else if(decPart=0)return(00);           //return 0 if decimal part of float number is not available
+  long decPart = 10 * (val - intPart); //I am multiplying by 1000 assuming that the foat values will have a maximum of 3 decimal places.
+  //Change to match the number of decimal places you need
+  if (decPart > 0)return (decPart);       //return the decimal part of float number if it is available
+  else if (decPart < 0)return ((-1) * decPart); //if negative, multiply by -1
+  else if (decPart = 0)return (00);       //return 0 if decimal part of float number is not available
 }
 //FAUXMO CALLBACK FUNCTION add devices here
 //------------------------------------------------------------------------------------------------
 void callback(uint8_t device_id, const char * device_name, bool state) {
   Serial.printf("[MAIN] %s state: %s\n", device_name, state ? "ON" : "OFF");
-
-
-//ZONE 1
+
+
+  //ZONE 1
   if ( (strcmp(device_name, "Zone A1") == 0) ) {
     if (state) {
       mcp.digitalWrite(relayPin_K1, LOW); //TURN ON RELAY
@@ -240,7 +251,7 @@
       mcp.digitalWrite(relayPin_K1, HIGH); //TURN OFF RELAY
     }
   }
-//ZONE 2
+  //ZONE 2
   if ( (strcmp(device_name, "Zone A2") == 0) ) {
     if (state) {
       mcp.digitalWrite(relayPin_K2, LOW); //TURN ON RELAY
@@ -248,15 +259,15 @@
       mcp.digitalWrite(relayPin_K2, HIGH); //TURN OFF RELAY
     }
   }
-//ZONE 3
-  if ( (strcmp(device_name, "Zone A3") == 0) ) {
+  //ZONE 3
+  if ( (strcmp(device_name, "Zone A3") == 0) ) {
     if (state) {
       mcp.digitalWrite(relayPin_K3, LOW); //TURN ON RELAY
     } else {
       mcp.digitalWrite(relayPin_K3, HIGH); //TURN OFF RELAY
     }
   }
-//ZONE 4
+  //ZONE 4
   if ( (strcmp(device_name, "Zone A4") == 0) ) {
     if (state) {
       mcp.digitalWrite(relayPin_K4, LOW); //TURN ON RELAY
@@ -264,23 +275,23 @@
       mcp.digitalWrite(relayPin_K4, HIGH); //TURN OFF RELAY
     }
   }
-//ZONE 5
+  //ZONE 5
   if ( (strcmp(device_name, "Zone A5") == 0) ) {
     if (state) {
       mcp.digitalWrite(relayPin_K5, LOW); //TURN ON RELAY
     } else {
       mcp.digitalWrite(relayPin_K5, HIGH); //TURN OFF RELAY
     }
-  }
-//ZONE 6
+  }
+  //ZONE 6
   if ( (strcmp(device_name, "Zone A6") == 0) ) {
     if (state) {
       mcp.digitalWrite(relayPin_K6, LOW); //TURN ON RELAY
     } else {
       mcp.digitalWrite(relayPin_K6, HIGH); //TURN OFF RELAY
     }
-  }
-//ZONE 7
+  }
+  //ZONE 7
   if ( (strcmp(device_name, "Zone A7") == 0) ) {
     if (state) {
       mcp.digitalWrite(relayPin_K7, LOW); //TURN ON RELAY
@@ -288,7 +299,7 @@
       mcp.digitalWrite(relayPin_K7, HIGH); //TURN OFF RELAY
     }
   }
-//ZONE 8
+  //ZONE 8
   if ( (strcmp(device_name, "Zone A8") == 0) ) {
     if (state) {
       mcp.digitalWrite(relayPin_K8, LOW); //TURN ON RELAY
@@ -311,13 +322,13 @@

   // Wait
   while (WiFi.status() != WL_CONNECTED) {
-      Serial.print(".");
-      delay(100);
+    Serial.print(".");
+    delay(100);
   }
   Serial.println();
-
+
   timeClient.begin(); // start NTP time client
-
+
   // Connected!
   Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
 }


-Logging now actually works.

-Logging now actually works.

--- loggertask.ino
+++ loggertask.ino
@@ -2,23 +2,26 @@
 {
   const uint64_t loggerTaskdelayTime  = ( 1000 * 60 ) / portTICK_PERIOD_MS;

-  Serial.println( "Data logger task init." );
-
-  Serial.printf( "Free space left on SPIFFS: %.2f MB.\n", ( SPIFFS.totalBytes() - SPIFFS.usedBytes() ) / ( 1024.0 * 1024 ) );
-
   if ( !numberOfFoundSensors )
   {
-    Serial.println( "No dallas sensors. Exiting task." );
     vTaskDelete( NULL );
   }

+  TickType_t xLastWakeTime;
+
+  xLastWakeTime = xTaskGetTickCount();
+
   while (1)
   {
+    char            content[40];
+    uint8_t           charCount = 0;
+    static bool systemHasBooted = true;
+    time_t                  now;
+    struct tm          timeinfo;

-    char content[40];
-    uint8_t charCount = 0;
+    time( &now );

-    charCount += snprintf( content, sizeof( content ), "%i,", time( NULL ) );
+    charCount += snprintf( content, sizeof( content ), "%i,", now );

     if ( numberOfFoundSensors )
     {
@@ -34,75 +37,45 @@
       charCount += snprintf( content + charCount, sizeof( content ) - charCount, ",%s", "No sensors." );
     }

-    struct tm timeinfo;
-    getLocalTime( &timeinfo );
+    char fileName[17];

-    char fileName[17];
+    localtime_r( &now, &timeinfo );
     strftime( fileName , sizeof( fileName ), "/%F.log", &timeinfo );
+
+    const char * appendError = "Failed to open log file.";
+
+    if ( systemHasBooted )
+    {
+      char buffer[40];
+
+      snprintf( buffer, sizeof( buffer ), "#%i Aquacontrol32 start", now );
+      if ( !writelnFile( SPIFFS, fileName, buffer ) )
+      {
+        Serial.println( appendError );
+      }
+      systemHasBooted = false;
+    }

     if ( !writelnFile( SPIFFS, fileName, content ) )
     {
-      Serial.println("Failed to open file for appending");
+      Serial.println( appendError );
     }
-    else
-    {
-      Serial.printf( "Written '%s' to '%s'.\n", content, fileName );
-    }
-    vTaskDelay( loggerTaskdelayTime );
+    vTaskDelayUntil( &xLastWakeTime, loggerTaskdelayTime / portTICK_PERIOD_MS );
   }
 }

-bool writelnFile( fs::FS &fs, const char * path, const char * message )
+static inline __attribute__((always_inline)) bool writelnFile( fs::FS &fs, const char * path, const char * message )
 {
   File file = fs.open( path, FILE_APPEND );
   if ( !file )
   {
-    Serial.println("Failed to open file for writing");
     return false;
   }
   if ( !file.println( message ) )
   {
-    Serial.println("File write failed");
     file.close();
     return false;
   }
   file.close();
   return true;
 }
-/*
-  void listDir( fs::FS &fs, const char * dirname, uint8_t levels )
-  {
-    Serial.printf( "Listing directory: %s\n", dirname );
-
-    File root = fs.open( dirname );
-    if( !root ){
-        Serial.println( "Failed to open directory" );
-        return;
-    }
-    if( !root.isDirectory() ){
-        Serial.println( "Not a directory" );
-        return;
-    }
-
-    File file = root.openNextFile();
-    while(file)
-    {
-        if(file.isDirectory())
-        {
-            Serial.print("  DIR : ");
-            Serial.println(file.name());
-            if(levels){
-                listDir(fs, file.name(), levels -1);
-            }
-        }
-        else
-        {
-            Serial.print("  FILE: ");
-            Serial.print(file.name());
-            Serial.print("  SIZE: ");
-            Serial.println(file.size());
-        }
-        file = root.openNextFile();
-    }
-  }
-*/


Updates to Xively client

Updates to Xively client

--- hardware/arduino/avr/libraries/Bridge/examples/XivelyClient/XivelyClient.ino
+++ hardware/arduino/avr/libraries/Bridge/examples/XivelyClient/XivelyClient.ino
@@ -35,6 +35,7 @@
 // set up net client info:
 boolean lastConnected = false;      // state of the connection last time through the main loop
 const unsigned long postingInterval = 60000;  //delay between updates to Pachube.com
+unsigned long lastRequest = 0;      // when you last made a request
 String dataString = "";
 Process xively;

@@ -43,7 +44,10 @@
   Serial.begin(9600);
   Bridge.begin();
   delay(2000);
-
+
+  while(!Serial);    // wait for Serial Monitor to open
+  Serial.println("Xively client");
+
   // reserve space for dataString:
   dataString.reserve(100);
 }
@@ -70,8 +74,9 @@

   // if you're not connected, and the sending interval has passed since
   // your last connection, then connect again and send data:
-  if(now % postingInterval < 5) {
+  if(now - lastRequest >= postingInterval) {
     sendData();
+    lastRequest = now;
   }
 }


fix merge messages

fix merge messages

--- files/template_home/template_home_2014/template_home_2014.ino
+++ files/template_home/template_home_2014/template_home_2014.ino
@@ -1,13 +1,5 @@
 /*
 SenseBox Citizen Sensingplatform
-<<<<<<< HEAD:files/template.ino
-Version: 1.2
-Date: 2015-01-06
-Homepage: http://sensebox.uni-muenster.de/bestellen/fuer-buerger/
-Author: Jan Wirwahn
-Note: Version with additional sensors for GIS-GK@ifgi
-*/
-=======
 Version: 1.1
 Date: 2015-01-14
 Homepage: http://www.sensebox.de
@@ -15,40 +7,25 @@
 Note: Sketch for SB-Home Edition 2014
 */

->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino
 #include <Wire.h>
 #include <SPI.h>
 #include <EthernetV2_0.h>
 #include <DHT.h>
 #include <Barometer.h>
-<<<<<<< HEAD:files/template.ino
-#include <Digital_Light_TSL2561.h>
 #include <avr/wdt.h>

-=======
-#include <avr/wdt.h>
-
 //IDs are being generated by the OSM server
->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino
 //SenseBox ID

 //Sensor IDs

 //Sensor pin settings
 #define NOISEPIN A0
-<<<<<<< HEAD:files/template.ino
-#define DHTPIN A1
-#define UVPIN A2
-#define DHTTYPE DHT11
-//Ethernet shield settings
-#define W5200_CS  10
-=======
 #define LIGHTPIN A1
 #define DHTPIN A2
 #define DHTTYPE DHT11
 //Ethernet shield settings
 #define W5200_CS 10
->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino
 #define SDCARD_CS 4

 //Network settings
@@ -58,17 +35,8 @@
 EthernetClient client;

 String currentSensorId = TEMPERATURESENSOR_ID;
-<<<<<<< HEAD:files/template.ino
-float temperature;
-float humidity;
-float pressure;
-unsigned long  lux;
-int analogNoise;
-int uvValue;
-=======
 float temperature, humidity, pressure;
 int analogNoise, analogLight;
->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino

 DHT dht(DHTPIN, DHTTYPE);
 Barometer barometer;
@@ -79,12 +47,8 @@
 boolean lastConnected = false;
 boolean uploadSuccess = true;
 String sensorSample;
-<<<<<<< HEAD:files/template.ino
-int sampleType = 1; //1=temp,2=humi,3=baro,4=light
-=======
 int sampleType = 1;
 int phenomenonCount = 5; //1=temp,2=humi,3=baro,4=noise,5=light
->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino

 void setup(){
   Wire.begin();
@@ -93,7 +57,7 @@
   pinMode(SDCARD_CS,OUTPUT);
   digitalWrite(SDCARD_CS,HIGH);
   delay(500);
-  // start the Ethernet connection
+  // start the Ethernet connection
   if (Ethernet.begin(mac) == 0) {
     Serial.println("Failed to configure Ethernet using DHCP.");
     //If DHCP is disabled, use static IP
@@ -104,7 +68,7 @@
   for (byte thisByte = 0; thisByte < 4; thisByte++) {
     // print the value of each byte of the IP address:
     Serial.print(Ethernet.localIP()[thisByte], DEC);
-    Serial.print(".");
+    Serial.print(".");
   }
   Serial.println();
   barometer.init();
@@ -126,7 +90,7 @@
     Serial.println();
     Serial.println("...stopping client!");
     client.stop();
-  }
+  }
   //If last upload was successful, switch case to select the next sensor
   if (uploadSuccess){
     Serial.println();
@@ -137,11 +101,7 @@
       case 1:
         //temperature = dht.readTemperature();
         temperature = barometer.bmp085GetTemperature(barometer.bmp085ReadUT());
-<<<<<<< HEAD:files/template.ino
-        sensorSample = floatToString(temperature,0);
-=======
         sensorSample = floatToString(temperature,1);
->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino
         currentSensorId = TEMPERATURESENSOR_ID;
         break;
       case 2:
@@ -161,33 +121,21 @@
         currentSensorId = NOISESENSOR_ID;
         break;
       case 5:
-<<<<<<< HEAD:files/template.ino
-        TSL2561.getLux();
-        lux = TSL2561.calculateLux(0,0,1);
-        sensorSample = (String)lux;
-        currentSensorId = LIGHTSENSOR_ID;
-        break;
-      case 6:
-        uvValue = analogRead(UVPIN);
-        sensorSample = (String)calcUVIndex(uvValue);
-        currentSensorId = UVSENSOR_ID;
-=======
         analogLight = analogRead(LIGHTPIN);
         sensorSample = (String)analogLight;
         currentSensorId = LIGHTSENSOR_ID;
->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino
         break;
     }
   }
   // if you're not already connected, and 60 seconds have passed since
-  // your last connection, then connect again and send data:
+  // your last connection, then connect again and send data:
   uploadSuccess = false;
   if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
     Serial.println("-----------------------------------");
     Serial.print("Connecting and posting sensor sample (case ");
     Serial.print(sampleType);
     Serial.print(")...");
-    Serial.println();
+    Serial.println();
     postObservation(sensorSample, currentSensorId, SENSEBOX_ID);
   }
   // store the state of the connection for next time through the loop
@@ -206,71 +154,47 @@
   return stringNumber;
 }

-<<<<<<< HEAD:files/template.ino
-int calcUVIndex(int analogValue){
-  int uvi;
-  if (analogValue<10) uvi = 0;
-  else if (analogValue<46) uvi = 1;
-  else if (analogValue<65) uvi = 2;
-  else if (analogValue<83) uvi = 3;
-  else if (analogValue<103) uvi = 4;
-  else if (analogValue<124) uvi = 5;
-  else if (analogValue<142) uvi = 6;
-  else if (analogValue<162) uvi = 7;
-  else if (analogValue<180) uvi = 8;
-  else if (analogValue<200) uvi = 9;
-  else if (analogValue<221) uvi = 10;
-  else if (analogValue<240) uvi = 11;
-  return uvi;
-}
-
-=======
->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino
 //Method for posting a measurement to OSM server
 void postObservation(String measurement, String sensorId, String boxId)
-{
+{
   //if (measurement=="") return;
   wdt_enable(WDTO_8S);
-  //json must look like {"value":"12.5"}
-  String valueJson = "{\"value\":";
-  valueJson += measurement;
+  //json must look like {"value":"12.5"}
+  String valueJson = "{\"value\":";
+  valueJson += measurement;
   valueJson += "}";
   Serial.println(valueJson);
   //post observation to: http://opensensemap.org:8000/boxes/boxId/sensorId
-  // if you get a connection, report back via serial:
+  // if you get a connection, report back via serial:
   wdt_reset();
-  if (client.connect(server, 8000))
+  if (client.connect(server, 8000))
   {
-    Serial.print("connected...");
-    Serial.println();
-    // Make a HTTP Post request:
-    client.print("POST /boxes/");
+    Serial.print("connected...");
+    Serial.println();
+    // Make a HTTP Post request:
+    client.print("POST /boxes/");
     client.print(boxId);
-    client.print("/");
-    client.print(sensorId);
-    client.println(" HTTP/1.1");
-    // Send the required header parameters
-    client.println("Host:opensensemap.org");
-    client.println("Content-Type: application/json");
-    client.println("Connection: close");
-    client.print("Content-Length: ");
-    client.println(valueJson.length());
-    client.println();
-    client.print(valueJson);
-    client.println();
+    client.print("/");
+    client.print(sensorId);
+    client.println(" HTTP/1.1");
+    // Send the required header parameters
+    client.println("Host:opensensemap.org");
+    client.println("Content-Type: application/json");
+    client.println("Connection: close");
+    client.print("Content-Length: ");
+    client.println(valueJson.length());
+    client.println();
+    client.print(valueJson);
+    client.println();
     Serial.println("done!");
     uploadSuccess = true;
     //Change case
-<<<<<<< HEAD:files/template.ino
-    if (sampleType == 6) {
-=======
     if (sampleType == phenomenonCount) {
->>>>>>> d9865cb6c3dc6543253fc1c85805d10c0e4ef2d4:files/template_home/template_home_2014/template_home_2014.ino
       sampleType = 1;
       // remember the time that the connection was made or attempted
       lastConnectionTime = millis();
     }else sampleType++;
-  }else
+  }else
   {
     // stop the client if you couldn't make a connection !
     Serial.println("failed...disconnecting.");


plaque chauffante OK

plaque chauffante OK

--- arduino/plaques_de_cuisson_captors/plaques_de_cuisson_captors.ino
+++ arduino/plaques_de_cuisson_captors/plaques_de_cuisson_captors.ino
@@ -28,6 +28,7 @@
 /* Variables globales */
 char command[500];
 bool firstRead = true;
+bool firstTime = true;

 /* Initialize console output */
 void initOutput() {
@@ -70,6 +71,10 @@
   panValue = analogRead(panPin);
   /*Serial.print("poids : ");
   Serial.println(panValue);*/
+  if(firstTime) {
+    firstTime = false;
+    old_panValue = panValue;
+  }
   if(panValue - old_panValue > 20) {
     isWeighted = true;
   } else if (old_panValue - panValue > 20) {


ble_proximity_template done

ble_proximity_template done

--- libraries/BLE/examples/ble_proximity_template/ble_proximity_template.ino
+++ libraries/BLE/examples/ble_proximity_template/ble_proximity_template.ino
@@ -56,7 +56,6 @@
  *
  */
 #include <SPI.h>
-#include <avr/pgmspace.h>
 #include <lib_aci.h>

 #include <aci_setup.h>
@@ -304,6 +303,8 @@

 void aci_loop()
 {
+  static bool setup_required = false;
+
   // We enter the if statement only when there is a ACI event available to be processed
   if (lib_aci_event_get(&aci_state, &aci_data))
   {
@@ -325,10 +326,7 @@
             When the device is in the setup mode
             */
             Serial.println(F("Evt Device Started: Setup"));
-            if (ACI_STATUS_TRANSACTION_COMPLETE != do_aci_setup(&aci_state))
-            {
-              Serial.println(F("Error in ACI Setup"));
-            }
+            setup_required = true;
             break;

             case ACI_DEVICE_STANDBY:
@@ -578,6 +576,18 @@
     // Arduino can go to sleep now
     // Wakeup from sleep from the RDYN line
   }
+
+  /* setup_required is set to true when the device starts up and enters setup mode.
+   * It indicates that do_aci_setup() should be called. The flag should be cleared if
+   * do_aci_setup() returns ACI_STATUS_TRANSACTION_COMPLETE.
+   */
+  if(setup_required)
+  {
+    if (SETUP_SUCCESS == do_aci_setup(&aci_state))
+    {
+      setup_required = false;
+    }
+  }
 }

 void alert_level_print(alert_level_t level)
@@ -656,7 +666,8 @@

   //We reset the nRF8001 here by toggling the RESET line connected to the nRF8001
   //and initialize the data structures required to setup the nRF8001
-  lib_aci_init(&aci_state);
+  //The second parameter is for turning debug printing on for the ACI Commands and Events so they be printed on the Serial
+  lib_aci_init(&aci_state, true);
   aci_state.bonded = ACI_BOND_STATUS_FAILED;

   pinMode(6, INPUT); //Pin #6 on Arduino -> PAIRING CLEAR pin: Connect to 3.3v to clear the pairing


Moved state machine switch to ISR

Moved state machine switch to ISR

--- software/_proto_DriverFirmware/MainControlFirmware/MainControlFirmware.ino
+++ software/_proto_DriverFirmware/MainControlFirmware/MainControlFirmware.ino
@@ -61,6 +61,8 @@
   PCComm.begin(57600);
   PCComm.print("\n\r[Board Init]\n\r");

+  Timer1.initialize(3000);  //def 100000
+  Timer1.attachInterrupt( dispDrive );
   //t.every(2000, sayHello);

 }
@@ -81,21 +83,22 @@
   MISC
 } CurrentState = DISPLEFT;

+static Display disp(0);
+static Display disp2(1);

 void loop()
 {
-  static Display disp(0);
-  static Display disp2(1);
+

   static uint16_t timing = 1;
   static uint16_t i = 0;
   uint8_t status = 0;
   uint8_t status2 = 0;

-  uint16_t to_write = 0;
+  //uint16_t to_write = 0;

   if(!timing){  //Time to do the asynch tasks
-	//PCComm.println("[Processing configureToWrite]");
+	//PCComm.println("[Processing Asynch Tasks]");

 	i = ++i%10;
 	char temp[2];
@@ -110,6 +113,31 @@
 	temp[1] = '4'; //4 + 48;
 	disp2.setRight(temp);
   }
+
+
+
+
+  disp.writeToDisplay();
+  disp2.writeToDisplay();
+
+  /*
+  PCComm.print("[Wrote '");
+  PCComm.print(to_write, BIN);
+  PCComm.print("' to board timing: ");
+  PCComm.print(timing);
+  PCComm.print("]\n\r");
+  */
+
+  ++timing;
+
+  timing = timing % TIMING_CONSTANT;
+
+}
+
+//Drives the I2C interface for the displays
+void dispDrive(){
+
+  PCComm.println("[dispDrive]");

   switch(CurrentState) {
     case DISPLEFT:
@@ -124,26 +152,7 @@
       break;
   }

-  disp.writeToDisplay();
-  disp2.writeToDisplay();
-
-
-  /*
-  PCComm.print("[Wrote '");
-  PCComm.print(to_write, BIN);
-  PCComm.print("' to board timing: ");
-  PCComm.print(timing);
-  PCComm.print("]\n\r");
-  */
-
-  ++timing;
-
-  timing = timing % TIMING_CONSTANT;
-
-}
-
-void sayHello(){
-	PCComm.println("Hello!");
+
 }

 /*


Visual feedback

Visual feedback

Flash led on starting AP (2 twice) on starting WiFi (4 times)

--- ESP8266-code/WiFiconfig.ino
+++ ESP8266-code/WiFiconfig.ino
@@ -5,11 +5,9 @@
  *
  * In normal mode, collect data and send to the data store
  *
- * Todo
- *   configuration needs to set the configuration in non-volatile store
- *   wifi connection failure not quite handled correctly yet
- *   need to flash the led when connected and data flowing
- *
+ *
+ * configuration needs to set the configuration in non-volatile store
+ *  *
  */

 #include <ESP8266WiFi.h>
@@ -29,8 +27,12 @@
 String password;
 String stream_id;
 String stream_pk;
-
 char* host ="kitwallace.co.uk";
+
+
+// interaction
+//const int startAP = D1;
+const int LED = D4;

 WiFiServer server(80);
 WiFiClient client;
@@ -39,6 +41,10 @@
 	delay(1000);
 	Serial.begin(9600);
   Serial.println(String("ap started: ") + ap_started + " WiFi connected: " + wifi_connected);
+
+  pinMode(D1,INPUT);
+  pinMode(D4,OUTPUT);
+  digitalWrite(D4,HIGH);  // turn it off
 }

 void loop() {
@@ -139,6 +145,7 @@
   IPAddress ap_IP = WiFi.softAPIP();
   Serial.print("AP IP address: ");
   Serial.println(ap_IP);
+  blink(2,500,500);
 }

 void startServer() {
@@ -166,6 +173,7 @@
   }
   Serial.println("");
   Serial.println("WiFi connected");
+  blink(4,500,200);
   return true;
 }

@@ -209,3 +217,12 @@
    url += params;
    httpGet(host,url);
 }
+
+void blink(int n, int onms,int offms) {
+    for (int i =0;i <n; i++) {
+      digitalWrite(LED,LOW);
+      delay(onms);
+      digitalWrite(LED,HIGH);
+      delay(offms);
+    }
+}


Formatting

Formatting

--- interocitor/interocitor.ino
+++ interocitor/interocitor.ino
@@ -96,7 +96,8 @@
 // Note scheduling array,
 volatile MidiNote active_notes[TIMER_COUNT];

-void set_note(int i, byte channel, byte pitch, byte velocity){
+void set_note(int i, byte channel, byte pitch, byte velocity)
+{
   active_notes[i].channel = channel;
   active_notes[i].pitch = pitch;
   active_notes[i].velocity = velocity;
@@ -104,7 +105,8 @@
   active_notes[i].phase_us = micros() % active_notes[i].period_us;
 }

-void clear_note(int i) {
+void clear_note(int i)
+{
   active_notes[i].velocity = 0;
   active_notes[i].pitch = 255;
   active_notes[i].channel = 0;
@@ -112,15 +114,17 @@
   active_notes[i].phase_us = 0;
 }

-int find_first_empty_note_index() {
-  for(int i = 0; i<TIMER_COUNT; i++){
-    if(active_notes[i].pitch == 255){
+int find_first_empty_note_index()
+{
+  for (int i = 0; i < TIMER_COUNT; i++)
+  {
+    if (active_notes[i].pitch == 255)
+    {
       return i;
     }
   }
   return -1;
 }
-

 float bent_value_cents = 0;

@@ -363,15 +367,23 @@

   if ((midi_vs_pulse == 1))
   {
-    if (sub_setting == 0){
+    if (sub_setting == 0)
+    {
       system_mode = SM_MIDI_USB;
-    } else {
+    }
+    else
+    {
       system_mode = SM_MIDI_JACK;
     }
-  } else {
-    if (sub_setting == 0){
+  }
+  else
+  {
+    if (sub_setting == 0)
+    {
       system_mode = SM_FREQ_FIXED;
-    } else {
+    }
+    else
+    {
       system_mode = SM_FREQ_PINK;
     }
   }
@@ -414,7 +426,8 @@
 {
   // if we find a timer free, start a note with pitch/velocity specified
   int idx = find_first_empty_note_index();
-  if (idx == -1){
+  if (idx == -1)
+  {
     return;
   }

@@ -447,7 +460,6 @@
   }
 };

-
 void clear_notes_and_timers()
 {
   for (byte i = 0; i < TIMER_COUNT; i++)
@@ -475,19 +487,21 @@
 // For the pulsed (tick) mode
 const int32_t MAX_WAIT_US = 1000;
 const float DUTY_CYCLE = 0.25;
-const float PULSE_MULT = (1.0/DUTY_CYCLE) - 1.0;
+const float PULSE_MULT = (1.0 / DUTY_CYCLE) - 1.0;

 volatile MUSIC_STATE music_state = SM_NEXT;
 volatile int pulse_length_us = 100;
 volatile unsigned long next_pulse_start_micros = 0;

-void start_music_sm(){
+void start_music_sm()
+{
   music_state = SM_NEXT;
   timer_0.begin(music_loop, 10);
   // timer_0.priority(0);
 }

-void stop_music_sm() {
+void stop_music_sm()
+{
   music_state = SM_NEXT;
   timer_0.end();
 }
@@ -501,41 +515,46 @@
 //  - pulse_length_us - the length of the pulse to be played.
 void music_loop()
 {
-  unsigned long start_micros = micros();
-
-  switch(music_state){
-    case SM_NEXT: {
-        uint32_t wait_us = 10000;
-        for(int i=0; i < TIMER_COUNT; i++){
-          if(active_notes[i].pitch == 255){
-            continue;
-          }
-          unsigned long phase_us = active_notes[i].phase_us;
-          unsigned long period_us = active_notes[i].period_us;
-
-          unsigned long this_wait_us = period_us - ((start_micros + phase_us) % period_us) ;
-
-          if(this_wait_us < wait_us){
-            wait_us = this_wait_us;
-            next_pulse_start_micros = start_micros + this_wait_us;
-            pulse_length_us = velocity_to_pulse_length(active_notes[i].velocity);
-            music_state = SM_WAIT;
-          }
-        }
+  unsigned long start_micros = micros();
+
+  switch (music_state)
+  {
+  case SM_NEXT:
+  {
+    uint32_t wait_us = 10000;
+    for (int i = 0; i < TIMER_COUNT; i++)
+    {
+      if (active_notes[i].pitch == 255)
+      {
+        continue;
       }
-      break;
-    case SM_WAIT:
-      music_state = micros() > next_pulse_start_micros ? SM_PULSE : SM_WAIT;
-      break;
-    case SM_PULSE:
-      // Actual pulse is below
-      digitalWriteFast(channel_1_out, HIGH);
-      delay_safe_micros(pulse_length_us);
-      digitalWriteFast(channel_1_out, LOW);
-      // Compute the time needed to keep duty cycle below:
-      delayMicroseconds(PULSE_MULT * pulse_length_us);
-      music_state = SM_NEXT;
-      break;
+      unsigned long phase_us = active_notes[i].phase_us;
+      unsigned long period_us = active_notes[i].period_us;
+
+      unsigned long this_wait_us = period_us - ((start_micros + phase_us) % period_us);
+
+      if (this_wait_us < wait_us)
+      {
+        wait_us = this_wait_us;
+        next_pulse_start_micros = start_micros + this_wait_us;
+        pulse_length_us = velocity_to_pulse_length(active_notes[i].velocity);
+        music_state = SM_WAIT;
+      }
+    }
+  }
+  break;
+  case SM_WAIT:
+    music_state = micros() > next_pulse_start_micros ? SM_PULSE : SM_WAIT;
+    break;
+  case SM_PULSE:
+    // Actual pulse is below
+    digitalWriteFast(channel_1_out, HIGH);
+    delay_safe_micros(pulse_length_us);
+    digitalWriteFast(channel_1_out, LOW);
+    // Compute the time needed to keep duty cycle below:
+    delayMicroseconds(PULSE_MULT * pulse_length_us);
+    music_state = SM_NEXT;
+    break;
   }
 }


How to teach young people to program? How I pretend to program? # kidsSerie-06

How to teach young people to program? How I pretend to program? # kidsSerie-06

--- _06_kidSerie_sketch_unique_Adafruit_IO_FakeToReal_Feeds.ino
+++ _06_kidSerie_sketch_unique_Adafruit_IO_FakeToReal_Feeds.ino
@@ -41,9 +41,9 @@
 //#include <WiFiClient.h>
 //#include <ESP8266WebServer.h>
 /******************************* DHT Config **********************************/
-//#include <DHT.h>
-//#define DHTTYPE DHT11
-//#define DHTPIN  2
+#include <DHT.h>
+#define DHTTYPE DHT11
+#define DHTPIN  2

 /************************* WiFi Access Point *********************************/

@@ -61,15 +61,16 @@
 // higher the value.  The default for a 16mhz AVR is a value of 6.  For an
 // Arduino Due that runs at 84mhz a value of 30 works.
 // This is for the ESP8266 processor on ESP-01
-//DHT dht(DHTPIN, DHTTYPE, 15); // 15 works fine for ESP8266
+DHT dht(DHTPIN, DHTTYPE, 15); // 15 works fine for ESP8266
 /*************************** DHT Data   **************************************/
 //float humidity, temp_f;  // Values read from sensor Fº
-//float humidity, temp_c;  // Values read from sensor as Celsius
+float humidity, temp_c;  // Values read from sensor as Celsius
 //String webString = "";   // String to display
+String tempString = "";   // String to display
 /*************************** DHT Timing   ************************************/
 // Generally, you should use "unsigned long" for variables that hold time
-//unsigned long previousMillis = 0;        // will store last temp was read
-//const long interval = 2000;              // interval at which to read sensor
+unsigned long previousMillis = 0;        // will store last temp was read
+const long interval = 2000;              // interval at which to read sensor

 //void handle_root() {
 //  server.send(200, "text/plain", "Hello from the weather esp8266, read from /temp or /humidity");
@@ -97,10 +98,12 @@
 /****************************** Topics ***************************************/
 // Setup a feed called 'test' for publishing.
 // Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
-Adafruit_MQTT_Publish test_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/test");
+//Adafruit_MQTT_Publish test_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/test");
+Adafruit_MQTT_Publish temp_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temp");
 /****************************** Subscriptions*********************************/
 // Setup a feed called 'test' for subscribing to changes.
-Adafruit_MQTT_Subscribe test_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/test");
+//Adafruit_MQTT_Subscribe test_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/test");
+Adafruit_MQTT_Subscribe temp_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/temp");

 /***************************  MQTT Conn   ************************************/

@@ -168,14 +171,16 @@
   Serial.println("IP address: "); Serial.println(WiFi.localIP());

   // Setup MQTT subscription for onoff feed.
-  mqtt.subscribe(&test_subscription);
+  //mqtt.subscribe(&test_subscription);
+  mqtt.subscribe(&temp_subscription);
 }

-uint32_t x=0;    // Mock data
+//uint32_t x=0;    // Mock data

 /****************************** Loop  ***************************************/
 void loop(void)
 {
+  gettemperature() ;
   //server.handleClient();
   // Ensure the connection to the MQTT server is alive (this will make the first
   // connection and automatically reconnect when disconnected).  See the MQTT_connect
@@ -188,17 +193,24 @@
  /****************************** Subscript  ***********************************/
  Adafruit_MQTT_Subscribe *subscription;
   while ((subscription = mqtt.readSubscription(5000))) {
-    if (subscription == &test_subscription) {
-      Serial.print(F("Got: "));
-      Serial.println((char *)test_subscription.lastread);
+    //if (subscription == &test_subscription) {
+    if (subscription == &temp_subscription) {
+      //Serial.print(F("Got: "));
+      Serial.print(F("Got temp: "));
+      //Serial.println((char *)test_subscription.lastread);
+      Serial.println((char *)temp_subscription.lastread);
+
     }
   }
  /****************************** Publish  **********************************/
    // Now we can publish stuff!
-  Serial.print(F("\nSending test val "));
-  Serial.print(x);
+  //Serial.print(F("\nSending test val "));
+  //Serial.print(x);
+  Serial.print(F("\nSending temp val "));
+  Serial.print(temp_c);
   Serial.print("...");
-  if (! test_topic.publish(x++)) {
+  //if (! test_topic.publish(x++)) {
+   if (! temp_topic.publish(temp_c)) {
     Serial.println(F("Failed"));
   } else {
     Serial.println(F("OK!"));
@@ -242,7 +254,7 @@
 }

   /****************************** Get Data From DHTxx  ************************/
-  /*
+
 void gettemperature() {
   // Wait at least 2 seconds seconds between measurements.
   // if the difference between the current time and last time you read
@@ -266,6 +278,6 @@
       return;
     }
   }
- */
+}


parse local time in callback example

parse local time in callback example

--- examples/mqtt_esp8266_callback/mqtt_esp8266_callback.ino
+++ examples/mqtt_esp8266_callback/mqtt_esp8266_callback.ino
@@ -51,9 +51,47 @@

 /*************************** Sketch Code ************************************/

-void timecallback(uint32_t x) {
-  Serial.print("Hey we're in a time callback, the epoch time is: ");
-  Serial.println(x);
+int sec;
+int min;
+int hour;
+
+int timeZone = -4; // utc-4 eastern daylight time (nyc)
+
+void timecallback(uint32_t current) {
+
+  // adjust to local time zone
+  current += (timeZone * 60 * 60);
+
+  // calculate current time
+  sec = current % 60;
+  current /= 60;
+  min = current % 60;
+  current /= 60;
+  hour = current % 24;
+
+  // print hour
+  if(hour == 0 || hour == 12)
+    Serial.print("12");
+  if(hour < 12)
+    Serial.print(hour);
+  else
+    Serial.print(hour - 12);
+
+  // print mins
+  Serial.print(":");
+  if(min < 10) Serial.print("0");
+  Serial.print(min);
+
+  // print seconds
+  Serial.print(":");
+  if(sec < 10) Serial.print("0");
+  Serial.print(sec);
+
+  if(hour < 12)
+    Serial.println(" am");
+  else
+    Serial.println(" pm");
+
 }

 void slidercallback(double x) {
@@ -144,4 +182,4 @@
        }
   }
   Serial.println("MQTT Connected!");
-}+}


Added punctuation

Added punctuation


Fixed serial I/O to not drop commands.

Fixed serial I/O to not drop commands.

Also added debugging code to figure this out.

--- teensy-stim/teensy-stim.ino
+++ teensy-stim/teensy-stim.ino
@@ -8,12 +8,10 @@
 #define MHZ 72
 #define HTZ 72000000

-int lo = LOW;
-int hi = HIGH;
+#define LED_PIN 13

 #define DIG 24
 int digi[DIG] = { 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
-int led_is = 23;

 #define ANA 1
 int16_t wave[256];
@@ -128,7 +126,7 @@
   Dura s;    // Stimulus on time
   Dura z;    // Stimulus off time
   Dura p;    // Pulse time (or period, for analog)
-  Dura q;    // Pulse off time (analog: amplitude 0-2047 stored as microseconds)
+  Dura q;    // Pulse off time (analog: amplitude 0-2047)
   byte i;    // Invert? 'i' == yes, otherwise no
   byte j;    // Shape: 'l' = sinusoidal, 'r' = triangular, other = digital
   byte next; // Number of next protocol, 255 = none
@@ -228,16 +226,12 @@
   Dura pq;        // Time until next pulse status switch
   byte runlevel;  // Runlevel 0 = off, 1 = stim off, 2 = stim on pulse off, 3 = pulse on
   byte pin;       // The digital pin number for this output, or 255 = analog out
-  byte disabled;  // Channel will not run unless this has value 0
   byte who;       // Which protocol we're running now, 255 = none
   byte zero;      // Initial protocol to start at (used only for resetting), 255 = none
-  byte unused0;
-  byte unused1;
-  byte unused2;
   ChannelError e; // Error statistics

   void init(int index) {
-    *this = (Channel){ {0, 0}, {0, 0}, {0, 0}, 0, 0, 1, 255, 255, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0} };
+    *this = (Channel){ {0, 0}, {0, 0}, {0, 0}, C_ZZZ, 0, 255, 255, {0, 0, 0, 0, 0, 0, 0, 0} };
     pin = (index < DIG) ? digi[index] : 255;
     zero = (index < CHAN) ? index : 255;
   }
@@ -246,7 +240,6 @@
     e = (ChannelError){0, 0, 0, 0, 0, 0, 0, 0};
     t = yn = pq = (Dura){0, 0};
     runlevel = C_ZZZ;
-    disabled = 0;
     who = zero;
     while (who < PROT && ps[who].next < PROT) who = ps[who].next;
   }
@@ -269,27 +262,29 @@

   bool run_next_protocol(Protocol *ps, Dura d) {
     Protocol *p = ps + who;
-    pin_low();
+    pin_off(p);
     if (p->next < 255) {
       p = ps + p->next;
-      pin_off(ps);
+      pin_off(p);
       runlevel = C_WAIT;
       t = p->t; t += d;
       yn = p->d; yn += d;
     }
     else {
       who = 255;
+      digitalWrite(pin, LOW);
       runlevel = C_ZZZ;
-      disabled = 1;
       return false;
     }
   }
+
+  bool alive() { return runlevel != C_ZZZ && who != 255; }

   Dura advance(Dura d, Protocol *ps) {
     bool started_yn = false;
     bool started_pq = false;
 tail_recurse:
-    if (disabled || runlevel == C_ZZZ) return (Dura){0,0};
+    if (!alive()) return (Dura){0,0};
     if (runlevel == C_WAIT) {
       // Only relevant times are c->t and c->yn
       Dura *x = (yn < t) ? &yn : &t;
@@ -363,7 +358,7 @@

   static Dura advance(Channel *cs, Dura d, Protocol *ps) {
     Dura x = (Dura){0, 0};
-    for (int i = 0; i < DIG; i++) if (!cs[i].disabled) {
+    for (int i = 0; i < DIG; i++) if (cs[i].alive()) {
       Dura y = cs[i].advance(d, ps);
       if (!y.is_empty()) {
         if (x.is_empty() || y < x) x = y;
@@ -374,7 +369,7 @@
 };

 Channel channels[CHAN];
-Channel not_a_channel = (Channel){ {0, 0}, {0, 0}, {0, 0}, 0, 128, 1, 255, 255, 0, 0, 0, {0, 0, 0, 0, 0, 0, {0, 0}, {0, 0}}};
+Channel not_a_channel = (Channel){ {0, 0}, {0, 0}, {0, 0}, C_ZZZ, 128, 255, 255, {0, 0, 0, 0, 0, 0, {0, 0}, {0, 0}}};

@@ -389,6 +384,49 @@
  * Error and I/O buffers *
  *************************/

+#define YELLN 39
+int yelln = 0;
+
+void yell(const char* msg) {
+  int k = strlen(msg);
+  Serial.write(msg, k);
+  yelln += k;
+  if (yelln > YELLN) {
+    yelln = 0;
+    Serial.write("\n", 1);
+  }
+  Serial.send_now();
+}
+
+void yell2ib(int i, int j, const byte* text) {
+  char buffer[23+128+1];
+  snprintf(buffer, 23, "%d %d ", i, j);
+  int k = 0, l = 0;
+  while (l < 23 && buffer[l]) l++;
+  for (; k < j && k < 128 && text[k]; k++) buffer[l+k] = text[k];
+  buffer[l+k] = '\n';
+  buffer[l+k+1] = 0;
+  Serial.write(buffer, l+k+1);
+  Serial.send_now();
+}
+
+void yellr3d(int rl, Dura g, Dura n, Dura io) {
+  char buffer[54];
+  buffer[0] = '^';
+  snprintf(buffer+1, 5, "%d  ", rl);
+  g.write_15((byte*)buffer+4);
+  buffer[19] = ' ';
+  n.write_15((byte*)buffer+20);
+  buffer[35] = ' ';
+  n.write_15((byte*)buffer+36);
+  buffer[51] = '$';
+  buffer[52] = '\n';
+  buffer[53] = 0;
+  Serial.write(buffer,53);
+  Serial.send_now();
+}
+
+
 #define MSGN 62
 #define WHON 62
 #define BUFN 128
@@ -400,26 +438,35 @@
 byte buf[BUFN];
 int bufi = 0;

-int shift_buffer(byte* buffer, int iN, int shift) {
-  if (shift > iN) return 0;
-  if (shift < 1) return iN;
-  for (int j = shift; j < iN; j++) buffer[j-shift] = buffer[shift];
-  return iN - shift;
-}
-
-int advance_command(byte* buffer, int i0, int iN) {
-  int i = i0;
-  while (i < iN) {
-    byte b = buffer[i];
+void discard(byte* buffer, int& iN, int shift) {
+  if (shift > iN) iN = 0;
+  else if (shift >= 1) {
+    for (int j = shift; j < iN; j++) buffer[j-shift] = buffer[j];
+    int result = iN - shift;
+    yell2ib(iN, result, buffer);
+    iN = result;
+  }
+}
+
+void discard_buf(int shift) { discard(buf, bufi, shift); }
+
+void discard_command() {
+  int i = 1;
+  while (i < bufi) {
+    byte b = buf[i];
     if (b == '~' || b == '^') break;
     i++;
   }
-  return shift_buffer(buffer, iN, i);
+  discard(buf, bufi, i);
 }

 void drain_to_buf() {
   int av = Serial.available();
-  while ((av--) > 0 && bufi < BUFN) buf[bufi++] = Serial.read();
+  if (av > 0) {
+    int old = bufi;
+    while ((av--) > 0 && bufi < BUFN) buf[bufi++] = Serial.read();
+    yell2ib(old, bufi, buf);
+  }
 }

 void write_from_msg() {
@@ -436,18 +483,6 @@
   int n = 0;
   for (; n < WHON && whoami[n] != 0; n++) msg[n] = whoami[n];
   Serial.write(msg, n);
-  Serial.send_now();
-}
-
-int yelln = 0;
-
-void yell(const char* msg) {
-  Serial.write(msg, strlen(msg));
-  yelln += 1;
-  if (yelln > 78) {
-    yelln = 0;
-    Serial.write("\n", 1);
-  }
   Serial.send_now();
 }

@@ -510,7 +545,7 @@
 Dura next_event;         // Time of next event.  Just busywait until then.

 #define MIN_BUSY_US 1000
-#define MAX_BUSY_US 10000
+#define MAX_BUSY_US 20000
 Dura io_anyway;          // Time at which you need to read I/O even if it may interfere with events

 #define LOCKED  -3
@@ -542,22 +577,21 @@
     runlevel = LOCKED;
     if (led_is_on) {
       led_is_on = false;
-      channels[led_is].pin_low();
+      digitalWrite(LED_PIN, LOW);
     }
     int found = 0;
     for (int i = 0; i < DIG; i++) {
       Channel *c = channels + i;
-      if (!c->disabled) {
-        c->who = c->zero;
-        Protocol *p = protocols + c->who;
-        c->pin_off(p);
-        c->t = p->t;
-        c->yn = p->d;
-        c->runlevel = C_WAIT;
-        if (found) next_event = next_event.or_smaller(p->d);
-        else next_event = p->d;
-        found += 1;
-      }
+      c->who = c->zero;
+      if (c->who == 255) continue;
+      Protocol *p = protocols + c->who;
+      c->pin_off(p);
+      c->t = p->t;
+      c->yn = p->d;
+      c->runlevel = C_WAIT;
+      if (found) next_event = next_event.or_smaller(p->d);
+      else next_event = p->d;
+      found += 1;
     }
     global_clock = (Dura){0, 0};
     io_anyway = global_clock;
@@ -629,8 +663,8 @@

 void process_error_command() {
   if (bufi < 2) return;
-  if (buf[0] != '~') {
-    bufi = advance_command(buf, (buf[0] == '^') ? 1 : 0, bufi);
+  if (buf[0] != '~') {
+    discard_command();
     return;
   }
   // Was a fixed-length command.  Pick out the meaningful ones.
@@ -641,14 +675,14 @@
     case '?': write_who_am_i(); break;
     default: break;
   }
-  bufi = shift_buffer(buf, bufi, 2);
+  discard_buf(2);
 }

 void process_complete_command() {
   if (bufi < 2) return;
   if (buf[0] != '~') {
     error_with_message("unknown command starting: ", (char*)buf, 1);
-    bufi = advance_command(buf, (buf[0] == '^') ? 1 : 0, bufi);
+    discard_command();
     return;
   }
   switch(buf[1]) {
@@ -661,11 +695,11 @@
     default:
       if (buf[1] >= 'A' && buf[1] <= 'Z' && buf[1] != 'Y') {
         if (bufi < 3) return;
-        if (buf[2] == '/') { shift_buffer(buf, bufi, 3); return; }
+        if (buf[2] == '/') { discard_buf(3); return; }
       }
       error_with_message("Command not valid (run complete): ", (char*)buf, 2);
   }
-  bufi = shift_buffer(buf, bufi, 2);
+  discard_buf(2);
 }

 void process_init_command() {
@@ -676,13 +710,15 @@
     if (i < bufi) {
       if (memcmp("IDENTITY", buf+1, 8) != 0) {
         error_with_message("Expected ^IDENTITY found:", (char*)buf, bufi);
+        discard_command();
         return;
       }
       ensure_eeprom_is(buf + 9, 8, i-1, WHON - 2);
-      bufi = shift_buffer(buf, bufi, i+1);
+      discard_buf(i+1);
     }
     else if (bufi >= WHON) {
       error_with_message("^ without $ in: ", (char*)buf, bufi);
+      discard_command();
     }
     return;
   }
@@ -707,7 +743,7 @@
             error_with_message("Bad =: ", (char*)buf, 53);
           }
         }
-        bufi = shift_buffer(buf, bufi, 56);
+        discard_buf(56);
         if (b == ':') process_start_running(ch);
         return;
         break;
@@ -731,13 +767,13 @@
             error_with_message("Bad duration format: ", (char*)buf, 11);
           }
         }
-        bufi = shift_buffer(buf, bufi, 11);
+        discard_buf(11);
         return;
       case 'a': /* TODO */ return;
       default:
         error_with_message("Channel command not valid (setting): ", (char*)buf, 3);
     }
-    bufi = shift_buffer(buf, bufi, 3);
+    discard_buf(3);
   }
   else {
     switch(b) {
@@ -750,7 +786,7 @@
       default:
         error_with_message("Command not valid (setting): ", (char*)buf, 2);
     }
-    bufi = shift_buffer(buf, bufi, 2);
+    discard_buf(2);
   }
 }

@@ -758,7 +794,7 @@
   if (bufi < 2) return;
   if (buf[0] != '~') {
     error_with_message("Channel command not valid(running): ", (char*)buf, 2);
-    bufi = advance_command(buf, (buf[0] == '^') ? 1 : 0, bufi);
+    discard_command();
     return;
   }
   byte b = buf[1];
@@ -780,7 +816,7 @@
       default:
         error_with_message("Channel command not valid (running): ", (char*)buf, 3);
     }
-    bufi = shift_buffer(buf, bufi, 3);
+    discard_buf(3);
   }
   else {
     switch(b) {
@@ -792,7 +828,7 @@
       default:
         error_with_message("Command not valid (running): ", (char*)buf, 2);
     }
-    bufi = shift_buffer(buf, bufi, 2);
+    discard_buf(2);
   }
 }

@@ -805,8 +841,10 @@
 // Setup runs once at reset / power on
 void setup() {
   runlevel = RUNSTOP;
+  ensure_eeprom_is((byte*)"stim1.0 ", 0, 8, 0);
   read_my_eeprom();
   process_reset();
+  for (int i = 0; i<DIG; i++) { pinMode(i, OUTPUT); digitalWrite(i, LOW); }
   Serial.begin(115200);
   ARM_DEMCR |= ARM_DEMCR_TRCENA;
   ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
@@ -817,8 +855,9 @@
   led_is_on = false;
   tick = ARM_DWT_CYCCNT;
   runlevel = RUNSET;
-  yell("S");
-}
+}
+
+int lastrun = -10;

 // Runs over and over forever (after setup() finishes)
 void loop() {
@@ -831,23 +870,25 @@
     urgent = true;
     if (runlevel == GOGOGO) {
       /* TODO */
-      yell("go");
     }
     else {
-      if (led_is_on) channels[led_is].pin_low();
-      else channels[led_is].pin_high();
+      if (led_is_on) digitalWrite(LED_PIN, LOW);
+      else digitalWrite(LED_PIN, HIGH);
       led_is_on = !led_is_on;
       delta = 0;
       switch(runlevel) {
-        case RUNSET: delta = (led_is_on) ? MHZ*100000 : MHZ*400000;
-        case RUNSTOP: delta = MHZ*1000000;
-        case ERRSTOP: delta = MHZ*100000;
-        case ERRDONE: delta = MHZ*100000;
-        default: delta = MHZ*1000;
+        case RUNSET:  delta = (led_is_on) ?   5000 :  495000; break;
+        case RUNSTOP: delta = (led_is_on) ? 100000 : 1900000; break;
+        case ERRSTOP: delta = (led_is_on) ?  10000 :   90000; break;
+        case ERRDONE: delta = (led_is_on) ?  10000 :  190000; break;
+        default:      delta = (led_is_on) ?  10000 :   40000; break;
       }
-      next_event += delta;
-      yell("L");
-    }
+      next_event += MHZ * delta;
+    }
+  }
+  if (runlevel == ERRSTOP) {
+    // Without analog I/O, can just stop immediately.
+    runlevel = ERRDONE;
   }
   if (!urgent || io_anyway < global_clock) {
     Dura soon = global_clock;
@@ -862,15 +903,15 @@
         case GOGOGO: process_runtime_command(); break;
         default: break;
       }
+      if (io_anyway < global_clock) yell("io");
       now = ARM_DWT_CYCCNT;
       delta = now - tick;
       tick = now;
       global_clock += delta;
       io_anyway = global_clock;
       io_anyway += MHZ * MAX_BUSY_US;
-      yell("p");
-    }
-    else yell("_");
-  }
-  delay(100);
-}
+    }
+  }
+  if (lastrun != runlevel) yellr3d(runlevel, global_clock, next_event, io_anyway);
+  lastrun = runlevel;
+}


Added estop publisher, fixed pin modes (#58)

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -38,6 +38,7 @@
 #include <victoria_nav_msgs/Odom2DRaw.h>
 #include <victoria_sensor_msgs/DistanceDisplacement1D.h>
 #include <victoria_sensor_msgs/EncoderCount.h>
+#include <victoria_sensor_msgs/EStop.h>
 #include <victoria_sensor_msgs/FobMode.h>
 #include <victoria_sensor_msgs/IMURaw.h>

@@ -149,6 +150,10 @@
 ros::Publisher ros_encoder_left_pub("encoder_left", &ros_encoder_left_msg);
 ros::Publisher ros_encoder_right_pub("encoder_right", &ros_encoder_right_msg);

+// EStop publisher
+victoria_sensor_msgs::EStop ros_estop_msg;
+ros::Publisher ros_estop_pub("estop", &ros_estop_msg);
+
 // Position of robot
 geometry_msgs::Pose2D pose;

@@ -165,6 +170,18 @@
 void setupTimerCallback(int callback_freq_hz, void (*callback)(void));

 void setup() {
+
+  // Setup pin configurations
+  pinMode(FOB_STOP_1_PIN, INPUT);
+  pinMode(FOB_STOP_2_PIN, INPUT);
+  pinMode(FOB_STOP_3_PIN, INPUT);
+  pinMode(FOB_STOP_4_PIN, INPUT);
+  pinMode(E_STOP_PIN, INPUT);
+  pinMode(BLINK_PIN, OUTPUT);
+
+  // Set to high to indicate teensy is alive
+  digitalWrite(BLINK_PIN, HIGH);
+
   // Register ros publishers
   ros_nh.advertise(ros_raw_odom_pub);
   ros_nh.advertise(ros_raw_imu_pub);
@@ -172,6 +189,7 @@
   ros_nh.advertise(ros_bumper_right_pub);
   ros_nh.advertise(ros_encoder_left_pub);
   ros_nh.advertise(ros_encoder_right_pub);
+  ros_nh.advertise(ros_estop_pub);
   ros_nh.advertise(ros_teensy_debug_pub);

   // Register ros subscribers
@@ -203,6 +221,9 @@

   int publish_encoder_info_freq_hz =
     ros_param_helper.getParam("publish_encoder_info_freq_hz", 10);
+
+  int publish_estop_info_freq_hz =
+    ros_param_helper.getParam("publish_estop_info_freq_hz", 10);

   int publish_teensy_debug_info_freq_hz =
     ros_param_helper.getParam("publish_teensy_debug_info_freq_hz", 1);
@@ -253,9 +274,6 @@

   // Start the TRex
   trex_err = startTRex();
-
-  // Setup pin configurations
-  pinMode(BLINK_PIN, OUTPUT);

   // Setup Timer callbacks
   setupTimerCallback(read_encoders_freq_hz, doReadEncoders);
@@ -264,6 +282,7 @@
   setupTimerCallback(publish_raw_imu_freq_hz, doPublishRawImu);
   setupTimerCallback(publish_bumper_info_freq_hz, doPublishBumpers);
   setupTimerCallback(publish_encoder_info_freq_hz, doPublishEncoders);
+  setupTimerCallback(publish_estop_info_freq_hz, doPublishEStop);
   setupTimerCallback(publish_teensy_debug_info_freq_hz, doTeensyDebug);
   setupTimerCallback(BLINK_FREQ_HZ, doBlink);

@@ -632,6 +651,14 @@
   ros_encoder_right_pub.publish(&ros_encoder_right_msg);
 }

+/**
+ * Publish estop data to ros.
+ */
+void doPublishEStop(void) {
+  ros_estop_msg.stopped = external_stop;
+  ros_estop_pub.publish(&ros_estop_msg);
+}
+
 /*
  * Sets the speed for the motors. Values are expected
  * to be between -1 and 1. Values outside this range


prettied up

prettied up

--- arduino/ws2812_controller_esp32/ws2812_controller_esp32.ino
+++ arduino/ws2812_controller_esp32/ws2812_controller_esp32.ino
@@ -23,10 +23,10 @@
 unsigned int localPort = 7777;
 char packetBuffer[BUFFER_LEN];

-// LED strip
-NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> ledstrip(NUM_LEDS, PixelPin);
+uint8_t N = 0;

 WiFiUDP port;
+NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> ledstrip(NUM_LEDS, PixelPin);

 void setup() {
     Serial.begin(115200);
@@ -47,7 +47,6 @@
     ledstrip.Show();//Clear the strip for use
 }

-uint8_t N = 0;
 #if PRINT_FPS
     uint16_t fpsCounter = 0;
     uint32_t secondTimer = 0;


Switching to LCD display

Switching to LCD display

--- sketches/WeatherPod/WeatherPod.ino
+++ sketches/WeatherPod/WeatherPod.ino
@@ -1,33 +1,194 @@
+
+/**
+ * Libraries used in this WeatherPod:
+ *
+ * 		Wire
+ * 		Time
+ * 		DHT
+ * 		Adafruit_BMP085_Unified
+ * 		Adafruit_Sensor
+ * 		DS1307RTC
+ * 		LiquidCrystal_I2C2004V1
+ * 		SimpleTimer
+ *
+ *
+ *
+ *
+ * 		By carefully watching the pressure on a barometer, you can forecast local weather
+ * 		using these simple guidelines:
+ *
+ * 			Decreasing barometric pressure indicates storms, rain and windy weather.
+ *
+ * 			Rising barometric pressure indicates fair, dry, and colder weather.
+ *
+ * 			Slow, regular and moderate falls in pressure suggest a low pressure
+ *			area is passing some distance away. Marked changes in the weather are unlikely.
+ *
+ * 			Small rapid decreases in pressure indicate a nearby change in weather.
+ *			They are usually followed by short lasting wind and showers.
+ *
+ * 			A quick drop in pressure over a short time indicates a storm is likely in 5
+ * 			to 6 hours.
+ *
+ * 			Large, slow and sustained decreasing pressure forecasts a long period of
+ *			poor weather. The weather will be more pronounced if the pressure started
+ *			rising before it began to drop.
+ *
+ * 			A rapid rise in pressure, during fair weather and average, or above average
+ *			pressure, indicates a low pressure cell is approaching. The pressure will
+ *			soon decrease forecasting poorer weather.
+ *
+ * 			Quickly rising pressure, when the pressure is low, indicates a short period
+ *			of fair weather is likely.
+ *
+ * 			A large, slow and sustained rise in pressure forecasts a long period of good
+ *			weather is on its way.
+ *
+			Definition of Pressure Tendency Terms
+
+			Term							Pressure Tendency Over 3 Hours
+			Steady							Less than 0.1 mb
+			Rising or falling slowly		0.1 to 1.5 mb
+			Rising or falling				1.6 to 3.5 mb
+			Rising or falling quickly		3.6 to 6.0 mb
+			Rising or falling very rapidly	More than 6.0 mb
+ *
+ */
+
 #include <Arduino.h>
-#include <SparkfunSerial7SD.h>
 #include <SimpleTimer.h>
+#include <DS1307RTC.h>
+#include <LiquidCrystal_I2C.h>

 #define DHTTYPE DHT22   // DHT 22  (AM2302)
-
 #include <DHT.h>
-
-const uint8_t pinDHT = 2, pin7Segment = 7;
-DHT dht(pinDHT, DHTTYPE);
-SparkfunSerial7SD SevenSegment(pin7Segment);
-
 #include <Wire.h>
 #include <Adafruit_Sensor.h>
 #include <Adafruit_BMP085_U.h>
-
+#include <Time.h>
+
+#define DEGREE_SYMBOL (char)223
+
+#define LOW_PRESSURE 1002
+#define HIGH_PRESSURE 1020
+
+const uint8_t pinDHT = 2, pin7Segment = 7;
+DHT dht(pinDHT, DHTTYPE);
+LiquidCrystal_I2C lcd(0x3F, 20, 4);
 Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
 SimpleTimer timer(1);
+
+uint16_t hourlyPressure[24];

 typedef struct configStruct  {
 	uint16_t pause;
 	float temperatureDHTinF;
 	float temperatureBMPinF;
 	float pressureInches;
+	float pressureMb;
 	float humidityPercent;
 } configType;

-char buffer[10];
-configType config = { 3000 };
-
+typedef struct displayStruct {
+	char row[4][20];
+} displayType;
+
+char buffer[20];
+displayType display;
+configType config = { 10 };
+
+
+/**********************************************************************************
+ *
+ * Utilities
+ */
+
+char *ftoa(char *a, double f, int precision) {
+  long p[] = {0,10,100,1000,10000,100000,1000000,10000000,100000000};
+
+  char *ret = a;
+  long heiltal = (long)f;
+  itoa(heiltal, a, 10);
+  while (*a != '\0') a++;
+  *a++ = '.';
+  long desimal = abs((long)((f - heiltal) * p[precision]));
+  itoa(desimal, a, 10);
+  return ret;
+}
+
+/**********************************************************************************
+ *
+ * Display routines
+ *
+ */
+time_t getTime() {
+	time_t t;
+
+	if ((t = RTC.get())) {
+		sprintf(display.row[0], "%02d/%02d/%4d %02d:%02d:%02d",
+				month(t),
+				day(t),
+				year(t),
+				hour(t),
+				minute(t),
+				second(t)
+				);
+
+		// save the value for this hour
+		hourlyPressure[hour(t)] = config.pressureMb;
+	} else {
+		if (RTC.chipPresent()) {
+			sprintf(display.row[0], "Must init time chip!");
+		} else {
+			sprintf(display.row[0], "Time chip not found.");
+		}
+	}
+	return t;
+}
+
+
+void displayReadings(int timerId) {
+	time_t t = getTime();
+
+	lcd.setCursor(0,0);
+
+	sprintf(display.row[1], "Humidity: %d%%", (int) config.humidityPercent);
+
+	char temp1[20];
+	char temp2[30];
+
+	ftoa(temp1, config.pressureMb, 1);
+
+	// now check the difference in the last 3 hours
+	int hourToCompare = hour(t) - 3; // 3 behind
+	if (hourToCompare < 0)
+		hourToCompare = 24 + hourToCompare; // handle midnight
+
+	float delta = config.pressureMb - hourlyPressure[hourToCompare];
+	sprintf(temp2, "%s", (delta > 0 ? "^" : "V"));
+	sprintf(display.row[2], "Air: %smb (%s)", temp1, temp2);
+
+	float tmp = (config.temperatureBMPinF + config.temperatureDHTinF) / 2.0;
+
+	char temp[20];
+	ftoa(temp, 5.0 / 9.0 * (tmp - 32.0), 1);
+	ftoa(buffer, tmp, 1);
+
+	sprintf(display.row[3], "Temp: %s%cF %s%cC", buffer,
+		DEGREE_SYMBOL, temp,
+		DEGREE_SYMBOL);
+
+	for (int i = 0; i < 4; i++) {
+		lcd.setCursor(0,i);
+		lcd.print(display.row[i]);
+		Serial.println(display.row[i]);
+	}
+	Serial.println(F("====================================="));
+}
+/**********************************************************************************
+ *
+ * Sensor readings routines
+ */

 void readBMP(int timerId) {
 	sensors_event_t event;
@@ -35,6 +196,7 @@

 	/* Display the results (barometric pressure is measure in hPa) */
 	if (event.pressure) {
+		config.pressureMb = event.pressure;  // hPa
 		config.pressureInches = hPa2inHg(event.pressure);
 		float temperature;
 		bmp.getTemperature(&temperature);
@@ -61,57 +223,35 @@
 	config.temperatureDHTinF = f;
 }

-void displayTemperatureBMP(int timerId) {
-	SevenSegment.printUnits(config.temperatureBMPinF, "F");
-}
-void displayTemperatureDHT(int timerId) {
-	SevenSegment.printUnits(config.temperatureDHTinF, "F");
-}
-
-void displayPressure(int timerId) {
-	SevenSegment.printUnits(config.pressureInches, "i");
-}
-
-void displayHumiduty(int timerId) {
-	SevenSegment.printUnits(config.humidityPercent, "h");
-}
-
-
+/**********************************************************************************
+ *
+ * Arduino Callbacks
+ */
 void setup() {
 	Serial.begin(9600); //Setup the debug terminal at regular 9600bps
-	Serial.println("OpenSegment Example Code");

 	dht.begin();
 	bmp.begin();

-	SevenSegment.init();
-	SevenSegment.setBaud(57600);
-	SevenSegment.setBrignessPercent(20);
-
-	timer.setInterval(3000, &readBMP);
-	delay(1000);
-	timer.setInterval(3000, &readDHT);
-
+	lcd.init();
+	lcd.backlight();
+	lcd.setCursor(0, 0);
+
+	memset(&display, 0x0, sizeof(displayType));
+	memset(&hourlyPressure, 0x0, sizeof(hourlyPressure)*sizeof(uint16_t));
+
+	Serial.print("Resetting memory structures.");
+	Serial.println(sizeof(displayType));
+	Serial.println(sizeof(hourlyPressure) * sizeof(uint16_t));
+
+	timer.setInterval(2000, &readBMP);
+	delay(500);
+	timer.setInterval(2000, &readDHT);
+	delay(500);
+	timer.setInterval(1000, &displayReadings);
 }

 void loop() {
 	timer.run();
-
-	displayTemperatureBMP(1);
 	delay(config.pause);
-
-	timer.run();
-
-	displayHumiduty(1);
-	delay(config.pause);
-
-	timer.run();
-
-	displayTemperatureDHT(1);
-	delay(config.pause);
-
-	timer.run();
-
-	displayPressure(1);
-	delay(config.pause);
-}
+}


Changing variable name

Changing variable name

--- Arduino/weather-tree.ino
+++ Arduino/weather-tree.ino
@@ -32,7 +32,7 @@
     randomSeed(analogRead(0));

     Spark.function("snow", snow);
-    Spark.function("noPercipitation", noPercipitation);
+    Spark.function("none", noPercipitation);
 }


Fix power pin options

Fix power pin options

--- src/Full_decoder/Full_decoder.ino
+++ src/Full_decoder/Full_decoder.ino
@@ -89,7 +89,7 @@
         speed = eeprom_read_word((uint16_t*)&(_CV.conf[slot].servo.speed));
         fbslot1  = eeprom_read_word((uint16_t*)&(_CV.conf[slot].servo.fbslot1));
         fbslot2  = eeprom_read_word((uint16_t*)&(_CV.conf[slot].servo.fbslot2));
-        powerpin = eeprom_read_word((uint16_t*)&(_CV.conf[slot].servo.pwrslot)) && 0xFF;
+        powerpin = eeprom_read_word((uint16_t*)&(_CV.conf[slot].servo.pwrslot));
         confpins[slot] = new ServoSwitch(slot, pin, address, pos1, pos2, speed, powerpin, fbslot1, fbslot2);
         confpins[slot]->restore_state(eeprom_read_word((uint16_t*)&(_CV.conf[slot].servo.state)));
         break;


Example AudioPassThru_wEarpieces: added text describing trouble-shooting if you can't hear anything

--- examples/09-Earpieces/AudioPassThru_wEarpieces/AudioPassThru_wEarpieces.ino
+++ examples/09-Earpieces/AudioPassThru_wEarpieces/AudioPassThru_wEarpieces.ino
@@ -18,6 +18,21 @@
  * is working.  That's what this example here is for.  But, once you are beyond this basic
  * example, we strongly recommend that you use the EarpieceMixer.  For an example, of the
  * EarpieceMixer class, see "TrebleBoost_wComp_wEarpieces_wApp"
+ *
+ * BE AWARE: Since this example has no amplification, it sounds very quiet if you listen through
+ * the earpieces.  Very quiet.  If you cannot hear audio through your earpieces, please consider:
+ *
+ *    * Plug headphones into the headphone jack of your Tympan or of your Earpiece shield.  Rub
+ *      the earpiece mics with your finger.  Do you hear it through the headphones?
+ *
+ *    * Listening through the earpiece again, rub the earpiece mics with your finger.  Do you
+ *      hear it through the earpiece?  Try unplugging the earpiece from the Tympan to really
+ *      hear what it sounds like unampflied.  Then, plug the earpiece in and listen again?
+ *
+ *    * Try turning up the output loudness on the Tympan (ie, add some gain!).  Find the line
+ *      "earpieceShield.volume_dB(0.0);"  Change the 0.0 to 10.0 or even to 20.0.  That'll add
+ *      a lot of gain.  Because you've added gain, it's no longer "AudioPassThru", but you
+ *      should more easily hear the output.
  *
  * License: MIT License, Use At Your Own Risk
  *


Different instructions for ooa updates.

Different instructions for ooa updates.

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@17094 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/zcommand.ino
+++ zimodem/zcommand.ino
@@ -1047,7 +1047,7 @@
   }
   serial.prints("Done");
   serial.prints(EOLN);
-  serial.prints("Please wait for modem to restart...");
+  serial.prints("Modem will now restart. If restart fails, you might need to power-cycle or reset your modem.");
   ESP.restart();
   return ZOK;
 }