Parameterize fixes for MCCI BSP limitations; 2.5.0.10 fixes USB

--- examples/compliance-otaa-halconfig/compliance-otaa-halconfig.ino
+++ examples/compliance-otaa-halconfig/compliance-otaa-halconfig.ino
@@ -706,53 +706,54 @@
     }
 }

+#define NEED_USBD_LL_ConnectionState    0
+#ifdef ARDUINO_ARCH_STM32
+# ifdef _mcci_arduino_version
+#  if _mcci_arduino_version < _mcci_arduino_version_calc(2, 5, 0, 10)
+#   undef NEED_USBD_LL_ConnectionState
+#   define NEED_USBD_LL_ConnectionState 1
+#  endif // _mcci_arduino_version < _mcci_arduino_version_calc(2, 5, 0, 10)
+# endif // def _mcci_arduino_version
+#endif // def ARDUINO_ARCH_STM32
+
+#define NEED_STM32_ClockCalibration    0
+#ifdef ARDUINO_ARCH_STM32
+# ifdef _mcci_arduino_version
+#  if _mcci_arduino_version <= _mcci_arduino_version_calc(2, 5, 0, 10)
+#   undef NEED_STM32_ClockCalibration
+#   define NEED_STM32_ClockCalibration 1
+#  endif // _mcci_arduino_version <= _mcci_arduino_version_calc(2, 5, 0, 10)
+# endif // def _mcci_arduino_version
+#endif // def ARDUINO_ARCH_STM32
+
+
 // there's a problem with running 2.5 of the MCCI STM32 BSPs;
 // hack around it.
-#ifdef ARDUINO_ARCH_STM32
-# ifdef _mcci_arduino_version
-#  if _mcci_arduino_version <= _mcci_arduino_version_calc(2, 5, 0, 0)
+#if NEED_USBD_LL_ConnectionState
 uint32_t USBD_LL_ConnectionState(void) {
   return 1;
 }
-#  endif // _mcci_arduino_version
-# endif // defined(_mcci_arduino_version)
-#endif // ARDUINO_ARCH_STM32
-
-#ifdef ARDUINO_ARCH_STM32
-# if defined(_mcci_arduino_version)
-#  if _mcci_arduino_version >= _mcci_arduino_version_calc(2,4,0,90)
+#endif // NEED_USBD_LL_ConnectionState
+
+#if NEED_STM32_ClockCalibration
         static constexpr bool kUsesLSE = true;          // _mcci_arduino_version indicates that LSE clock is used.
-#  else
-        // versions before 2.4.0.90 use LSI clock. Can't calibrate.
-        static constexpr bool kUsesLSE = false;         // _mcci_arduino_version defined, too small
-#  endif
-# else
-        // versions before 2.4.0.90 use LSI clock. Can't calibrate.
-        static constexpr bool kUsesLSE = false;         // _mcci_arduino_version not defined
-# endif
 #else
         static constexpr bool kUsesLSE = false;
 #endif

 void setup_calibrateSystemClock(void) {
-#ifdef ARDUINO_ARCH_STM32
-# ifdef _mcci_arduino_version
-#  if _mcci_arduino_version <= _mcci_arduino_version_calc(2, 5, 0, 0)
     if (kUsesLSE) {
         Serial.println("need to calibrate clock");
+#if NEED_STM32_ClockCalibration
         Stm32_CalibrateSystemClock();
+#endif // NEED_STM32_ClockCalibration
     } else {
         Serial.println("calibration not supported");
     }
-#  endif // _mcci_arduino_version
-# endif // defined(_mcci_arduino_version)
-#endif // ARDUINO_ARCH_STM32
-}
-
-#ifdef ARDUINO_ARCH_STM32
-# ifdef _mcci_arduino_version
-#  if _mcci_arduino_version <= _mcci_arduino_version_calc(2, 5, 0, 0)
+}
+
+#if NEED_STM32_ClockCalibration

 // RTC needs to be initialized before we calibrate the clock.
 bool rtcbegin() {
@@ -1144,6 +1145,4 @@
     /* return the delta */
     return end - start;
     }
-#  endif // _mcci_arduino_version
-# endif // defined(_mcci_arduino_version)
-#endif // ARDUINO_ARCH_STM32
+#endif // NEED_STM32_ClockCalibration


Update evcharging.ino

Update evcharging.ino

--- particle/evcharging.ino
+++ particle/evcharging.ino
@@ -5,6 +5,7 @@
 int button = D6;
 char PIN[8] = {B3, B2, B1, B0, D3, D2, D1, D0};
 int carRead[8];
+double previousCharge[8] = {0, 0, 0, 0, 0, 0, 0, 0};
 double channelMaxCharge[8];
 int channelSupplyCharge[8];

@@ -77,29 +78,41 @@
         }
     }

+    for (i = 0; i < 8; i++) {
+        if (channelMaxCharge[i] == 0) {
+            analogWrite(PIN[i], 0);
+        }
+    }
+
     // Print out the measured rates for debugging purposes
+    /*
     for (i = 0; i < 8; i++) {
         Serial.println(channelMaxCharge[i]);
     }
+    */

     // At this point, the max rate of charge for each car has been measured
     // 0 means that there isn't a car connected
     // If the button is not pressed, it will loop

-    if (button == LOW) {    // if the button is pressed
+    if (digitalRead(D6) == LOW) {    // if the button is pressed
         // Send request to create a new charging session
         // Pass the data from channelMaxCharge[]
-        String temp = "";
+
+        Serial.println("button press");
+
+        digitalWrite(D7, HIGH);
+
         for (i = 0; i < 8; i++) {
-            String num = String(channelMaxCharge[i]);
-            temp.concat(num);
-            if (i != 7) {
-                temp.concat(",");
+            if ((previousCharge[i] == 0 && channelMaxCharge[i] != 0) || (previousCharge[i] != 0 && channelMaxCharge[i] == 0)) {
+                String data = String("{\"pinId\": " + String(i) + ", \"maxChargeRate\": " + String(channelMaxCharge[i]) + "}");
+                newSession(data);
+                previousCharge[i] = channelMaxCharge[i];
             }
         }
-        newSession(temp);

-        delay(250);     // 250ms delay
+        delay(1000);    // 1s delay
+        digitalWrite(D7, LOW);
     }

     delay(0.5); // 500us delay
@@ -108,6 +121,7 @@
 int newSession(String data) {
     // Trigger the new charging session
     Serial.println("creating a new charging session");
+    Serial.println(data);
     Particle.publish("new_session", data, PRIVATE);
     return 1;
 }


devirtualised RFM23BLink interrupt

devirtualised RFM23BLink interrupt

--- Arduino/hardware/REV10/REV10MessagePathTest/REV10SecureBHR/REV10SecureBHR.ino
+++ Arduino/hardware/REV10/REV10MessagePathTest/REV10SecureBHR/REV10SecureBHR.ino
@@ -75,14 +75,8 @@
 static constexpr uint8_t RFM23B_RX_QUEUE_SIZE = OTRFM23BLink::DEFAULT_RFM23B_RX_QUEUE_CAPACITY;
 static constexpr int8_t RFM23B_IRQ_PIN = PIN_RFM_NIRQ;
 static constexpr bool RFM23B_allowRX = true;
-OTRFM23BLink::OTRFM23BLink<OTV0P2BASE::V0p2_PIN_SPI_nSS, RFM23B_IRQ_PIN, RFM23B_RX_QUEUE_SIZE, RFM23B_allowRX> RFM23B;
-OTSIM900Link::OTSIM900Link<8, 5, RADIO_POWER_PIN, OTV0P2BASE::getSecondsLT> SIM900; // (REGULATOR_POWERUP, RADIO_POWER_PIN);
-
-// Assigns radio to PrimaryRadio alias
-OTRadioLink::OTRadioLink &PrimaryRadio = RFM23B;
-
-// Assign radio to SecondaryRadio alias.
-OTRadioLink::OTRadioLink &SecondaryRadio = SIM900;
+OTRFM23BLink::OTRFM23BLink<OTV0P2BASE::V0p2_PIN_SPI_nSS, RFM23B_IRQ_PIN, RFM23B_RX_QUEUE_SIZE, RFM23B_allowRX> PrimaryRadio;
+OTSIM900Link::OTSIM900Link<8, 5, RADIO_POWER_PIN, OTV0P2BASE::getSecondsLT> SecondaryRadio; // (REGULATOR_POWERUP, RADIO_POWER_PIN);

 /////// SENSORS

@@ -209,7 +203,7 @@
     return (OTRadioLink::decodeAndHandleOTSecureOFrameWithWorkspace<OTRadioLink::SimpleSecureFrame32or0BodyRXV0p2,
                                                     OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleDec_DEFAULT_WITH_LWORKSPACE,
                                                    OTV0P2BASE::getPrimaryBuilding16ByteSecretKey,
-                                                   OTRadioLink::relayFrameOperation<decltype(SIM900), SIM900>,
+                                                   OTRadioLink::relayFrameOperation<decltype(SecondaryRadio), SecondaryRadio>,
                                                    OTRadioLink::boilerFrameOperation<decltype(BoilerHub), BoilerHub, minuteCount>
                                                   >(msg, sW));
 }
@@ -234,7 +228,7 @@
     // Handler routine not required/expected to 'clear' this interrupt.
     // TODO: try to ensure that OTRFM23BLink.handleInterruptSimple() is inlineable to minimise ISR prologue/epilogue time and space.
     if((changes & RFM23B_INT_MASK) && !(pins & RFM23B_INT_MASK))
-        { PrimaryRadio.handleInterruptSimple(); }
+        { PrimaryRadio._handleInterruptNonVirtual(); }
 }

 // Previous state of port D pins to help detect changes.


fixed two messages

fixed two messages

--- examples/UbidotsSaveMultiValues/UbidotsSaveMultiValues.ino
+++ examples/UbidotsSaveMultiValues/UbidotsSaveMultiValues.ino
@@ -9,8 +9,6 @@
 #define USER "Your_username_here"  // If your apn doesnt have username just put ""
 #define PASS "Your_password_here"  // If your apn doesnt have password just put ""
 #define TOKEN "Your_token_here"  // Replace it with your Ubidots token
-#define ID "Your_id_here" // Replace it with your Ubidots' variable ID
-// You can send 1 to 10 variable at the same time
 #define VARIABLE_NAME_ONE "Your_variable_name_here"
 #define VARIABLE_NAME_TWO "Your_variable_name_here"
 #define VARIABLE_NAME_THREE "Your_variable_name_here"


changed glass to have slider function

changed glass to have slider function

--- glass/glass.ino
+++ glass/glass.ino
@@ -13,6 +13,7 @@
 #define VERIFY 4
 #define CONNECTED 5
 #define SOFTPOT_THREASHOLD 950
+#define SOFTPOT_DELTA_THREASHOLD 111
 #define DELAY_IN_WAIT 1000000
 unsigned long session_id = 0xA90;

@@ -23,11 +24,31 @@
 int ledPin = 8;
 int state = 0;
 int softpotReading = 0;
+int softpotInitV = 0;
+int delta_threshold = 0;
+int changes = 0;
 struct XBeePacket XBeePacketArr[20];
 volatile int XBeePacketCounter;
 volatile int selectedXBee;
 unsigned long start_time;
+unsigned long last_release_time;
+bool released;
+bool pressed;
 unsigned long end_time;
+
+
+int readXBeeString (char *strArray) {
+  int i = 0;
+  if(!XBee.available()) {
+    return -1;
+  }
+  while (XBee.available()) {
+    strArray[i] = XBee.read();
+    i++;
+  }
+  strArray[i] = '\0';
+  return i;
+}

 void setup()
 {
@@ -38,6 +59,53 @@
   digitalWrite(ledPin, LOW);
   XBee.begin(9600);
   XBeePacketCounter = 0;
+  pressed = false;
+  released = false;
+  last_release_time = 0;
+}
+
+// void test slider detection
+void loop3() {
+  delay(10);
+  int delta_threshold = SOFTPOT_DELTA_THREASHOLD;
+  if (XBeePacketCounter > 5) {
+    // this happens really rare
+    // you will only have 800 of the whole slider to use
+    // then each step is 800/XBeePacketCounter
+    delta_threshold = 800/XBeePacketCounter;
+  }
+
+  softpotReading = analogRead(softpotPin);
+
+  Serial.print("Softpot Reading: ");
+  Serial.println(softpotReading);
+
+  if (softpotReading < SOFTPOT_THREASHOLD){
+    // tapped on
+    pressed = true;
+  }
+
+  // should detect double click here:
+  if (pressed == true && softpotReading > SOFTPOT_THREASHOLD) {
+    // hand left, expected to have double tap
+    // bug is the release time is updated every time here
+    last_release_time = millis();
+    Serial.println("pressed");
+    released = true;
+    pressed = false;
+  }
+  if (released == true && softpotReading < SOFTPOT_THREASHOLD) {
+    // detect if tapped again in a timely fashion
+    unsigned long new_press_time = millis();
+    if (new_press_time - last_release_time < 300) {
+      // definitely timeout
+      Serial.println("tap event detected");
+      delay(4000);
+      released = false;
+      pressed = false;
+    }
+
+  }
 }

 void loop() {
@@ -50,6 +118,8 @@
     if (softpotReading < SOFTPOT_THREASHOLD) {
       Serial.println("[INIT] Entering");
       state = INIT;
+      softpotInitV = softpotReading;
+      pressed = true;
     }
     selectedXBee = -1;
     break;
@@ -90,8 +160,10 @@
       else {
 	// there are multiple repliers, need to adjust
 	// sort the received Id or actually no need if we have TDMA
-
-	// complex part to implement, take a coffee and then start
+
+	// complex part to implement, take a coffee and then start
+	selectedXBee = XBeePacketCounter / 2;
+	released = false;
 	state = VERIFY;
       }
     }
@@ -119,19 +191,52 @@
   case CONFIRM:
     // send out the signal to THE selected XBee
     // WAIT for the confirmation message to arrive
-
     state = CONNECTED;
     break;
   case VERIFY:
     // when there are multiple targets who have responded
     // one of the LED should be on at this case
-    Serial.println("[VERIFY] Detecting gestures");
-
+    Serial.print("[VERIFY] now trying id=");
+    Serial.println(selectedXBee);
+    sendXBeePacketFromRaw(&XBee, XBeePacketArr[selectedXBee].id, "v", XBeePacketArr[selectedXBee].data);
+
+    // configure the slider dynamically
+    delta_threshold = SOFTPOT_DELTA_THREASHOLD;
+    changes = 0;
+    if (XBeePacketCounter > 5) {
+      // this happens really rare
+      // you will only have 800 of the whole slider to use
+      // then each step is 800/XBeePacketCounter
+      delta_threshold = 800/XBeePacketCounter;
+    }
+
     softpotReading = analogRead(softpotPin);
-
-    // digitalWrite(ledPin, HIGH);
-    // then based on the gesture, we start to rotate them
-    state = CONNECTED;
+    if (softpotReading < SOFTPOT_THREASHOLD){
+      // still in hold
+      pressed = true;
+    }
+
+    // should detect double click here:
+    if (pressed == true && softpotReading > SOFTPOT_THREASHOLD) {
+      // hand left, expected to have a tap
+      last_release_time = millis();
+      pressed = false;
+      released = true;
+    }
+    if (released == true && softpotReading < SOFTPOT_THREASHOLD) {
+      // detect if tapped again in a timely fashion
+      unsigned long new_release_time = millis();
+      if (new_release_time - last_release_time < 400) {
+	// definitely timeout
+	Serial.println("tap event detected");
+	sendXBeePacketFromRaw(&XBee, XBeePacketArr[selectedXBee].id, "c", XBeePacketArr[selectedXBee].data);
+	state = CONNECTED;
+      }
+    }
+
+    changes = (softpotReading - softpotInitV) / delta_threshold;
+    selectedXBee += changes;
+
     break;
   case CONNECTED:


Refactored logic for choosing which pixels are light around pendulum

Refactored logic for choosing which pixels are light around pendulum

--- goggles9dof.ino
+++ goggles9dof.ino
@@ -14,10 +14,10 @@
 #include <FastLED.h>

-#define DATAPIN_LEFT    6
-#define CLOCKPIN_LEFT   9
-#define DATAPIN_RIGHT    0
-#define CLOCKPIN_RIGHT   1
+#define DATAPIN_LEFT    0
+#define CLOCKPIN_LEFT   1
+#define DATAPIN_RIGHT    6
+#define CLOCKPIN_RIGHT   9
 #define NUM_LEDS 21 //Number of LEDS per lense

 CRGB leftLense[NUM_LEDS];
@@ -34,18 +34,18 @@

 // Tuning constants. (a.k.a. "Fudge Factors)
 // These can be tweaked to adjust the liveliness and sensitivity of the eyes.
-const float friction = 0.999; // frictional damping constant.  1.0 is no friction.
-const float swing = 60;  // arbitrary divisor for gravitational force
-const float gravity = 200;  // arbitrary divisor for lateral acceleration
+const float friction = 0.985; // frictional damping constant.  1.0 is no friction.
+const float swing = 20;  // arbitrary divisor for gravitational force
+const float gravity = 100;  // arbitrary divisor for lateral acceleration
 const float nod = 7.5; // accelerometer threshold for toggling modes

 long nodStart = 0;
 long nodTime = 2000;

-bool antiGravity = true;  // The pendulum will anti-gravitate to the top.
+bool antiGravity = false;  // The pendulum will anti-gravitate to the top.
 bool mirroredEyes = false; // The left eye will mirror the right.

-const float halfWidth = 2.0; // half-width of pupil (in pixels)
+const float halfWidth = 2; // half-width of pupil (in pixels)

 // Pi for calculations - not the raspberry type :: 1.25
 const float Pi = 3.14159;
@@ -78,7 +78,7 @@

    // Try to initialise and warn if we couldn't detect the chip
   if (!lsm.begin()) {
-//    Serial.println("Oops ... unable to initialize the LSM9DS0. Check your wiring!");
+    Serial.println("Oops ... unable to initialize the LSM9DS0. Check your wiring!");
     while (1);
   }
   setupSensor();
@@ -86,8 +86,7 @@
 }

 // main processing loop
-void loop(void)
-{
+void loop(void) {
    // Read the magnetometer and determine the compass heading:
    lsm.getEvent(&accel, &mag, &gyro, &temp);

@@ -97,7 +96,8 @@
    // Calculate the angle of the vector z,x from magnetic North
 //   float heading = atan2(mag.magnetic.x,mag.magnetic.z) * (180 / Pi);
     float heading = orientation.heading;
-
+//    Serial.print("Heading");
+//    Serial.println(heading);
    // Normalize to 0-360 for a compass heading
    if (heading < 0) {
       heading = 360 + heading;
@@ -134,45 +134,46 @@
    while (round(pos) < 0) pos += 21.0;
    while (round(pos) > 20) pos -= 21.0;

-   // Now re-compute the display
+   CRGB color = selectColor(heading);
+
+
+   int lightOn[round(halfWidth*2 + 1)] = {0,1,2,3};
+   int lightIndex = 0;
+   for(int i = pos;i>pos-halfWidth;i--) {
+     lightOn[lightIndex] = wrapAround(i);
+     lightIndex++;
+   }
+   for(int i=pos;i<pos+halfWidth;i++) {
+     lightOn[lightIndex] = wrapAround(i);
+     lightIndex++;
+   }
    for (int i = 0; i <21; i++) {
-      // Compute the distance bewteen the pixel and the center
-      // point of the virtual pendulum.
-      float diff = i - pos;
-
-      // Light up nearby pixels proportional to their proximity to 'pos'
-      if (fabs(diff) <= halfWidth) {
-         CRGB color;
-         float proximity = halfWidth - fabs(diff) * 200; //Not being used right now
-
-         // pick a color based on heading & proximity to 'pos'
-         color = selectColor(heading);
-
-         // do both eyes
-         leftLense[i] = color;
-         float rightLenseOffset = i - 10;
-         while (round(rightLenseOffset) < 0) rightLenseOffset += 21.0;
-         while (round(rightLenseOffset) > 20) rightLenseOffset -= 21.0;
-         int rightLenseIndex = fabs(rightLenseOffset);
-         if (mirroredEyes) {
-           rightLense[rightLenseIndex] = color;
-         } else {
-           rightLense[rightLenseIndex] = color;
-         }
-      } else {// all others are off
-         float rightLenseOffset = i - 10;
-         while (round(rightLenseOffset) < 0) rightLenseOffset += 21.0;
-         while (round(rightLenseOffset) > 20) rightLenseOffset -= 21.0;
-         int rightLenseIndex = fabs(rightLenseOffset);
-         leftLense[i] = CRGB(0,0,0);
-         if (mirroredEyes) {
-           rightLense[rightLenseIndex] = CRGB(0,0,0);
-         } else {
-           rightLense[rightLenseIndex] = CRGB(0,0,0);
-         }
+      int rightIndex = i;
+      int leftIndex = wrapAround(i - 10); // This is because the strips aren't installed in the same place
+      boolean turnedOn = false;
+      for(int j=0;j<(halfWidth*2+1);j++) {
+        if(lightOn[j] == i){
+          leftLense[leftIndex] = color;
+          rightLense[rightIndex] = color;
+          turnedOn = true;
+        }
       }
+      if(turnedOn == false){
+        leftLense[leftIndex] = CRGB(0,0,0);
+        rightLense[rightIndex] = CRGB(0,0,0);
+      }
    }
    FastLED.show();
+}
+
+int wrapAround(int value) {
+  if(value < 0) {
+    return value + 21;
+  }
+  if(value > 20) {
+    return value - 21;
+  }
+  return value;
 }

 // choose a color based on the compass heading and proximity to "pos".
@@ -215,12 +216,12 @@
 // Reset to default
 void resetModes() {
    antiGravity = false;
-   mirroredEyes = true;
+   mirroredEyes = false;

    /// spin-up
-   spin(CRGB(255, 0, 0), 1, 500);
-   spin(CRGB(0, 255, 0), 1, 500);
-   spin(CRGB(0, 0, 255), 1, 500);
+   spin(CRGB(255, 0, 0), 1, 250);
+   spin(CRGB(0, 255, 0), 1, 250);
+   spin(CRGB(0, 0, 255), 1, 250);
    spinUp();
 }


I2C tweaks. Remove OTA window.

I2C tweaks. Remove OTA window.

I2C tweaks. Remove OTA window.

--- firmware/examples/RUSK-Basic.ino
+++ firmware/examples/RUSK-Basic.ino
@@ -1,3 +1,4 @@
+#include "FOXFIRE_RUSK_R002/FOXFIRE_RUSK_R002.h"
 #include "FOXFIRE_RUSK_R002/FOXFIRE_EmonLib.h"
 #include "FOXFIRE_RUSK_R002/FOXFIRE_Si1132.h"
 #include "FOXFIRE_RUSK_R002/FOXFIRE_Si70xx.h"
@@ -15,7 +16,7 @@
 int SLEEP_DELAY = 0; // 40 seconds (runs x1) - should get about 24 hours on 2100mAH, 0 to disable and use RELAX_DELAY instead
 String SLEEP_DELAY_MIN = "15"; // seconds - easier to store as string then convert to int
 String SLEEP_DELAY_STATUS = "OK"; // always OK to start with
-int RELAX_DELAY = 10; // seconds (runs x1) - no power impact, just idle/relaxing
+int RELAX_DELAY = 5; // seconds (runs x1) - no power impact, just idle/relaxing

 // Variables for the I2C scan
 byte I2CERR, I2CADR;
@@ -363,6 +364,10 @@
     // Open serial over USB
     Serial.begin(9600);

+    // Set I2C speed
+    // --> 400Khz seems to help stabilize I2C bus operation with packaged sensors
+    Wire.setSpeed(CLOCK_SPEED_400KHZ);
+
     // Disable Interrupts
     noInterrupts();

@@ -517,18 +522,14 @@
         postSensingEventPublish();

-        Serial.println("RUSK --> Device --> OTA Update Window");
+        //Serial.println("RUSK --> Device --> OTA Update Window Begin");

         // set aside time to do OTA updates
-        digitalWrite(LED, HIGH);
-        Particle.process(); delay(OTAUPDDELAY);
-        digitalWrite(LED, LOW);
-
-        //********************************************************************************
-        //********************************************************************************
-        //********************************************************************************
-
-        Wire.reset();
+        //digitalWrite(LED, HIGH);
+        //Particle.process(); delay(OTAUPDDELAY);
+        //digitalWrite(LED, LOW);
+
+        //Serial.println("RUSK --> Device --> OTA Update Window End");

         //********************************************************************************
         //********************************************************************************


refactor

refactor

--- firmware/beer/beersensor.ino
+++ firmware/beer/beersensor.ino
@@ -17,6 +17,7 @@
   int instantPulseCount;
   int previousPulseCount;
   int flowing;
+  int previousFlowing;
   int percentFull;
   int currentSecond;
   int previousSecond;
@@ -26,9 +27,9 @@
 };

 //initialize taps
-TapObject T0 = {1000, 1000, 0, 0, 0, 100, 1, 0, 0, D6, D3};
-TapObject T1 = {1000, 1000, 0, 0, 0, 100, 1, 0, 0, D5, D2};
-TapObject T2 = {1000, 1000, 0, 0, 0, 100, 1, 0, 0, D4, D1};
+TapObject T0 = {1000, 1000, 0, 0, 0, 0, 100, 1, 0, 0, D6, D3};
+TapObject T1 = {1000, 1000, 0, 0, 0, 0, 100, 1, 0, 0, D5, D2};
+TapObject T2 = {1000, 1000, 0, 0, 0, 0, 100, 1, 0, 0, D4, D1};

 int ledPin = D7;

@@ -132,30 +133,39 @@
   pinValT0();
   pinValT1();
   pinValT2();
-
-  // Serial.println("pulseCountT0: " + String(T0.pulseCount));
-  // Serial.println("pulseCountT1: " + String(T1.pulseCount));
-  // Serial.println("pulseCountT2: " + String(T2.pulseCount));
-
-
+  calculatePercentFull();
+  publishFlowingEvents();
+  handleAnimation();
+  writeToEEPROM();
+}
+
+void writeToEEPROM()
+{
+  EEPROM.put(EEPROM_ADDR_T0, T0);
+  EEPROM.put(EEPROM_ADDR_T1, T1);
+  EEPROM.put(EEPROM_ADDR_T2, T2);
+}
+
+void calculatePercentFull()
+{
   float percentT0 = (float)T0.pulseCount / (float)T0.maxPulseCount;
   T0.percentFull = (int)(percentT0 * 100.0f);
   if(T0.percentFull > 100)
     T0.percentFull = 100;
-  EEPROM.put(EEPROM_ADDR_T0, T0);

   float percentT1 = (float)T1.pulseCount / (float)T1.maxPulseCount;
   T1.percentFull = (int)(percentT1 * 100.0f);
   if(T1.percentFull > 100)
     T1.percentFull = 100;
-  EEPROM.put(EEPROM_ADDR_T1, T1);
-
+
   float percentT2 = (float)T2.pulseCount / (float)T2.maxPulseCount;
   T2.percentFull = (int)(percentT2 * 100.0f);
   if(T2.percentFull > 100)
     T2.percentFull = 100;
-  EEPROM.put(EEPROM_ADDR_T2, T2);
-
+}
+
+void handleAnimation()
+{
   if(T0.flowing)
   {
     Serial.println("flowingT0: " + String(T0.flowing));
@@ -165,7 +175,6 @@
   {
     if(T0.pulseCount > T0.maxPulseCount)
       T0.pulseCount = T0.maxPulseCount;
-    EEPROM.put(EEPROM_ADDR_T0, T0);
     recalculateTapColor(0);
   }

@@ -178,7 +187,6 @@
   {
     if(T1.pulseCount > T1.maxPulseCount)
       T1.pulseCount = T1.maxPulseCount;
-    EEPROM.put(EEPROM_ADDR_T1, T1);
     recalculateTapColor(1);
   }

@@ -191,29 +199,76 @@
   {
     if(T2.pulseCount > T2.maxPulseCount)
       T2.pulseCount = T2.maxPulseCount;
-    EEPROM.put(EEPROM_ADDR_T1, T1);
     recalculateTapColor(2);
   }
 }

+void publishFlowingEvents()
+{
+  if(T0.flowing != T0.previousFlowing)
+  {
+    if(T0.flowing)
+    {
+      //publish a start event
+      Particle.publish("start-flow-T0", String(T0.maxPulseCount) +
+                       "," + String(T0.pulseCount) + "," + String(T0.percentFull));
+    }
+    else
+    {
+      //publish a stop event
+      Particle.publish("stop-flow-T0", String(T0.maxPulseCount) +
+                       "," + String(T0.pulseCount) + "," + String(T0.percentFull));
+    }
+  }
+
+  if(T1.flowing != T1.previousFlowing)
+  {
+    if(T1.flowing)
+    {
+      //publish a start event
+      Particle.publish("start-flow-T1", String(T1.maxPulseCount) +
+                       "," + String(T1.pulseCount) + "," + String(T1.percentFull));
+    }
+    else
+    {
+      //publish a stop event
+      Particle.publish("stop-flow-T1", String(T1.maxPulseCount) +
+                       "," + String(T1.pulseCount) + "," + String(T1.percentFull));
+    }
+  }
+
+  if(T2.flowing != T2.previousFlowing)
+  {
+    if(T2.flowing)
+    {
+      //publish a start event
+      Particle.publish("start-flow-T2", String(T2.maxPulseCount) +
+                       "," + String(T2.pulseCount) + "," + String(T2.percentFull));
+    }
+    else
+    {
+      //publish a stop event
+      Particle.publish("stop-flow-T2", String(T2.maxPulseCount) +
+                       "," + String(T2.pulseCount) + "," + String(T2.percentFull));
+    }
+  }
+}
+
 int resetPulseCount(int tap)
 {
   if(tap == 0)
   {
     T0.pulseCount = T0.maxPulseCount;
-    EEPROM.put(EEPROM_ADDR_T0, T0);
   }
   else if(tap == 1)
   {
     T1.pulseCount = T1.maxPulseCount;
-    EEPROM.put(EEPROM_ADDR_T1, T1);
   }
   else if(tap == 2)
   {
     T2.pulseCount = T2.maxPulseCount;
-    EEPROM.put(EEPROM_ADDR_T2, T2);
-  }
-
+  }
+  writeToEEPROM();
   return 1;
 }

@@ -222,23 +277,22 @@
   if(tap == 0)
   {
     T0.maxPulseCount = val;
-    EEPROM.put(EEPROM_ADDR_T0, T0);
   }
   else if(tap == 1)
   {
     T1.maxPulseCount = val;
-    EEPROM.put(EEPROM_ADDR_T1, T1);
   }
   else if(tap == 2)
   {
     T2.maxPulseCount = val;
-    EEPROM.put(EEPROM_ADDR_T2, T2);
-  }
+  }
+  writeToEEPROM();
   return 1;
 }

 void pinValT0()
 {
+  T0.previousFlowing = T0.flowing;
   if(digitalRead(T0.flowPin) == HIGH)
   {
     if(flowTapPin0Value == 0)
@@ -267,12 +321,10 @@
       if(T0.previousPulseCount != T0.pulseCount)
       {
         T0.flowing = 1;
-        Particle.publish("start-flow-T0", String(T0.maxPulseCount) + "," + String(T0.pulseCount) + "," + String(T0.percentFull));
       }
       else
       {
         T0.flowing = 0;
-        // Particle.publish("stop-flow-T0", String(T0.maxPulseCount) + "," + String(T0.pulseCount) + "," + String(T0.percentFull));
       }
       T0.previousPulseCount = T0.pulseCount;
       T0.previousSecond = T0.currentSecond;
@@ -280,7 +332,8 @@
 }

 void pinValT1()
-{
+{
+  T1.previousFlowing = T1.flowing;
   if(digitalRead(T1.flowPin) == HIGH)
   {
     if(flowTapPin1Value == 0)
@@ -309,12 +362,10 @@
       if(T1.previousPulseCount != T1.pulseCount)
       {
         T1.flowing = 1;
-        Particle.publish("start-flow-T1", String(T1.maxPulseCount) + "," + String(T1.pulseCount) + "," + String(T1.percentFull));
       }
       else
       {
         T1.flowing = 0;
-        // Particle.publish("stop-flow-T1", String(T1.maxPulseCount) + "," + String(T1.pulseCount) + "," + String(T1.percentFull));
       }
       T1.previousPulseCount = T1.pulseCount;
       T1.previousSecond = T1.currentSecond;
@@ -323,6 +374,7 @@

 void pinValT2()
 {
+  T2.previousFlowing = T2.flowing;
   if(digitalRead(T2.flowPin) == HIGH)
   {
     if(flowTapPin2Value == 0)
@@ -351,12 +403,10 @@
       if(T2.previousPulseCount != T2.pulseCount)
       {
         T2.flowing = 1;
-        Particle.publish("start-flow-T2", String(T2.maxPulseCount) + "," + String(T2.pulseCount) + "," + String(T2.percentFull));
       }
       else
       {
         T2.flowing = 0;
-        // Particle.publish("stop-flow-T2", String(T2.maxPulseCount) + "," + String(T2.pulseCount) + "," + String(T2.percentFull));
       }
       T2.previousPulseCount = T2.pulseCount;
       T2.previousSecond = T2.currentSecond;


Cleaned up code. Added parameter to play_song. Renamed variables to be underscore separated.

--- frankenbear.ino
+++ frankenbear.ino
@@ -1,12 +1,14 @@
+#include <Adafruit_PWMServoDriver.h>
 #include <Wire.h>
+
 #include "pitches.h"
-#include <Adafruit_PWMServoDriver.h>

 // Uses the default address 0x40.
 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

-#define BIG_SERVO_MIN 160 // this is the 'minimum' pulse length count (out of 4096)
-#define BIG_SERVO_MAX 584 // this is the 'maximum' pulse length count (out of 4096)
+// These are the minimum and maximum pulse length counts (out of 4096) for our servos.
+#define BIG_SERVO_MIN 160
+#define BIG_SERVO_MAX 584
 #define MICRO_SERVO_MIN 160
 #define MICRO_SERVO_MAX 584

@@ -29,16 +31,13 @@
 int kissed_flag = 0;
 int normal_light_flag = 0;

-int photocellPin = A5;     // the cell and 10K pulldown are connected to a0
-int photocellReading;     // the analog reading from the sensor divider
-int LEDpin = 11;          // connect Red LED to pin 11 (PWM pin)
-int LEDbrightness;
+int photocell_pin = A5;
+int photocell_reading;
+
+const int button_pin = 2;
+const int button_state = 0;

 int speakerPin = 12;
-int numTones = 10;
-int tones[] = {261, 277, 294, 311, 330, 349, 370, 392, 415, 440};
-//            mid C  C#   D    D#   E    F    F#   G    G#   A
-
 int mary_had_a_little_lamb_notes[] = {
   NOTE_E4, NOTE_D4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_D4, NOTE_C4
 };
@@ -46,82 +45,64 @@
   4, 4, 4, 4, 4, 4, 2, 4, 4, 2, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2
 };

-const int buttonPin = 2;     // the number of the pushbutton pin
-const int ledPin =  13;      // the number of the LED pin
-int buttonState = 0;         // variable for reading the pushbutton status
-
 void setup()
 {
-  // Initialize serial port.
+  // Initialize serial port at 9600 baud.
   Serial.begin(9600);

   pwm.begin();
-
   pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz.
-
+
+  // Initialize the pushbutton pin as an input.
+  pinMode(button_pin, INPUT);
+
+  // Put arms and ears at normal position and wait for that to happen.
   reset_arms();
   reset_ears();
   delay(1000);
-
-  // initialize the LED pin as an output:
-  pinMode(ledPin, OUTPUT);
-  // initialize the pushbutton pin as an input:
-  pinMode(buttonPin, INPUT);
 }

 void loop()
 {
-  photocellReading = analogRead(photocellPin);
+  photocell_reading = analogRead(photocell_pin);
   Serial.print("Analog reading = ");
-  Serial.print(photocellReading);
-  Serial.print(", ");
-  Serial.println(normal_light_flag);
+  Serial.print(photocell_reading);
+  // Commented out because it's unneeded debugging information.
+  // Serial.print(", ");
+  // Serial.println(normal_light_flag);

   // When it gets bright or dark, make a sound.
   // Stop playing the sound until it's normal lighting out again.
-  if ( photocellReading >= 700 && photocellReading <= 710 )
+  if ( photocell_reading >= 700 && photocell_reading <= 710 )
   {
     normal_light_flag = 1;
   }

-  if ( photocellReading < 700 && normal_light_flag ) //it is dark
+  if ( photocell_reading < 700 && normal_light_flag )
   {
-    play_song();
+    play_song(0);
     normal_light_flag = 0;
   }
-  else if ( photocellReading > 710 && normal_light_flag ) // it is bright
+  else if ( photocell_reading > 710 && normal_light_flag )
   {
-//    tone(speakerPin, tones[9]); //play A
-//    delay(500);
-//    noTone(speakerPin);
-    while ( kissed_flag < 4 )
+    for ( int i = 0; i < 4; i++ )
     {
       wiggle_ears();
-      kissed_flag++;
     }

     reset_ears();
-    kissed_flag = 0;
     normal_light_flag = 0;
   }

-  // read the state of the pushbutton value:
-  buttonState = digitalRead(buttonPin);
+  button_state = digitalRead(button_pin);

-  // check if the pushbutton is pressed.
-  // if it is, the buttonState is HIGH:
-  if ( buttonState == HIGH )
+  if ( button_state == HIGH )
   {
-    digitalWrite(ledPin, HIGH);
     hug();
     reset_arms();
   }
-  else
-  {
-    digitalWrite(ledPin, LOW);
-  }

-  // check if manually moved
+  // TODO: check if manually moved
 }

 void wiggle_ears()
@@ -146,25 +127,28 @@

 void reset_arms()
 {
-  // Sets left_arm and right_arm at their min and max values.
+  // Sets left_arm and right_arm to their min and max values.
   pwm.setPWM(left_arm, 0, LEFT_ARM_OPEN);
   pwm.setPWM(right_arm, 0, RIGHT_ARM_OPEN);
 }

 void reset_ears()
 {
-  // Sets left_ear and right_ear at the middle.
+  // Sets left_ear and right_ear to the middle.
   pwm.setPWM(left_ear, 0, MIDDLE_EAR);
   pwm.setPWM(right_ear, 0, MIDDLE_EAR);
 }

-void play_song()
+void play_song(int song_number)
 {
   // 26 notes long
   for ( int i = 0; i < 26; i++ )
   {
-    int note_length = 1000 / mary_had_a_little_lamb_lengths[i];
-    tone(speakerPin, mary_had_a_little_lamb_notes[i], note_length);
+    if ( song_number == 0 )
+    {
+      int note_length = 1000 / mary_had_a_little_lamb_lengths[i];
+      tone(speakerPin, mary_had_a_little_lamb_notes[i], note_length);
+    }

     int pause_between_notes = note_length * 1.30;
     delay(pause_between_notes);


Programm mit ShiftRegister und virtualwire erweitert

--- ATtiny_Humidor_Monitoring/ATtiny_Humidor_Monitoring.ino
+++ ATtiny_Humidor_Monitoring/ATtiny_Humidor_Monitoring.ino
@@ -19,6 +19,10 @@
  * PB3 = 433MHz Sender
  * PB4 = DHT11 Sensor
  *
+ * shiftRegister Belegung:
+ * out1 = schieber / oeffner
+ * out2 = Luefter
+ *
  * Info:
  * Falls ein anderer Arduino Controller verwendet wird, muss man die Pins anpassen.
  *
@@ -54,91 +58,158 @@
  * EINES DELIKTES ODER ANDERS IM ZUSAMMENHANG MIT DER SOFTWARE ODER SONSTIGER VERWENDUNG DER SOFTWARE ENTSTANDEN.
  *
  */
-//attiny85
+#include<stdlib.h>
+//VirtualWire lib
+#include <VirtualWire.h>
+#undef int
+#undef abs
+#undef double
+#undef float
+#undef round
+
+int txPin = 3; //ueber Pin 3 die Daten senden
+
+//attiny85 shiftregister
 /*
 #define latchPin PB2
 #define clockPin PB0
 #define dataPin PB1
+int dhtPin = PB4; //DHT11 Pin
 */
-//arduino
+//arduino shiftregister
 #define latchPin A1
 #define clockPin A0
 #define dataPin A2
-//manchester lib
-#include <Manchester.h>
-#define TX_PIN  5  //uebertragungs Pin
+// shiftregister
+byte reg = 0;
+
+//DHT11 und 22 lib
+#include <Adafruit_Sensor.h>
+#include <DHT.h>
+#include <DHT_U.h>
+#define dhtPin 5 //DHT Pin
+// Uncomment the type of sensor in use:
+//#define DHTTYPE DHT11 // DHT 11
+#define DHTTYPE DHT22 // DHT 22 (AM2302)
+//#define DHTTYPE DHT21 // DHT 21 (AM2301)
+DHT_Unified dht(dhtPin, DHTTYPE);

 //Pausen zwischen den Messungen in Millisekunden
-unsigned long mtime = 10000;
-
-/*
- * Verschiedene Uebertragungsgeschwindigkeiten sind moeglich.
- * Variiert von der Distanz und Empfangsqualitaet
- *
- * Bei den Tests hat am besten die MAN_1200 Funktioniert.
- *
- * MAN_300 0
- * MAN_600 1
- * MAN_1200 2
- * MAN_2400 3
- * MAN_4800 4
- * MAN_9600 5
- * MAN_19200 6
- * MAN_38400 7
- */
+unsigned long stime = 10000;
+unsigned long mtime = 5000;
+
+// boolean felder
+boolean fan1 = false;

 void setup() {
   //Serial.begin(115200);
-
-  //manchester lib
-  man.workAround1MhzTinyCore(); //patch fuer 1Mhz ATtinyx4/x5
-  man.setupTransmit(TX_PIN, MAN_1200);
-
+  // Initialise the IO and ISR
+  vw_set_ptt_inverted(true); // Required for RF Link module
+  vw_setup(1200); // Bits per sec
+  vw_set_tx_pin(txPin); // pin 3 is used as the transmit data out into the TX Link module, change this as per your needs
   //shiftregister
   pinMode(latchPin, OUTPUT);
   pinMode(clockPin, OUTPUT);
   pinMode(dataPin, OUTPUT);
-}
-
-char msg[] = "adsfED";
-
-byte count = 1;
-unsigned long task1 = 0;
+  //init DHT device
+  dht.begin();
+  sensor_t sensor;
+}
+
+unsigned long task1, task2 = 0;
 void loop() {
   unsigned long currmillis = millis();

-  // Wenn die Zeit (worktime) kleiner als die Vergangene Zeit ist, schalte ab.
-  if ((unsigned long)(currmillis - task1) >= mtime || (currmillis == 1000)) {
-    uint16_t msglen = sizeof(msg)-1;
-    man.transmitArray(msglen, msg);
+  // Wenn die Zeit (worktime) kleiner als die Vergangene Zeit ist, Sende eine Nachricht.
+  if ((unsigned long)(currmillis - task1) >= stime || (currmillis == 1000)) {
+    send_msg("Testnachricht_1");
+    compute_msg(temp_sensor_id(), get_temp(), hum_sensor_id(), get_hum());
     task1 = millis();
   }
+
+  // checke die Luftfeuchtigkeit und wenn zu niedrig schalte Luefter ein.
+  if ((unsigned long)(currmillis - task2) >= mtime) {
+    if ((float)(get_hum() <= 70.0)) {
+      // switch ventilator on
+      if (!fan1) {
+        //oeffne Luefter schlitz
+        int i = 1;
+        bitSet(reg, i);
+        updateShiftRegister();
+        delay(10);
+        //switch fan1 on
+        i = i + 1;
+        bitSet(reg, i);
+        updateShiftRegister();
+        delay(60);
+        fan1 = true;
+      }
+    } else {
+      if (fan1) {
+        // switch fan1 off und schliesse den Schlitz
+        reg = 0;
+        updateShiftRegister();
+        delay(60);
+        fan1 = false;
+      }
+    }
+    task2 = millis();
+  }
+
+}
+
+void updateShiftRegister() {
+   digitalWrite(latchPin, LOW);
+   shiftOut(dataPin, clockPin, LSBFIRST, reg);
+   digitalWrite(latchPin, HIGH);
+}
+
+char temp_sensor_id() {
+  sensor_t sensor;
+  dht.temperature().getSensor(&sensor);
+  return sensor.sensor_id;
+}
+
+char hum_sensor_id() {
+  sensor_t sensor;
+  dht.humidity().getSensor(&sensor);
+  return sensor.sensor_id;
+}
+
+float get_temp() {
+  // Read temperature as Celsius (the default)
+  sensors_event_t event;
+  dht.temperature().getEvent(&event);
+  return event.temperature;
+}
+
+float get_hum() {
+  // Read humidity
+  sensors_event_t event;
+  dht.humidity().getEvent(&event);
+  return event.relative_humidity;
+}
+
+void compute_msg(char temp_uuid, float temp, char hum_uuid, float hum){
   /*
-  //if ((unsigned long)(currmillis - task1) == 1000) {
-  //rf_receive();
-  //}
-  */
-}
-
-/*
-void rf_receive() {
-  if (mySwitch.available()) {
-
-    int value = mySwitch.getReceivedValue();
-
-    if (value == 0) {
-      Serial.print("Unknown encoding");
-    } else {
-      Serial.print("Received ");
-      Serial.print( mySwitch.getReceivedValue() );
-      Serial.print(" / ");
-      Serial.print( mySwitch.getReceivedBitlength() );
-      Serial.print("bit ");
-      Serial.print("Protocol: ");
-      Serial.println( mySwitch.getReceivedProtocol() );
-    }
-
-    mySwitch.resetAvailable();
-  }
-}
-*/
+   * compute message for sending data
+   * dtostrf(FLOAT,WIDTH,PRECSISION,BUFFER);
+   */
+   char str;
+   str += temp_uuid;
+   str += dtostrf(temp,5,2,7);
+   str += hum_uuid;
+   str += dtostrf(hum,5,2,7);
+   //Serial.println(str);
+   send_msg(str);
+}
+
+void send_msg(char message) {
+  /*
+   * Sending data over 433MHz Sender
+   */
+  const char *msg = message; // this is your message to send
+  vw_send((uint8_t *)msg, strlen(msg));
+  vw_wait_tx(); // Wait for message to finish
+}
+


Added Limit Functions

Added Limit Functions

--- FumeHoodMonitor/DS18B20.ino
+++ FumeHoodMonitor/DS18B20.ino
@@ -7,7 +7,9 @@
 DallasTemperature sensors(&oneWire);

 const int numDS18B20Readings = 5;
-const float maxDS18B20Temperature = 200.0; //Deg F
+static const float airTempLow = 75.0; //Deg F
+static const float airTempHigh = 80.0; //Deg F
+static const float airTempOnFire = 85.0; //Deg F
 float DS18B20readings[numDS18B20Readings];
 int DS18B20readIndex = 0;
 float DS18B20total = 0;
@@ -38,3 +40,15 @@
   if (DS18B20readIndex >= numDS18B20Readings)DS18B20readIndex = 0;
   DS18B20average = DS18B20total / numDS18B20Readings;
 }
+
+bool isAirTempLow(float tempF){
+  return tempF <= airTempLow;
+}
+
+bool isAirTempHigh(float tempF) {
+  return tempF >= airTempHigh;
+}
+
+bool isAirTempOnFire(float tempF){
+  return tempF >= airTempOnFire;
+}


longtitude <-> latitude coordinates swapped *FIX*

--- hackAPost_1/hackAPost_1.ino
+++ hackAPost_1/hackAPost_1.ino
@@ -161,10 +161,10 @@
         valGPSTimestamp = strtod(command, NULL);
         break;
       case 1:
+        valGPSLongitude = strtod(command, NULL);
+        break;
+      case 2:
         valGPSLatitude = strtod(command, NULL);
-        break;
-      case 2:
-        valGPSLongitude = strtod(command, NULL);
         break;
       case 3:
         valGPSAltitude = strtod(command, NULL);


[LogToSerial] Output for Fahrenheit and digital filter are now really commented out

--- LogToSerial/LogToSerial.ino
+++ LogToSerial/LogToSerial.ino
@@ -36,10 +36,10 @@
   int digi = czr.GetDigiFilter();

   Serial.print("Celsius : ");Serial.println(t);
-  Serial.print("Fahrenheit : ");Serial.println(f);
+  //Serial.print("Fahrenheit : ");Serial.println(f);
   Serial.print("Humidity : ");Serial.println(h);
   Serial.print("CO2 : ");Serial.println(c);
-  Serial.print("Digital Filter : ");Serial.println(digi);
+  //Serial.print("Digital Filter : ");Serial.println(digi);
   Serial.println("");
 }


src: add metrics end point

src: add metrics end point

--- PlantSensor/PlantSensor.ino
+++ PlantSensor/PlantSensor.ino
@@ -12,6 +12,7 @@
 // device specifics
 #include "WirelessConfig.h"
 #include "SensorConfig.h"
+#include "ESP8266WebServer.h"

 #define TRANSMIT_INTERVAL_SECONDS 30
 #define MILLIS_IN_SECOND 1000
@@ -25,6 +26,7 @@
 };

 ESP8266WiFiGenericClass wifi;
+ESP8266WebServer server(80);

 #ifdef USE_CERTS
 // if certs are used the following must be defined in WirelessConfig.h
@@ -48,6 +50,25 @@

 int counter = 0;
 char macAddress[] = "00:00:00:00:00:00";
+
+
+char tempMessage[MAX_MESSAGE_SIZE];
+char floatBuffer[10];
+float currentTemp = 0;
+float currentHumidity = 0;
+int lightValue = 0;
+void provideMetrics() {
+  snprintf(tempMessage, MAX_MESSAGE_SIZE, "plant_humidity %s\n",
+             dtostrf(currentHumidity, 4, 2, floatBuffer));
+  String ptr = tempMessage;
+  snprintf(tempMessage, MAX_MESSAGE_SIZE, "plant_temperature %s\n",
+           dtostrf(currentTemp,4, 2, floatBuffer));
+  ptr+= tempMessage;
+  snprintf(tempMessage, MAX_MESSAGE_SIZE, "plant_light %d\n", lightValue);
+  ptr+= tempMessage;
+
+  server.send(200, "text/plain", ptr);
+}

 void setup() {
   delay(1000);
@@ -79,6 +100,9 @@
           macRaw[3],
           macRaw[4],
           macRaw[5]);
+
+  server.on("/metrics", provideMetrics);
+  server.begin();
 }

 void loop() {
@@ -114,26 +138,27 @@

     // don't send out temperature too often as we'll get
     // incorrect values if we sample too often
-    char tempMessage[MAX_MESSAGE_SIZE];
-    char floatBuffer[10];
+

     // read temperature in Celsius
-    float currentTemp = SHT2x.GetTemperature();
+    currentTemp = SHT2x.GetTemperature();
     snprintf(tempMessage, MAX_MESSAGE_SIZE, "0, 0 - temp: %s",
              dtostrf(currentTemp, 4, 2, floatBuffer));
     client.publish(TEMP_TOPIC, tempMessage);

     // read humidity
-    float currentHumidity = SHT2x.GetHumidity();
+    currentHumidity = SHT2x.GetHumidity();
     snprintf(tempMessage, MAX_MESSAGE_SIZE, "0, 0 - hum: %s",
              dtostrf(currentHumidity, 4, 2, floatBuffer));
     client.publish(HUM_TOPIC, tempMessage);

     char lightMessage[MAX_MESSAGE_SIZE];
-    int lightValue = analogRead(LIGHT_PIN);
+    lightValue = analogRead(LIGHT_PIN);
     snprintf(lightMessage, MAX_MESSAGE_SIZE, "0, 0 - light: %d", lightValue);
     client.publish(LIGHT_TOPIC, lightMessage);

     counter = 0;
   }
+
+  server.handleClient();
 }


Revert "fuzzy"

Revert "fuzzy"

This reverts commit 21be4841e2b539880edeb9dd5359eef493e5daee.

--- Elcano_C6_Navigator/Elcano_C6_Navigator.ino
+++ Elcano_C6_Navigator/Elcano_C6_Navigator.ino
@@ -1,5 +1,4 @@
 #include <GPS.h>
-//test

 /*
 Elcano Module C6: Navigator.


Some major reformatting and documentation going on here

--- teensy_octo.ino
+++ teensy_octo.ino
@@ -1,18 +1,23 @@
 /**
-http://www.pjrc.com/teensy/td_libs_Bounce.html
-http://www.pjrc.com/teensy/pinout.html
+ * Teensy Octo
+ *
+ * @author <david@sqroot.eu>
+ *
+ * Useful links:
+ *
+ * http://www.pjrc.com/teensy/td_libs_Bounce.html - About button bouncing
+ * http://www.pjrc.com/teensy/pinout.html - Teensy pinout diagram
 **/

 #include <Bounce.h>

-
 #define DEBOUNCE 10  // Number of ms to debounce
-
 #define NUMBER_OF_BUTTONS 8

-// Define pins for the buttons
+// Define digital pins for the buttons
 const byte BUTTON_PINS[] = {0, 1, 2, 3, 13, 16, 17, 18};

+// Initialize button objects
 Bounce buttons[NUMBER_OF_BUTTONS] = {
   Bounce( BUTTON_PINS[0], DEBOUNCE),
   Bounce( BUTTON_PINS[1], DEBOUNCE),
@@ -24,70 +29,222 @@
   Bounce( BUTTON_PINS[7], DEBOUNCE)
 };

-// Define pins for the RGB LED
+// Define PWM pins for the RGB LED
 const byte RGB_RED = 4;
 const byte RGB_GREEN = 5;
 const byte RGB_BLUE = 9;

+// The Piezo buzzer sits in this PWM pin
 const byte BUZZER_PIN = 12;

-void setup()   {
-  Serial.begin(38400);
-
-  // Initialize pushbutton pins
+/**
+ * Setup function - run once on power-on
+**/
+void setup() {
+  Serial.begin(9600);
+
+  // Initialize pushbutton pins as inputs with the internal pullup resistor enabled
   for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {
       pinMode(BUTTON_PINS[i], INPUT_PULLUP);
   }

+  // Set RGB LED pins as output
   pinMode(RGB_RED, OUTPUT);
   pinMode(RGB_GREEN, OUTPUT);
   pinMode(RGB_BLUE, OUTPUT);

-  analogWrite(RGB_RED, 250);
-  analogWrite(RGB_GREEN, 250);
-  analogWrite(RGB_BLUE, 250);
-
-  // Onboard LED to ON
+  // The LED is OFF by default
+  setLED(255, 255, 255);
+
+  // Onboard LED to ON for debugging
   pinMode(11, OUTPUT);
   digitalWrite(11, HIGH);
-}
-
-void buzz(unsigned int freq, unsigned long duration){
-  tone(BUZZER_PIN, freq, duration);
-}
-
+
+  Serial.println("Teensy Octo v1.0 by A. Roots 2013. Who are you?"); // I wonder whether he gets it without reading the source...
+}
+
+/**
+ * Main loop - the program keeps repeating this forever, as long as there is power
+**/
 void loop()
 {
+
+  // Detect and handle button presses
+  processButtonPress();
+
+  // Receive and proccess commands sent from the PC over serial
+  processSerialCommand();
+
+  delay(10);
+}
+
+/**
+ * Detect and handle button presses
+**/
+void processButtonPress() {
   for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {
     if (buttons[i].update() && buttons[i].read()) {
-      buttonPress(i);
+
+      Serial.println(i);
+      buzz(i*30 + 30, 500);
+
     }
   }
-  int bytecount=0;
-  byte incomingByte;
-   while (Serial.available() && bytecount < 10) {
-    incomingByte = Serial.read();
-Serial.println(incomingByte);
-if (incomingByte == 49){
-  buzz(100,900);
-}
-if (incomingByte == 50){
-  buzz(300,300);
-}
-
-    bytecount++;
-  }
-}
-
-void buttonPress(int buttonNumber) {
-  Serial.println(buttonNumber);
-
-  static int r;
-  static int g;
-  static int b;
-
-
-
-  buzz(buttonNumber*30 + 30, 500);
-}
-
+}
+
+/**
+ * Set the RGB LED values
+ *
+ * r - The intensity of the RED LED, 0 - 255
+ * g - The intensity of the GREEN LED, 0 - 255
+ * b - The intensity of the BLUE LED, 0 - 255
+**/
+void setLED(byte r, byte g, byte b){
+  analogWrite(RGB_RED, r);
+  analogWrite(RGB_GREEN, g);
+  analogWrite(RGB_BLUE, b);
+}
+
+/**
+ * Play a sound through the Piezo buzzer
+ *
+ * freq - The frequency of the tone in Hz
+ * duration -  The duration of the tone in milliseconds
+**/
+void buzz(unsigned int freq, unsigned long duration){
+  tone(BUZZER_PIN, freq, duration);
+}
+
+/**
+ * Split the input string into words separated by spaces and return the n-th word
+ *
+ * Used to extract serial arguments
+ *
+ * http://stackoverflow.com/a/14824108/401554
+**/
+String getToken(String data, int index)
+{
+  char separator = ' ';
+  int found = 0;
+  int strIndex[] = {0, -1};
+  int maxIndex = data.length()-1;
+
+  for(int i=0; i<=maxIndex && found<=index; i++){
+    if(data.charAt(i)==separator || i==maxIndex){
+        found++;
+        strIndex[0] = strIndex[1]+1;
+        strIndex[1] = (i == maxIndex) ? i+1 : i;
+    }
+  }
+
+  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
+}
+
+/**
+ * Read serial interface and return a string of sent data
+**/
+String getSerialCommand() {
+
+  String serialInput = "";
+  char character;
+
+  while(Serial.available()) {
+      character = Serial.read();
+      serialInput.concat(character);
+  }
+
+  return serialInput;
+}
+
+/**
+ * Receive serial input and proccess it
+**/
+void processSerialCommand(){
+
+  String serialInput = getSerialCommand();
+
+  if (serialInput == "") {
+    return;
+  }
+
+  // The first "word" is always the command
+  String command = getToken(serialInput, 0);
+
+  // Numeric params for the command
+  unsigned long param1 = stringToInt(getToken(serialInput, 1));
+  unsigned long param2 = stringToInt(getToken(serialInput, 2));
+  unsigned long param3 = stringToInt(getToken(serialInput, 3));
+
+  if (command == "buzz"){ // Make sound
+    buzz(param1, param2);
+  } else if (command == "led") { // Light LED
+    setLED(param1, param2, param3);
+  } else if (command == "help") { // Get help
+      Serial.println("http://github.com/anroots/teensy_octo");
+  } else if (command == "kristo"){ // Easteregg
+    kristo();
+  } else {
+      Serial.print("Unknown command: ");
+      Serial.println(command);
+  }
+}
+
+/**
+ * Convert a string into an integer
+ *
+ * http://christianscode.blogspot.com/2012/05/convert-string-to-integer.html
+**/
+int stringToInt(String thisString) {
+  int i, value, length;
+  length = thisString.length();
+  char buffer[(length+1)];
+
+  for(i=0; i<length; i++) {
+    buffer[i] = thisString.charAt(i);
+  }
+
+  buffer[i]=0;
+  value = atoi(buffer);
+  return value;
+}
+
+/**
+ * Play Kristo's theme through the buzz function.
+ *
+ * http://garagelab.com/profiles/blogs/how-to-use-tone-function-arduino-playing-the-james-bond-theme
+**/
+void kristo(){
+
+  // Note frequencies
+  int melody[] = {
+  330,349,349,349,349,330,330,330,
+  330,392,392,392,392,330,330,330,
+  330,349,349,349,349,330,330,330,
+  330,392,392,392,392,330,330,330,
+  622,587,494,440,494,
+  330,392,622,587,392,494,
+  494,740,698,494,587,932,
+  880,698,880,1245,1175,0
+};
+
+  // Note duration: 1 = whole note, 2 = half note, 4 = quarter note, 8 = eighth note, etc.
+  int noteDurations[] = {
+    8,16,16,8,4,8,8,8,
+    8,16,16,8,4,8,8,8,
+    8,16,16,8,4,8,8,8,
+    8,16,16,8,4,8,8,8,
+    8,2,8,8,1,
+    8,4,8,4,8,8,
+    8,8,4,8,4,8,
+    4,8,4,8,3
+  };
+
+  int pace = 1450; // change pace of music("speedy")
+  for (int Note = 0; Note <54; Note++) {//counter of Notes (54 limit the array)
+    int duration = pace/noteDurations[Note];//Adjust duration with the pace of music
+    buzz(melody[Note],duration); //Play note
+
+    // to distinguish the notes, set a minimum time between them.
+    delay(duration*1.2);
+  }
+}


updated button test

updated button test

--- proj/ledvo_lounge_button_test/ledvo_lounge_button_test.ino
+++ proj/ledvo_lounge_button_test/ledvo_lounge_button_test.ino
@@ -161,7 +161,7 @@
 void loop() {
   // Read in global brightness value
   if (power_on) {
-    gBrightness = map(analogRead(VAL_POT), 0, 687, maxBrightness, 0);
+    gBrightness = map(analogRead(VAL_POT), 0, 687, 0, maxBrightness);

     // Read color from potentiometer input
     gRGB = CHSV(map(analogRead(HUE_POT), 0, 687, 0, 255), 255, gBrightness);


Update LBridge_Arduino_V09.ino

Update LBridge_Arduino_V09.ino

--- LBridge_Arduino_V09/LBridge_Arduino_V09.ino
+++ LBridge_Arduino_V09/LBridge_Arduino_V09.ino
@@ -47,7 +47,7 @@
 /* *** config #DEFINES **************************** */
 /* ************************************************ */

-#define N_RELEASE_VERSION
+#define RELEASE_VERSION

 #define LB_DATETIME "180618_0715"
 #define LB_VERSION "V0.9"        // version number


Remove AT&DEBUG and add #define instead.  Minor cleanup and memory reduction.

--- MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
+++ MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
@@ -4,9 +4,11 @@
     With assistance and code from Greg Alekel and Payton Byrd
 */

+//#define DEBUG
+
 // Defining HAYES enables Hayes commands and disables the 1) and 2) menu options for telnet and incoming connections.
 // This is required to ensure the compiled code is <= 30,720 bytes
-#define HAYES
+//#define HAYES
 //#define ENABLE_C64_DCD
 #include <MicroView.h>
 #include <elapsedMillis.h>
@@ -75,7 +77,6 @@
 #define ADDR_AUTOSTART     1
 #define ADDR_BAUD_LO       2
 #define ADDR_BAUD_HI       3
-#define ADDR_DEBUG         4
 #define ADDR_HOST_AUTO    99     // Autostart host number
 #define ADDR_HOSTS         100    // to 299 with ADDR_HOST_SIZE = 40 and ADDR_HOST_ENTRIES = 5
 //#define ADDR_xxxxx         300
@@ -114,7 +115,7 @@
     pinMode (C64_RxD, INPUT);
     digitalWrite (C64_RxD, HIGH);

-    Display("Baud\ndetection");
+    Display(F("Baud\ndetection"));

     long detectedBaudRate = detRate(C64_RxD);  // Function finds a standard baudrate of either
     // 1200,2400,4800,9600,14400,19200,28800,38400,57600,115200
@@ -124,13 +125,13 @@
     //char temp[20];
     //sprintf(temp, "Baud\ndetected:\n%ld", detectedBaudRate);
     //Display(temp);
-    char temp[6];
-    sprintf(temp, "%ld", detectedBaudRate);
-    Display(temp);
-
-    delay(3000);

     if (detectedBaudRate == 1200 || detectedBaudRate == 2400 || detectedBaudRate == 4800 || detectedBaudRate == 9600 || detectedBaudRate == 19200) {
+        char temp[6];
+        sprintf_P(temp, PSTR("%ld"), detectedBaudRate);
+        Display(temp);
+        delay(3000);
+
         BAUD_RATE = detectedBaudRate;

         byte a = BAUD_RATE / 256;
@@ -178,11 +179,11 @@

         DisplayBoth(F("Wi-Fi Init..."));

-        boolean ok;
-        if(EEPROM.read(ADDR_DEBUG) == 1)
-           ok = wifly.begin(&WifiSerial, &C64Serial);
-        else
-           ok = wifly.begin(&WifiSerial);
+#ifdef DEBUG
+        boolean ok = wifly.begin(&WifiSerial, &C64Serial);
+#else
+        boolean ok = wifly.begin(&WifiSerial);
+#endif

         if (ok)
         {
@@ -1400,7 +1401,6 @@
     else if (strcmp(Modem_CommandBuffer, ("AT&F")) == 0)
     {
         Modem_LoadDefaults();
-        updateEEPROMByte(ADDR_DEBUG,0);
         Modem_PrintOK();
     }
     else if (strcmp(Modem_CommandBuffer, ("ATA")) == 0)
@@ -1599,14 +1599,6 @@
                 Modem_PrintOK();
             else
                 Modem_PrintERROR();
-        }
-        if (strstr(Modem_CommandBuffer, ("&DEBUG=1")) != NULL)
-        {
-            updateEEPROMByte(ADDR_DEBUG,1);
-        }
-        if (strstr(Modem_CommandBuffer, ("&DEBUG=0")) != NULL)
-        {
-            updateEEPROMByte(ADDR_DEBUG,0);
         }

         char *currentS;
@@ -2075,7 +2067,6 @@
       if (digitalRead(recpin) == 0)
           break;
     }
-    //while(digitalRead(recpin) == 1 && millis()-3000 < timer){} // wait for low bit to start
     long baud;
     long rate = pulseIn(recpin, LOW); // measure zero bit width from character 'U'


adds a bool to keep track of hit (#9)

adds a bool to keep track of hit (#9)

* adds a bool to keep track of hit

* rename to result and change delay

* replace with delay consts

* revert rename of logger

* f

--- ir_targets/ir_targets.ino
+++ ir_targets/ir_targets.ino
@@ -5,12 +5,14 @@
 #define BLUE_LASER 0
 #define RED_LASER 1
 #define DEBUG_MODE false
+#define MIN_DELAY 500
+#define DELAY_CEIL 2500

 // Define all the devices as global variables
 IRrecv *irrecvs[BASE_COUNT];
-int ledPins[] = {7,2,4};
-int receiverPins[] = {8,13,13};
+int ledPins[] = {2,7,4};
+int receiverPins[] = {13,8,12};

 // Define all time related variables
 unsigned long startMillis;
@@ -19,10 +21,11 @@

 // State variables
 int activeReceiver;
+bool laserHit = false;

 // Store scores
 int scores[] = {0,0};
-decode_results results;
+decode_results result;

 // methods
 void setup() {
@@ -32,7 +35,6 @@
 }

 void initSensors() {
-
   for (int i = 0; i < BASE_COUNT; i++) {
     irrecvs[i] = new IRrecv(receiverPins[i]);
     irrecvs[i]->enableIRIn();
@@ -44,19 +46,12 @@
     pinMode(ledPins[i], OUTPUT);
 }

-
 void loop() {
   toggleSensors();
-
-  for (int i = 0; i < BASE_COUNT; i++){
-    if (irrecvs[i]->decode(&results)) {
-      if(i == activeReceiver)
-        recordHit(i);
-      irrecvs[i]->resume();
-    }
+  if (!laserHit && irrecvs[activeReceiver]->decode(&result)) {
+    recordHit(activeReceiver);
   }
 }
-

 void toggleSensors() {
   elapsedTime = millis() - startMillis;
@@ -69,9 +64,8 @@

 int interval() {
   // generate random intervel between 500ms to 2500ms
-    return rand() % 2000 + 500;
+    return (rand() % DELAY_CEIL) + MIN_DELAY;
 }
-

 void updateReceiverState() {
   for (int i = 0; i < BASE_COUNT; i++) {
@@ -80,20 +74,21 @@
     else
       turnOffReceiver(i);
   }
-
+  laserHit = false;
   startMillis = millis();
 }

 void turnOffReceiver(int index) {
-  digitalWrite(ledPins[index], LOW);
+  digitalWrite(ledPins[index], LOW);
 }

 void turnOnReceiver(int index) {
   digitalWrite(ledPins[index], HIGH);
+  irrecvs[index]->resume();
 }

 void recordHit(int index) {
-  unsigned int rawbuf_last = results.rawbuf[results.rawlen-1];
+  unsigned int rawbuf_last = result.rawbuf[result.rawlen-1];

   if(rawbuf_last < 10){
     scores[BLUE_LASER]++;
@@ -103,6 +98,7 @@
     Serial.write('R');
   }

+  laserHit = true;
   turnOffReceiver(index);
   printRawbufLast(rawbuf_last);
   printHit(index);
@@ -128,7 +124,7 @@

 void printHit(int index) {
   if(DEBUG_MODE) {
-     String logger = "hit index: " + String(index);
+    String logger = "hit index: " + String(index) + " value: " + String(result.value);
     Serial.println(logger);
   }
 }


Note about avoiding reboots during an update

--- src/homie-sonoff-touch.ino
+++ src/homie-sonoff-touch.ino
@@ -67,6 +67,7 @@
     if (millis() - connectedMillis >= 60000 ) {
       Serial.println("Restarting in ten seconds");
       delay(10000);
+      //FIXME Don't do this during an update!
       ESP.restart();
     };
   }


Add different fade outs

Add different fade outs

--- led_pixels/led_pixels.ino
+++ led_pixels/led_pixels.ino
@@ -219,10 +219,22 @@
   for (int y = 0; y < GRIDSIZE; y++) {
     for (int x = 0; x < GRIDSIZE; x++) {
       Fader.setPixelColor(x, y, Color(0, 0, 0), time);
-      time += duration / (GRIDSIZE * GRIDSIZE); // fade over 2s
+      time += duration / (GRIDSIZE * GRIDSIZE); // fade over duration
     }
   }
 }
+
+void allOffRowByRow(double duration)
+{
+  double time = 0.1;
+  for (int y = 0; y < GRIDSIZE; y++) {
+      time += duration / GRIDSIZE;
+    for (int x = 0; x < GRIDSIZE; x++) {
+      Fader.setPixelColor(x, y, Color(0, 0, 0), time);
+    }
+  }
+}
+

 /////////////

@@ -259,7 +271,7 @@
   { animateToLetterU, 0.2 },
   { pause, 1.5 },

-  { allOffBitByBit, 1 },
+  { allOffRowByRow, 2 },

   // Beating heart
   { animateToBigHeart, 0.5},
@@ -277,10 +289,11 @@
   { pause, 0.5 },

   // Color swirls
-  { rainbowAnimation, 1, 1 },
-  { rainbowAnimation, 1, 0 },
-
-  { allOffBitByBit, 2 },
+//  { rainbowAnimation, 15, 1 },
+//  { allOffRowByRow, 1 },
+  { rainbowAnimation, 30, 0 },
+
+  { allOffRowByRow, 2 },
   //{ pause, 0.5 },
 };

@@ -365,6 +378,12 @@
   pause(duration, &nextAnimation);
 }

+void allOffRowByRow(double duration, uint32_t param)
+{
+  allOffRowByRow(duration);
+  pause(duration, &nextAnimation);
+}
+
 //////////////

 void loop() {


Added switch

Added switch

--- m_led/m_led.ino
+++ m_led/m_led.ino
@@ -96,6 +96,42 @@

 uint8_t curbrightness=255;	//brightness is X=curbrightness/255.  Max brightness is set here
 uint32_t curslowdown=1024; //Slowness factor is X=slowdown/1024.  For example, set slowdown to 2048 to get a 2x slowdown.  set slowdown to 512 to get a 50% slowdown (2x speedup).
+uint8_t curpattern=2;
+
+#define BUTTON_MAX 4
+#define BUTTON_PUSHED 0
+
+#define UP_BUTTON 0
+#define DOWN_BUTTON 1
+
+int  buttonstates[]={BUTTON_MAX,BUTTON_MAX};
+int  buttonpins[]={2,3};
+
+static const int NUM_BUTTONS=sizeof(buttonstates)/sizeof(buttonstates[0]);
+
+void updatebuttons()
+{
+	for(int i=0;i<NUM_BUTTONS;i++)
+	{
+		int val=(digitalRead(buttonpins[i]) << 1) - 1;
+		buttonstates[i]+=val;
+		if(buttonstates[i]>=BUTTON_MAX)
+		{
+			buttonstates[i]=BUTTON_MAX;
+		}
+		else if(buttonstates[i] < 0)
+		{
+			buttonstates[i]=0;
+		}
+	}
+}
+void setupbuttons()
+{
+	for(int i=0;i<NUM_BUTTONS;i++)
+	{
+		pinMode(buttonpins[i], INPUT_PULLUP);
+	}
+}

 void setup()
 {
@@ -103,9 +139,21 @@
 	{
 		strips[i]->setup();
 	}
-	goto_pattern(2);
+	setupbuttons();
+	goto_pattern(curpattern);
 }
 void loop()
 {
 	pframeid=iterate_pattern(curptr,pframeid,curbrightness,curslowdown);
+	updatebuttons();
+	if(buttonstates[UP_BUTTON] == BUTTON_PUSHED)
+	{
+		curpattern++;
+		goto_pattern(curpattern);
+	}
+	else if(buttonstates[DOWN_BUTTON] == BUTTON_PUSHED)
+	{
+		curpattern--;
+		goto_pattern(curpattern);
+	}
 }


add 15

add 15

--- m_led/m_led.ino
+++ m_led/m_led.ino
@@ -1,6 +1,6 @@
 #include "LedStripRS.h"

-LedStripRS<A0> trs;
+LedStripRS<A0,15> trs;

 static BaseLedStripRS* strips[]=
 {


travis failing shrug

travis failing shrug

`home/travis/.arduino15/packages/esp8266/hardware/esp8266/2.6.0/cores/esp8266/debug.h:8:26: error: '::printf' has not been declared`

--- examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino
+++ examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino
@@ -5,10 +5,12 @@
  */
 #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
 #include <time.h>
+#include <stdio.h>

 #define USEOTA
 // enable OTA
 #ifdef USEOTA
+#include <ESPmDNS.h>
 #include <WiFiUdp.h>
 #include <ArduinoOTA.h>
 #endif


Trying with every line separated

Trying with every line separated

--- src/WiFiSensor/mqtt.ino
+++ src/WiFiSensor/mqtt.ino
@@ -28,9 +28,12 @@
     return(0);
   } else {
     Serial.println("Unable To Connect, Details: ");
-    Serial.println("  mqttclientname: " + mqttclientname);
-    Serial.println("  mqttusername: " + mqttusername);
-    Serial.println("  mqttpassword: " + mqttpassword);
+    Serial.println("  mqttclientname: ");
+    Serial.println(mqttclientname);
+    Serial.println("  mqttusername: ");
+    Serial.println(mqttusername);
+    Serial.println("  mqttpassword: ");
+    Serial.println(mqttpassword);
     Serial.println(" ");
     return(2);
   }
@@ -42,9 +45,11 @@
       return 0;
   }else{
       Serial.println( "Failed MQTT Update, Details:");
-      Serial.println("  topic: " + topic);
-      Serial.println("  msg: " + String(msg) );
-      Serial.println("");
+      Serial.println("  topic: ");
+      Serial.println(topic);
+      Serial.println("  msg: ");
+      Serial.println(msg );
+      Serial.println(" ");
       return 1;
   }
 }


changed sound sensor attiny

changed sound sensor attiny

--- Modules/Sensor/SoundSensor/ArduinoCodes/SoundSensorATtiny/SoundSensorATtiny.ino
+++ Modules/Sensor/SoundSensor/ArduinoCodes/SoundSensorATtiny/SoundSensorATtiny.ino
@@ -9,7 +9,7 @@
 **
 **  Pin 1 (Reset): N/U                   Pin 8 (PWR):         5V
 **  Pin 2 (D3/A3): Module Input          Pin 7 (D2/A1/SCK):   N/U
-**  Pin 3 (D4/A2): N/U                   Pin 6 (D1/PWM/MISO): Module Output
+**  Pin 3 (D4/A2): Sound Sensor          Pin 6 (D1/PWM/MISO): Module Output
 **  Pin 4 (GND):   GND                   Pin 5 (D0/PWM/MOSI): N/U
 **
 **
@@ -40,7 +40,7 @@

   int input_val = cutAndMap(input.filteredAnalogRead(AVERAGE), 50, 975, 0, 1023);
   int sensor_val = analogRead(A0);
-  int output_val = cutAndMap(input_val, 300, 400, 0, 255);              //350 and 475 experimentally determined
+  int output_val = cutAndMap(sensor_val, 300, 400, 0, 255);              //350 and 475 experimentally determined

   analogWrite(output_pin, output_val);
   /*for(int i = output_val; i >= 25; i-=25){                            //fade output slightly


logging responses

logging responses

--- sheild_sdlog_gps_color_v3/sheild_sdlog_gps_color_v3.ino
+++ sheild_sdlog_gps_color_v3/sheild_sdlog_gps_color_v3.ino
@@ -2,28 +2,31 @@
 #include <Adafruit_GPS.h>
 #include <SoftwareSerial.h>
 #include <SD.h>
-#include "Adafruit_TCS34725.h"
+#include <Wire.h>
+#include <Adafruit_TCS34725.h>
 #include <avr/sleep.h>

-// Ladyada's logger modified by Bill Greiman to use the SdFat library
+// Code hacked together by Nick Meehan nick@unsalted.nu -
+// In association with: Art Center College of Design - Media Design Practices - MFA
 //
-// This code shows how to listen to the GPS module in an interrupt
-// which allows the program to have more 'freedom' - just parse
-// when a new NMEA sentence is available! Then access data when
-// desired.
+// This code is a combination of two code sets:
+// https://github.com/adafruit/Adafruit-GPS-Library/tree/master/examples/shield_sdlog
+// https://github.com/adafruit/Adafruit_TCS34725/tree/master/examples/tcs34725
 //
-// Tested and works great with the Adafruit Ultimate GPS Shield
-// using MTK33x9 chipset
-//    ------> http://www.adafruit.com/products/
-// Pick one up today at the Adafruit electronics shop
-// and help support open source hardware & software! -ada
-// Fllybob added 10 sec logging option
-SoftwareSerial mySerial(8, 7);
+// With additional help from: http://www.instructables.com/id/Personal-Black-Box-Arduino-Mega-Ultimate-GPS-Shiel/
+// The goal of this code is to map coordinates with color data taken by TCS34725
+//
+//
+// Developed on the Adafruit Ultimate GPS + Logging Shield & TCS34725 RGB Color Sensor
+// on an Arduino Mega 2560
+//
+
+HardwareSerial mySerial = Serial1;    //This line is only for mega
 Adafruit_GPS GPS(&mySerial);

 // Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
 // Set to 'true' if you want to debug and listen to the raw GPS sentences
-#define GPSECHO  true
+#define GPSECHO  false
 /* set to true to only log to SD when GPS has a fix, for debugging, keep it false */
 #define LOG_FIXONLY false

@@ -41,16 +44,17 @@
 // read a Hex value and return the decimal equivalent
 uint8_t parseHex(char c) {
   if (c < '0')
-    return 0;
+  return 0;
   if (c <= '9')
-    return c - '0';
+  return c - '0';
   if (c < 'A')
-    return 0;
+  return 0;
   if (c <= 'F')
-    return (c - 'A')+10;
-}
-
-// blink out an error code
+  return (c - 'A')+10;
+}
+
+// Errors not vurrently used on board but could come in handy.
+// Blink out an error code
 void error(uint8_t errno) {
   /*
   if (SD.errorCode()) {
@@ -60,7 +64,7 @@
    Serial.println(card.errorData(), HEX);
    }
    */
-  while(1) {
+   while(1) {
     uint8_t i;
     for (i=0; i<errno; i++) {
       digitalWrite(ledPin, HIGH);
@@ -77,18 +81,15 @@
 Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);

 void setup() {
-  // for Leonardos, if you want to debug SD issues, uncomment this line
-  // to see serial output
-  //while (!Serial);

   if (tcs.begin()) {
     Serial.println("Found sensor");
-  } else {
-    Serial.println("No TCS34725 found ... check your connections");
-    while (1);
-  }
-
-  tcs.setInterrupt(true);
+    } else {
+      Serial.println("No TCS34725 found ... check your connections");
+      while (1);
+    }
+
+    tcs.setInterrupt(true);

   // connect at 115200 so we can read the GPS fast enough and echo without dropping chars
   // also spit it out
@@ -101,16 +102,18 @@
   pinMode(10, OUTPUT);

   // see if the card is present and can be initialized:
-  //if (!SD.begin(chipSelect, 11, 12, 13)) {
-  if (!SD.begin(chipSelect)) {      // if you're using an UNO, you can use this line instead
-    Serial.println("Card init. failed!");
-    error(2);
-  }
-  char filename[15];
-  strcpy(filename, "GPSLOG00.CSV");
-  for (uint8_t i = 0; i < 100; i++) {
-    filename[6] = '0' + i/10;
-    filename[7] = '0' + i%10;
+  if (!SD.begin(chipSelect, 11, 12, 13)) {
+  Serial.println("Card init. failed!");
+  error(2);
+}
+
+
+char filename[15];
+strcpy(filename, "GPSLOG00.CSV");
+
+for (uint8_t i = 0; i < 100; i++) {
+  filename[6] = '0' + i/10;
+  filename[7] = '0' + i%10;
     // create if does not exist, do not open existing, write, sync after write
     if (! SD.exists(filename)) {
       break;
@@ -125,8 +128,9 @@
   }
   Serial.print("Writing to ");
   Serial.println(filename);
-  //logfile.println("Time, Date, Latitude, Longitude, Elevation, Speed (Knots), Angle, Satellites");
-  //logfile.flush();
+  // Print csv header
+  logfile.println("Time, Date, Latitude, Longitude, Elevation, Speed (Knots), Angle, Satellites, Color Temp, Lux, R, G, B, C");
+  logfile.flush();

   // connect to the GPS at the desired rate
   GPS.begin(9600);
@@ -149,6 +153,8 @@
   useInterrupt(true);

   Serial.println("Ready!");
+  // Print CSV headers to serial
+  Serial.println("Time, Date, Latitude, Longitude, Elevation, Speed (Knots), Angle, Satellites, Color Temp, Lux, R, G, B, C");
 }

@@ -157,15 +163,15 @@
   char c = GPS.read();
   // if you want to debug, this is a good time to do it!
   #ifdef UDR0
-      if (GPSECHO)
-        if (c) UDR0 = c;
+  if (GPSECHO)
+  if (c) UDR0 = c;
       // writing direct to UDR0 is much much faster than Serial.print
       // but only one character can be written at a time.
-  #endif
-}
-
-void useInterrupt(boolean v) {
-  if (v) {
+      #endif
+    }
+
+    void useInterrupt(boolean v) {
+      if (v) {
     // Timer0 is already used for millis() - we'll just interrupt somewhere
     // in the middle and call the "Compare A" function above
     OCR0A = 0xAF;
@@ -179,13 +185,25 @@
   }
 }

+
 void loop() {
+
+  tcs.setInterrupt(true);      // turn on LED
+
+  // Declare color sensor variables
+  uint16_t r, g, b, c, colorTemp, lux;
+
+  tcs.getRawData(&r, &g, &b, &c);
+  colorTemp = tcs.calculateColorTemperature(r, g, b);
+  lux = tcs.calculateLux(r, g, b);
+
+
   if (! usingInterrupt) {
     // read data from the GPS in the 'main loop'
     char c = GPS.read();
     // if you want to debug, this is a good time to do it!
     if (GPSECHO)
-      if (c) Serial.print(c);
+    if (c) Serial.print(c);
   }

   // if a sentence is received, we can check the checksum, parse it...
@@ -203,15 +221,15 @@
       return;  // we can fail to parse a sentence in which case we should just wait for another

     // Sentence parsed!
-    Serial.println("OK");
+    Serial.println("GPS parsed OK");
     if (LOG_FIXONLY && !GPS.fix) {
       Serial.print("No Fix");
       return;
     }

-    // Rad. lets log it!
-    Serial.println("Log");
-
+    // Super. log it!
+    Serial.println("Log: start");
+    //Time
     logfile.print(GPS.hour, DEC);
     logfile.print(':');
     logfile.print(GPS.minute, DEC);
@@ -220,14 +238,14 @@
     logfile.print('.');
     logfile.print(GPS.milliseconds);
     logfile.print(",");
-
+    //Date
     logfile.print(GPS.month, DEC);
     logfile.print('/');
     logfile.print(GPS.day, DEC);
     logfile.print("/20");
     logfile.print(GPS.year, DEC);
     logfile.print(",");
-
+    //Coordinates
     logfile.print(GPS.latitude, 4);
     logfile.print(GPS.lat);
     logfile.print(",");
@@ -240,10 +258,72 @@
     logfile.print(",");
     logfile.print(GPS.angle);
     logfile.print(",");
-    logfile.println((int)GPS.satellites);
+    logfile.print((int)GPS.satellites);
+    logfile.print(",");
+    //Color
+    logfile.print(colorTemp, DEC);
+    logfile.print(",");
+    logfile.print(lux, DEC);
+    logfile.print(",");
+    logfile.print(r, DEC);
+    logfile.print(",");
+    logfile.print(g, DEC);
+    logfile.print(",");
+    logfile.print(b, DEC);
+    logfile.print(",");
+    logfile.println(c, DEC);
+    // Wait for logging to finish
     logfile.flush();
-    Serial.println("success.");
+    // Print to serial
+    Serial.println("Logging: complete");
     Serial.println();
+    Serial.println("Logged Data:");
+    // Time
+    Serial.print(GPS.hour, DEC);
+    Serial.print(':');
+    Serial.print(GPS.minute, DEC);
+    Serial.print(':');
+    Serial.print(GPS.seconds, DEC);
+    Serial.print('.');
+    Serial.print(GPS.milliseconds);
+    Serial.print(",");
+    // Date
+    Serial.print(GPS.month, DEC);
+    Serial.print('/');
+    Serial.print(GPS.day, DEC);
+    Serial.print("/20");
+    Serial.print(GPS.year, DEC);
+    Serial.print(",");
+    // Coordinates
+    Serial.print(GPS.latitude, 4);
+    Serial.print(GPS.lat);
+    Serial.print(",");
+    Serial.print(GPS.longitude, 4);
+    Serial.print(GPS.lon);
+    Serial.print(",");
+    Serial.print(GPS.altitude);
+    Serial.print(",");
+    Serial.print(GPS.speed);
+    Serial.print(",");
+    Serial.print(GPS.angle);
+    Serial.print(",");
+    Serial.print((int)GPS.satellites);
+    Serial.print(",");
+    // Color temp
+    Serial.print(colorTemp, DEC);
+    Serial.print(",");
+    Serial.print(lux, DEC);
+    Serial.print(",");
+    Serial.print(r, DEC);
+    Serial.print(",");
+    Serial.print(g, DEC);
+    Serial.print(",");
+    Serial.print(b, DEC);
+    Serial.print(",");
+    Serial.println(c, DEC);
+
+    Serial.print("\n");
+    Serial.println();
   }
 }


while et valeurs absolue corrigé. Reste du peuafinage!! ?

--- calibrateur.ino
+++ calibrateur.ino
@@ -9,7 +9,9 @@

 //a faire pour prochaine fois : pendant les grandes course vérifier si avec le nouveauc compteur qui peut etre négatif ça marche bien.
 autre point de suspissionde bug : la vitesse qui est trop élevé et que le servo n'arrive pas à suivre.--> il suffit de baisser VITESSEMAXSERVO (passé de 3500 à 2500)
-
+// a faire : arreter de demander a utilisateur de noter sens de rotation : le dire automatiquement grace à voie B
+// vérifier que 1 impulsion = 0,5°
+// améliorer la mesure de vitesse à la fin

 //afaire : faire un réinit propre car si on fait 2 étalonnage à la suite ca marche pas
 //a Faire : lire l'autre voie de la roue codeuse pour detectr les rebond du servo
@@ -49,7 +51,7 @@
 //en ms le temps d'etre sur que le servo ait bougé
 //d'un increment quand on fait les mesure à la roue codeuse
 #define PINVOIEB 3 //la pin surlaquelle est branché la voie B
-#define ERREURCOMPTAGE 10 //la tolérance de comptage avant que l'on estime que le servo est arrivé au bout
+#define ERREURCOMPTAGE 6 //la tolérance de comptage avant que l'on estime que le servo est arrivé au bout
 #define NBRCYCLE_AR 10 //nbre de cycle d'aller et retour pour la fin des mesure de caractérisation et nbr de cycle pour la mesure des PWMIN et PWMMAX
 #define TEMPO_STAT 200 // tempo pour laisser le servo avancer lors des mesures
                        // statistique à la fin de la calibration ATTENTION 100ms semble etre trop court!!!!
@@ -325,8 +327,7 @@

                     compteur=compteurRef;

-                    while (abs(compteur)>(abs(compteurRef)-ERREURCOMPTAGE)\
-                            && abs(compteur)<(abs(compteurRef)+ERREURCOMPTAGE))
+                    while (abs(compteurRef-compteur)<ERREURCOMPTAGE)
 /*
 Correction integre par JSO le 29/9 mail Gilles
 -                    while (compteur>compteurRef-ERREURCOMPTAGE\
@@ -349,9 +350,10 @@
                     sleep(TEMPOSLEEP);
                     //----------------------------------------------------------
                     //find mmin
-                    compteur=compteurRef;
-                    while (abs(compteur)>(abs(compteurRef)-ERREURCOMPTAGE)\
-                            && abs(compteur)<(abs(compteurRef)+ERREURCOMPTAGE))
+                    compteur=-compteurRef;
+                    while (abs(-compteurRef-compteur)<ERREURCOMPTAGE)
+						// inversion du signe de compteur ref car on change de sens
+						// de rotation (par rapport au sens de recherche de compteur ref)
 /*
 Correction integre par JSO le 29/9 mail Gilles
 -                    while (compteur>compteurRef-ERREURCOMPTAGE\
@@ -494,7 +496,8 @@
                         {
                             boutonP.acquit();
                             etatCalibrateur=MESREFPULSE;
-                            leServo=servoTest(PINSERVO);
+                            leServo.setType(leServo.getType());
+							leServo.setVitesse(VITESSEMAXSERVO);
                             leServo.setObjectif(leServo.getMilieu());
                             //potence.setObjectif(bonnePositionPotence);
                             sleep(TEMPOSLEEP*3);


making the firmware use the IC lib

making the firmware use the IC lib

--- firmware/src/controller_src/hcsr04_backpack/hcsr04_backpack.ino
+++ firmware/src/controller_src/hcsr04_backpack/hcsr04_backpack.ino
@@ -35,12 +35,6 @@
     }
 }

-// TODO remove this
-void test_command(String args) {
-    // a test command
-    Serial.println("This is just a test");
-}
-
 void setup() {

     // check to see if we're in config mode
@@ -49,8 +43,21 @@
     if (state == CONFIG) {
         Serial.begin(9600);
         run_config(Serial, FIRMWARE_VERSION);
+
     } else if (state == RUNNING) {
-        Wire.begin(DEFAULT_I2C_SENSOR_ADDRESS);
+        uint8_t i2c_address;
+
+        if (use_custom_address() ) {
+            if (get_i2c_address() > 0) {
+                i2c_address = get_i2c_address();
+            } else {
+                i2c_address = DEFAULT_I2C_SENSOR_ADDRESS;
+            }
+        } else {
+            i2c_address = DEFAULT_I2C_SENSOR_ADDRESS;
+        }
+
+        Wire.begin(i2c_address);
         Wire.onRequest(requestData);
     }

@@ -60,6 +67,10 @@
     }

     Serial.println(F("HCSR04 FIRMWARE - DEBUG MODE"));
+    Serial.print("Use custom: ");
+    Serial.println(use_custom_address());
+    Serial.print("I2C address: ");
+    Serial.println(get_i2c_address());
 #endif
 }


fixed compass

fixed compass

--- device/arduino/navi_v2-Uno/navi_v2-Uno/navi_v2-Uno.ino
+++ device/arduino/navi_v2-Uno/navi_v2-Uno/navi_v2-Uno.ino
@@ -1,124 +0,0 @@
-//////////////////////PINS//////////////////////
-/*
-  Magnometer: VIN: 3.3V  SDA: 20  SCL: 21
-  Motor - R: 9  L: 10
-*/
-///////////////////////////////////////////////
-#include <Adafruit_HMC5883_U.h>
-#include <Adafruit_Sensor.h>
-#include <Wire.h>
-#include <FRCmotor.h>
-
-int gamemode = 1; // Enables the FRCmotor library
-
-//Magnometer
-Adafruit_HMC5883_Unified mag = Adafruit_HMC5883_Unified(12345);
-float heading= 0;
-
-//SerialRead/Write
-#define BUFSIZE 256
-#define SPEED_LIMIT 100
-
-const int safesize = BUFSIZE / 2;
-char buf[BUFSIZE];
-char write_buffer[BUFSIZE];
-int available_bytes = 0;
-
-// Target and previous velocity arrays
-static int target_vel[] = {0 , 0};
-
-//Motor Control
-FRCmotor leftMotor; //DECLARE LEFT MOTOR CONTROLLER
-FRCmotor rightMotor; //DECLARE RIGHT MOTOR CONTROLLER
-
-
-void setup() {
-  leftMotor.SetPort(10); //DECLARE ARDUINO PORT FOR MOTOR CONTROLLER SIGNAL
-  rightMotor.SetPort(9);
-  leftMotor.Set(0); //SET INITIAL MOTOR VALUES TO ZERO
-  rightMotor.Set(0); //(100 MAX FORWARD, -100 MAX BACK)
-
-  Serial.begin(9600);
-
-}
-
-void loop()
-{
-  readSerial();
-  moveMotor();
-  getCompass();
-  writeSerial();
-}
-
-void readSerial()
-{
-  if ((available_bytes = Serial.available()))
-  {
-    // Read + attach null byte to read string
-    int obytes = strlen(buf);
-    Serial.readBytes(&buf[obytes], available_bytes);
-    buf[available_bytes + obytes] = '\0';
-
-    if(strlen(buf) > safesize){
-      memmove(buf,&buf[strlen(buf) - safesize],safesize);
-      buf[safesize] = '\0';
-    }
-    char *s, *e;
-    if ((e = strchr(buf, '\n')))
-    {
-      e[0] = '\0';
-      if ((s = strrchr(buf, '[')))
-      {
-        sscanf(s, "[%d,%d]\n", &target_vel[0], &target_vel[1]);
-        target_vel[0] = constrain(target_vel[0],-SPEED_LIMIT,SPEED_LIMIT);
-        target_vel[1] = constrain(target_vel[1],-SPEED_LIMIT,SPEED_LIMIT);
-      }
-      memmove(buf, &e[1], strlen(&e[1]) + sizeof(char));
-    }
-  }
-}
-
-void moveMotor()
-{
-  leftMotor.Set(-1*target_vel[0]);
-  rightMotor.Set(target_vel[1]);
-  //Serial.print(target_vel[0]);
-  //Serial.println(target_vel[1]);
-}
-
-
-float declinationAngle = -0.22;
-void getCompass(){
-  /* Get a new sensor event */
-  sensors_event_t event;
-  mag.getEvent(&event);
-
-  //Calculate heading
-  heading = atan2(event.magnetic.y, event.magnetic.x);
-
-  //Magnetic field error in Piscataway
-  //https://www.ngdc.noaa.gov/geomag-web/
-  heading += declinationAngle;
-
-  if(heading < 0)
-    heading += 2*PI;
-
-  // Check for wrap due to addition of declination.
-  if(heading > 2*PI)
-    heading -= 2*PI;
-  //Convert to degrees
-  heading = heading *180/M_PI;
-}
-
-
-char ftos [safesize];
-void writeSerial()
-{
-  memset(write_buffer,'\0',BUFSIZE);
-  strcat(write_buffer, "[uno,");
-  dtostrf(heading,20,10,ftos);
-  strcat(write_buffer, ftos);
-  strcat(write_buffer, "]\n");
-  Serial.write(write_buffer);
-}
-


putatitve (doesn't work) commit due to float print error

--- html/examples/01.Basics/ReadAnalogVoltage/ReadAnalogVoltage.ino
+++ html/examples/01.Basics/ReadAnalogVoltage/ReadAnalogVoltage.ino
@@ -1,23 +1,37 @@
 /*
   ReadAnalogVoltage
-  Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
-  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
+  Reads an analog input on pin A1, converts it to voltage, and prints the result to the serial monitor.
+  Attach the center pin of a potentiometer to pin A1, and the outside pins to A2 and A0.

  This example code is in the public domain.
  */

 // the setup routine runs once when you press reset:
+int calibrationValue;
 void setup() {
-  // initialize serial communication at 9600 bits per second:
-  Serial.begin(9600);
+  // the chibitronics implementation always runs at 115200 regardless of the argument
+  Serial.begin(115200);
+
+  pinMode(A0, OUTPUT);
+  digitalWrite(A0, LOW);   // A0 is the - reference
+
+  pinMode(A2, OUTPUT);
+  digitalWrite(A2, HIGH);  // A2 is the + voltage
+
+  pinMode(A1, INPUT);      // A1 is the sensor input
+
+  pinMode(A6, INPUT);      // A6 is the "bandgap" reference, it is stable at 1V over temperature and different chips
+
+  // use A6 bandgap value to calibrate our voltage!
+  calibrationValue = analogRead(A6);
 }

 // the loop routine runs over and over again forever:
 void loop() {
   // read the input on analog pin 0:
-  int sensorValue = analogRead(A0);
-  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
-  float voltage = sensorValue * (5.0 / 1023.0);
+  int sensorValue = analogRead(A1);
+  // Convert the analog reading (which goes from 0 - 4096) to a voltage (0 - 3.3V):
+  float voltage = (sensorValue / calibrationValue) * 1.0;
   // print out the value you read:
   Serial.println(voltage);
 }


add comment

add comment

--- examples/FirebasePush_ESP8266/FirebasePush_ESP8266.ino
+++ examples/FirebasePush_ESP8266/FirebasePush_ESP8266.ino
@@ -46,6 +46,7 @@
       Serial.println(logs.error().message());
       return;
   }
+  // print response.
   Serial.println(l);
   // print all entries.
   Serial.println(logs.val());


Updated to use keypad and send preset CAN messages

--- src/CAN/CAN_SHA1_send/CAN_SHA1_send.ino
+++ src/CAN/CAN_SHA1_send/CAN_SHA1_send.ino
@@ -7,8 +7,8 @@
 // For keypad
 char Keys[] = {
   '4','3','2','1',
-  '5','6','7','8',
-  '9','A','B','C',
+  '8','7','6','5',
+  'C','B','A','9',
   'D','E','#','*'
 };

@@ -25,6 +25,8 @@
 const int MIL_ID = 0x7e0;
 const int DOOR_ID = 0x7d0;
 const int ENGINE_ID = 0x7a0;
+bool SHOULD_GENERATE_MESSAGES = false;
+const int DELAY_TIME = 100; // milliseconds

 // Preset CAN messages (for IR remote)
 typedef enum {
@@ -108,18 +110,36 @@
             Serial << "Pressed: " << Key << "\n";
             switch(Key)
             {
-                case 'C':
+                case '1':
                   SendPresetMessage(UNLOCK_DOORS);
                   break;
+                case '2':
+                  SendPresetMessage(LOCK_DOORS);
+                  break;
+                case '3':
+                  SendPresetMessage(MIL_ON);
+                  break;
+                case '4':
+                  SendPresetMessage(MIL_OFF);
+                  break;
+                case '5':
+                  SendPresetMessage(ENGINE_GREEN);
+                  break;
+                case '6':
+                  SendPresetMessage(ENGINE_RED);
+                  break;
+                case '7':
+                  SendPresetMessage(ENGINE_BLUE);
+                  break;
                 case '*':
-                  SendPresetMessage(LOCK_DOORS);
+                  SHOULD_GENERATE_MESSAGES = !SHOULD_GENERATE_MESSAGES;
                   break;
                 default:
                   break;
             }
         }
     }
-    else if (false)
+    else if (SHOULD_GENERATE_MESSAGES)
     {
         // Otherwise, if the user didn't input a message,
         // generate a random, valid CAN message
@@ -139,7 +159,8 @@

     // Flush the serial buffer
     Serial.flush();
-    delay(1000);    // delay to actually be able to see serial output
+    if (SHOULD_GENERATE_MESSAGES)
+      delay(DELAY_TIME);    // delay to actually be able to see serial output
 }

@@ -403,13 +424,24 @@
           break;
         case ENGINE_GREEN:
           id = ENGINE_ID;
-          dlc = 2;
+          dlc = 3;
+          data[0] = 0x10;
+          data[1] = 0xF0;
+          data[2] = 0x10;
+          break;
+        case ENGINE_RED:
+          id = ENGINE_ID;
+          dlc = 3;
+          data[0] = 0xB0;
+          data[1] = 0x00;
+          data[2] = 0x00;
+          break;
+        case ENGINE_BLUE:
+          id = ENGINE_ID;
+          dlc = 3;
           data[0] = 0x10;
           data[1] = 0x10;
-          break;
-        case ENGINE_RED:
-          break;
-        case ENGINE_BLUE:
+          data[2] = 0xF0;
           break;
         default:
           break;


MultiColor lights

MultiColor lights

--- arduino/arduinoMultiColorLights/arduinoMultiColorLights.ino
+++ arduino/arduinoMultiColorLights/arduinoMultiColorLights.ino
@@ -76,19 +76,12 @@

 void ethernetSucceeded(){
   Serial.println("Ethernet Succeeded");
-      redIntensity = 255;
-      greenIntensity = 255;
-  for(blueIntensity= 225;blueIntensity > 0;blueIntensity-=5){
-
-

       analogWrite(GREEN_LED_PIN, 20);
     analogWrite(BLUE_LED_PIN, 0);
     analogWrite(RED_LED_PIN, 0);

-
-    delay(DISPLAY_TIME);
-  }
+
 }


ignore

ignore

--- ai_projecto.ino
+++ ai_projecto.ino
@@ -13,7 +13,7 @@
 int const MIN = 50;     // Minimum theta angle
 int const MAX = 140;    // Maximum theta angle
 int const mspeed = 100; // Motor Speed in ms
-float set_point = 15;    // Set point
+float set_point = 5;    // Set point

 Fuzzy* fuzzyObj = new Fuzzy();


さらなる省エネ化を行った.

さらなる省エネ化を行った.

--- arduino/GeneralIoSerial/GeneralIoSerial.ino
+++ arduino/GeneralIoSerial/GeneralIoSerial.ino
@@ -20,7 +20,7 @@

 // コマンドの文字列の先頭の文字と処理する関数を保持する構造体
 struct TASK_FUNC {
-  String prefix;
+  char* prefix;
   TASK_FUNC_PTR func;
 };

@@ -45,7 +45,7 @@
      {port}  => port number.
      example => ai/read/0
    */
-  {String("ai/read/"), &aiReadTask},
+  {"ai/read/", &aiReadTask},

   /*
     Switch AI reference volt.
@@ -53,7 +53,7 @@
     {TYPE}  => DEFAULT | INTERNAL | EXTERNAL
     example => ai/ref?type=INTERNAL
    */
-  {String("ai/ref"), &aiRefSwitchTask},
+  {"ai/ref", &aiRefSwitchTask},

   /*
      Write AO port.
@@ -62,7 +62,7 @@
      {val}   => write value.
      example => ao/write/1?val=100
    */
-  {String("ao/write/"), &aoWriteTask},
+  {"ao/write/", &aoWriteTask},

   /*
      Read DI port.
@@ -70,7 +70,7 @@
      {port}  => port number.
      example => di/read/2
    */
-  {String("di/read/"), &diReadTask},
+  {"di/read/", &diReadTask},

   /*
@@ -81,7 +81,7 @@
      example => do/write/3?val=1
      example => do/write/3?val=HIGH
    */
-  {String("do/write/"), &doWriteTask},
+  {"do/write/", &doWriteTask},

   /*
      Swith digital pin mode.
@@ -90,13 +90,13 @@
      {type}   => INPUT | OUTPUT | INPUT_PULLUP
      example => d/mode/3?type=INPUT
    */
-  {String("d/mode/"), &switchPinModeTask},
+  {"d/mode/", &switchPinModeTask},

   /*
      Close serial port.
      format => system/close
    */
-  {String("system/close"), &closeSerial}
+  {"system/close", &closeSerial}
 };

 void setup() {


Invert state

Invert state

--- src/homie-sonoff-touch.ino
+++ src/homie-sonoff-touch.ino
@@ -70,9 +70,9 @@
      tripletimer = timestamp;

      Serial.print("Button is now: ");
-     Serial.println(buttonState ? "pressed" : "released");
+     Serial.println(buttonState ? "released" : "pressed");

-     if (Homie.setNodeProperty(buttonNode, "state", buttonState ? "pressed" : "released", true)) {
+     if (Homie.setNodeProperty(buttonNode, "state", buttonState ? "released" : "pressed", true)) {
        lastbuttonState = buttonState;
      } else {
        Serial.println("Sending failed");


Added A4983 test code

Added A4983 test code

--- lab/Stepper_eval/Stepper_eval.ino
+++ lab/Stepper_eval/Stepper_eval.ino
@@ -10,23 +10,35 @@
 #define DRV8825_MODE2 5
 #define DRV8825_ENABLE 6

+//A4983 pins
+#define A4983_STEP 7
+#define A4983_MODE0 3 //Same as DRV8825
+#define A4983_MODE1 4 //Same as DRV8825
+#define A4983_MODE2 5 //Same as DRV8825
+#define A4983_ENABLE 8

 void setup() {
   Serial.begin(9600);
+  pinMode(13, OUTPUT);

   //DRV8825 pin config
-  pinMode(13, OUTPUT);
   pinMode(DRV8825_STEP, OUTPUT);
   pinMode(DRV8825_MODE0, OUTPUT);
   pinMode(DRV8825_MODE1, OUTPUT);
   pinMode(DRV8825_MODE2, OUTPUT);
   pinMode(DRV8825_ENABLE, OUTPUT);

+  //DRV8825 pin config
+  pinMode(A4983_STEP, OUTPUT);
+  pinMode(A4983_ENABLE, OUTPUT);
+
   digitalWrite(DRV8825_STEP, LOW);
   digitalWrite(DRV8825_MODE0, LOW);
   digitalWrite(DRV8825_MODE1, LOW);
   digitalWrite(DRV8825_MODE2, LOW);
-  digitalWrite(DRV8825_ENABLE, LOW);
+  digitalWrite(DRV8825_ENABLE, HIGH);
+  digitalWrite(A4983_STEP, LOW);
+  digitalWrite(A4983_ENABLE, HIGH);

   //Timer variables for steps
   blink_t = millis();
@@ -48,6 +60,8 @@
     Serial.write(Serial.read());
   }

+#if 0
+  //DRV8825
   //One revolution, then wait one cycle
   if (tu - step_t > step_wait) {
     //One fullstep lap (two toggles per step)
@@ -106,6 +120,65 @@
     step_count += 1;
     step_t = tu;
   }
+#endif
+
+
+
+#if 1
+  //A4983
+  //One revolution, then wait one cycle
+  if (tu - step_t > step_wait) {
+    //One fullstep lap (two toggles per step)
+    if (step_count > mode_div*400) {
+      digitalWrite(A4983_ENABLE, !digitalRead(A4983_ENABLE));
+      step_count = 0;
+
+      if (digitalRead(A4983_ENABLE) == LOW) {
+        //Change step mode
+        if (mode == 4) mode = 0;
+        else mode += 1;
+
+        if (mode == 0) {
+          digitalWrite(A4983_MODE0, LOW);
+          digitalWrite(A4983_MODE1, LOW);
+          digitalWrite(A4983_MODE2, LOW);
+          mode_div = 1;
+          step_wait = 1000;
+        } else if (mode == 1) {
+          digitalWrite(A4983_MODE0, HIGH);
+          digitalWrite(A4983_MODE1, LOW);
+          digitalWrite(A4983_MODE2, LOW);
+          mode_div = 2;
+          step_wait = 500;
+        } else if (mode == 2) {
+          digitalWrite(A4983_MODE0, LOW);
+          digitalWrite(A4983_MODE1, HIGH);
+          digitalWrite(A4983_MODE2, LOW);
+          mode_div = 4;
+          step_wait = 250;
+        } else if (mode == 3) {
+          digitalWrite(A4983_MODE0, HIGH);
+          digitalWrite(A4983_MODE1, HIGH);
+          digitalWrite(A4983_MODE2, LOW);
+          mode_div = 8;
+          step_wait = 125;
+        } else {
+          digitalWrite(A4983_MODE0, HIGH);
+          digitalWrite(A4983_MODE1, HIGH);
+          digitalWrite(A4983_MODE2, HIGH);
+          mode_div = 16;
+          step_wait = 62;
+        }
+      }
+    }
+
+    if (digitalRead(A4983_ENABLE) == LOW) {
+      digitalWrite(A4983_STEP, !digitalRead(A4983_STEP));
+    }
+    step_count += 1;
+    step_t = tu;
+  }
+#endif

   //Blink every second
   if (tm - blink_t > 1000) {


Fixed ip and LED pins

Fixed ip and LED pins

--- map/map.ino
+++ map/map.ino
@@ -6,7 +6,15 @@

 ESP8266WebServer server(80);

+IPAddress ip(192,168,0,21); // fixed IP address
+IPAddress gateway(192,168,0,255); // network gateway address
+IPAddress subnet(255,255,255,0); // network subnet mask
+
 const int led = 13;
+
+const int LED01 = D5;
+const int LED02 = D6;
+const int LED03 = D7;

 void handleRoot() {
     digitalWrite(led, 1);


non-sense files deleted

non-sense files deleted

--- Hardware/Ultrasonido_2.ino
+++ Hardware/Ultrasonido_2.ino
@@ -1,72 +0,0 @@
-/// Ultrasonic Senso/
-
-// defines pins numbers
-
-//Ultrasonido
-const int trigPin = 9;
-const int echoPin = 8;
-//Ultrasonido2
-const int trigPin2 = 11;
-const int echoPin2 = 10;
-// defines variables ultrasonido
-long duration;
-int distance;
-// defines variables ultrasonido2
-long duration2;
-int distance2;
-
-void setup() {
-Serial.begin(9600); // Starts the serial communication
-//Ultrasonido1
-pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
-pinMode(echoPin, INPUT); // Sets the echoPin as an Input
-//Ultrasonido2
-pinMode(trigPin2, OUTPUT); // Sets the trigPin as an Output
-pinMode(echoPin2, INPUT); // Sets the echoPin as an Inpu
-
-}
-
-void loop(){
-  if(Serial.available()){
-    delay(10);
-// Clears the trigPin
-digitalWrite(trigPin, LOW);
-delayMicroseconds(2);
-
-
-// Sets the trigPin on HIGH state for 10 micro seconds
-digitalWrite(trigPin, HIGH);
-delayMicroseconds(10);
-digitalWrite(trigPin, LOW);
-
-// Reads the echoPin, returns the sound wave travel time in microseconds
-duration = pulseIn(echoPin, HIGH);
-
-
-// Calculating the distance Ultrasonido
-distance= duration/74/2;
-
-// Prints the distance on the Serial Monitor
-Serial.print("Distance: ");
-Serial.println(distance);
-
-//Clears the trigPin2
-digitalWrite(trigPin2, LOW);
-delayMicroseconds(2);
-
-// Sets the trigPin2 on HIGH state for 10 micro seconds
-digitalWrite(trigPin2, HIGH);
-delayMicroseconds(10);
-digitalWrite(trigPin2, LOW);
-
-// Reads the echoPin2, returns the sound wave travel time in microseconds
-duration2 = pulseIn(echoPin2, HIGH);
-
-// Calculating the distance Ultrasonido2
-distance2= duration2/74/2;
-
-// Prints the distance on the Serial Monitor
-Serial.print("Distance2: ");
-Serial.println(distance2);
-}
-}


More stable loopback

More stable loopback

--- tests/loopback/EchoEsp8266_standalone/EchoEsp8266_standalone.ino
+++ tests/loopback/EchoEsp8266_standalone/EchoEsp8266_standalone.ino
@@ -36,7 +36,7 @@

 void loop(void)
 {
-  Serial.print("Connecting to ");
+  Serial.print(F("Connecting to "));
   Serial.println(ip);

   WiFiClient client;
@@ -48,11 +48,12 @@
       int qty = client.available();
       if (qty) {
         qty = client.read((uint8_t*)buf, qty);
-        delay(0); // Allow esp8266 housekeeping
+        yield();
         qty = client.write((const uint8_t*)buf, qty);
+        yield();
         draw('.');
       }
-      delay(0); // Allow esp8266 housekeeping
+      yield();
     }
   } else {
     Serial.println(F("Connection failed"));


pin num

pin num

--- sketches/foobar/foobar.ino
+++ sketches/foobar/foobar.ino
@@ -1,16 +1,16 @@
 int BAUD = 9600;
 char MESSAGE[] = "{\"foo\":0,\"bar\":1}";
-
+int LED_PIN = 13;
 void setup() {
   Serial.begin(BAUD);
-  pinMode(13, OUTPUT);
+  pinMode(LED_PIN, OUTPUT);
 }

 void loop() {
-  digitalWrite(13, HIGH);
+  digitalWrite(LED_PIN, HIGH);
   if (Serial.available() > 0) {
     Serial.read();
     Serial.println(MESSAGE);
   }
-  digitalWrite(13, LOW);
+  digitalWrite(LED_PIN, LOW);
 }


fixed spaces

fixed spaces

--- src/kit_iot/kit_iot.ino
+++ src/kit_iot/kit_iot.ino
@@ -19,13 +19,13 @@
 void loop() {
   while (Serial.available() > 0) {
     char x = Serial.read();
-
+
     if (x == '!') {
       index = 0;      // start
-
+
     } else if (x == '.') {
       process(); // end
-
+
     } else {
       messageBuffer[index++] = x;
     }
@@ -40,35 +40,35 @@

   strncpy(cmd, messageBuffer, 2);
   cmd[2] = '\0';
-
+
   strncpy(pin, messageBuffer + 2, 2);
   pin[2] = '\0';

   if (atoi(cmd) > 90) {
     strncpy(val, messageBuffer + 4, 2);
     val[2] = '\0';
-
+
     strncpy(aux, messageBuffer + 6, 3);
     aux[3] = '\0';
-
+
   } else {
     strncpy(val, messageBuffer + 4, 3);
     val[3] = '\0';
-
+
     strncpy(aux, messageBuffer + 7, 3);
     aux[3] = '\0';
   }
-
+
   Debug(messageBuffer);
-
+
   int cmdid = atoi(cmd);

   switch (cmdid) {
-    case 1 :  dw(pin,val);     break;
-    case 2 :  dr(pin,val);     break;
-    case 3 :  aw(pin,val);     break;
-    case 4 :  ar(pin,val);     break;
-    case 5 :  dht11Read(pin);  break;
+    case 1 : dw(pin,val);     break;
+    case 2 : dr(pin,val);     break;
+    case 3 : aw(pin,val);     break;
+    case 4 : ar(pin,val);     break;
+    case 5 : dht11Read(pin);  break;
     case 99: toggleDebug(val); break;
     default:                   break;
   }
@@ -81,7 +81,7 @@
   if (atoi(val) == 0) {
     debug = false;
     Serial.println("goodbye");
-
+
   } else {
     debug = true;
     Serial.println("hello");
@@ -93,22 +93,22 @@
  */
 void ar(char *pin, char *val) {
   Debug("ar");
-
-  int p = getPin(pin);
-
-  if(p == -1) {
-    Debug("badpin");
-    return;
-  }
-
+
+  int p = getPin(pin);
+
+  if(p == -1) {
+    Debug("badpin");
+    return;
+  }
+
   pinMode(p, INPUT);
   int rval = analogRead(p);
-
+
   Serial.println(pin);
   if (pin == "A0") {
     Serial.println("yeahh");
   }
-
+
   char m[8];
   sprintf(m, "%s::%03d", pin, rval);
   Serial.println(m);
@@ -120,15 +120,15 @@
  */
 void aw(char *pin, char *val) {
   Debug("aw");
-
+
   int p = getPin(pin);
   pinMode(p, OUTPUT);
-
-  if(p == -1) {
-    Debug("badpin");
-    return;
-  }
-
+
+  if(p == -1) {
+    Debug("badpin");
+    return;
+  }
+
   analogWrite(p,atoi(val));
 }

@@ -138,19 +138,19 @@
  */
 void dw(char *pin, char *val) {
   Debug("dw");
-
-  int p = getPin(pin);
-
-  if(p == -1) {
-    Debug("badpin");
-    return;
-  }
-
+
+  int p = getPin(pin);
+
+  if(p == -1) {
+    Debug("badpin");
+    return;
+  }
+
   pinMode(p, OUTPUT);
-
+
   if (atoi(val) == 0) {
     digitalWrite(p, LOW);
-
+
   } else {
     digitalWrite(p, HIGH);
   }
@@ -161,17 +161,17 @@
  */
 void dr(char *pin, char *val) {
   Debug("dr");
-
-  int p = getPin(pin);
-
-  if(p == -1) {
-    Debug("badpin");
-    return;
-  }
-
+
+  int p = getPin(pin);
+
+  if(p == -1) {
+    Debug("badpin");
+    return;
+  }
+
   pinMode(p, INPUT);
   int oraw = digitalRead(p);
-
+
   char m[7];
   sprintf(m, "%02d::%02d", p,oraw);
   Serial.println(m);
@@ -183,21 +183,21 @@
  */
 int getPin(char *pin) {
   int ret = -1;
-
+
   if(pin[0] == 'A' || pin[0] == 'a') {
     switch(pin[1]) {
-      case '0':  ret = A0; break;
-      case '1':  ret = A1; break;
-      case '2':  ret = A2; break;
-      case '3':  ret = A3; break;
-      case '4':  ret = A4; break;
-      case '5':  ret = A5; break;
-      default:             break;
+      case '0': ret = A0; break;
+      case '1': ret = A1; break;
+      case '2': ret = A2; break;
+      case '3': ret = A3; break;
+      case '4': ret = A4; break;
+      case '5': ret = A5; break;
+      default:            break;
     }
-
+
   } else {
     ret = atoi(pin);
-
+
     if(ret == 0 && (pin[0] != '0' || pin[1] != '0')) {
       ret = -1;
     }
@@ -212,14 +212,14 @@
 void dht11Read(char *pin) {
   Debug("dht11Read");
   int p = getPin(pin);
-
-  if(p == -1) {
-    Debug("badpin");
-    return;
-  }
-
+
+  if(p == -1) {
+    Debug("badpin");
+    return;
+  }
+
   int chk = DHT11.read(atoi(pin));
-
+
   char m[7];
   sprintf(m, "%s::%d::%d", pin, DHT11.temperature, DHT11.humidity);
   Serial.println(m);