Remove old bridge sensor sketch

Remove old bridge sensor sketch

--- Arduino/bridge_sensor/bridge_sensor.ino
+++ Arduino/bridge_sensor/bridge_sensor.ino
@@ -1,558 +0,0 @@
-#include <LowPower.h>
-#include <math.h>
-#include <SdFat.h>
-#include <SPI.h>
-#include <String.h>
-#include <Time.h>
-
-
-// Analog Pins
-#define THERMISTOR_PIN 5
-#define ULTRASONIC_PIN 6
-
-
-// Digital Pins
-#define MOSFET_RTC_PIN   3
-#define MOSFET_SD_PIN    4
-#define MOSFET_US_PIN    5
-#define MOSFET_GSM_PIN   6
-#define MOSFET_THERM_PIN 7
-#define RTC_CS_PIN       8
-#define GSM_PWRKEY       9
-#define SD_CS_PIN        10
-
-
-// Settings
-// ----------------------------------
-#define SEND_DATA_AFTER_X_READINGS 4
-#define SLEEP_CYCLES 4
-#define NUM_THERM_READINGS 5
-#define THERM_READING_DELAY 20
-#define NUM_DISTANCE_READINGS  3
-#define DISTANCE_READING_DELAY 200
-#define DATA_DELIM ';'
-#define BACKUP_FILENAME "backup.txt"
-#define UNSENT_FILENAME "unsent.txt"
-#define ERROR_FILENAME "error.txt"
-#define PHONE_NUMBER   "+16505033896"
-#define GSM_TIMEOUT 250
-#define SMS_TIMEOUT 100
-#define ERROR_GSM "GSM Failed"
-#define ERROR_SMS "SMS Failed"
-
-
-// Custom Datatypes
-// -------------------------------------
-typedef struct {
-  int distance;
-  int temperature;
-  time_t timestamp;
-} SensorReading;
-
-
-// Global Variables
-// -------------------------------------
-int numCachedReadings = 0;
-SensorReading sensorReadings[SEND_DATA_AFTER_X_READINGS];
-SdFat sd;
-SdFile fh;
-
-void setup()
-{
-  pinMode(SD_CS_PIN, OUTPUT);
-  pinMode(MOSFET_THERM_PIN, OUTPUT);
-}
-
-
-void loop()
-{
-
-  // 1. Wake up.
-  // -----------
-
-  // Enter idle state for 8 s with the rest of peripherals turned off.
-  // 98 sleep cycles will take a reading approximately every 13 minutes.
-  for (int i = 0; i < SLEEP_CYCLES; ++i)
-  {
-    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
-  }
-
-
-  // 2. Turn on thermistor.
-  // ----------------------
-  digitalWrite(MOSFET_THERM_PIN, HIGH);
-
-  // 3. Take 5 thermistor readings. (one every 20ms)
-  // -----------------------------------------------
-  int thermReadings[NUM_THERM_READINGS];
-  for (int i = 0; i < NUM_THERM_READINGS; ++i)
-  {
-    thermReadings[i] = analogRead(THERMISTOR_PIN);
-    delay(THERM_READING_DELAY);
-  }
-
-  // 4. Turn off thermistor.
-  // -----------------------
-  digitalWrite(MOSFET_THERM_PIN, LOW);
-  delay(500);
-
-  // 5. Average 5 thermistor readings.
-  // ---------------------------------
-  double sumTherm = 0;
-  for (int i = 0; i < NUM_THERM_READINGS; ++i)
-  {
-    sumTherm += thermReadings[i];
-  }
-  double avgTherm = sumTherm / NUM_THERM_READINGS;
-  avgTherm = 1023 / avgTherm - 1;
-  double R = 10000 / avgTherm;
-
-
-  // 6. Convert average thermistor reading into temperature.
-  // -------------------------------------------------------
-
-  // Steinhart-Hart, modified:
-  double avgTemperature = ( 3950.0 / (log( R / (10000.0 * exp( -3950.0 / 298.13 ) ) ) ) ) - 273.13;
-
-
-  // 7. Turn on ultrasonic sensor (MOSFET).
-  // --------------------------------------
-  digitalWrite(MOSFET_US_PIN, HIGH);
-  // Calibration time
-  delay(3000);
-
-
-  // 8. Take 3 distance readings. (One every 200ms)
-  // ----------------------------------------------
-  int distanceReadings[NUM_DISTANCE_READINGS];
-  for (int i = 0; i < NUM_DISTANCE_READINGS; ++i)
-  {
-    distanceReadings[i] = analogRead(ULTRASONIC_PIN);
-    delay(DISTANCE_READING_DELAY);
-  }
-
-
-  // 9. Turn off ultrasonic sensor (MOSFET).
-  // ---------------------------------------
-  digitalWrite(MOSFET_US_PIN, LOW);
-  delay(500);
-
-
-  // 10. Average 3 distance measurements.
-  // ------------------------------------
-  double sumDistance = 0.0;
-  for (int i = 0; i < NUM_DISTANCE_READINGS; ++i)
-  {
-    sumDistance += distanceReadings[i];
-  }
-  double avgDistance = sumDistance / NUM_DISTANCE_READINGS;
-
-
-  // 11. Use average temperature to calculate actual distance.
-  // ---------------------------------------------------------
-  double adjustedDistance = ( ( 331.1 + .6 * avgTemperature ) / 344.5 ) * avgDistance;
-
-  int roundedDistance = round(adjustedDistance);
-  int roundedTemperature = round(avgTemperature);
-
-
-  // 12. Get time from RTC Shield.
-  // -----------------------------
-  digitalWrite(MOSFET_RTC_PIN, HIGH);
-  delay(500);
-  rtc_init();
-  time_t unixTime = rtc_readTimeDate();
-  digitalWrite(MOSFET_RTC_PIN, LOW);
-  delay(500);
-
-  // 13. Combine time, distance, and temperature into a single string.
-  // -----------------------------------------------------------------
-  String dataString = String(unixTime) + " " + String(roundedDistance) + " " + String(roundedTemperature);
-
-  // Cache distance and time in global array variable
-  sensorReadings[numCachedReadings].distance = roundedDistance;
-  sensorReadings[numCachedReadings].temperature = roundedTemperature;
-  sensorReadings[numCachedReadings].timestamp = unixTime;
-  numCachedReadings += 1;
-
-
-  // 14. Turn on SD Card.
-  // 15. Save data string to text file on SD card: "1399506809 1000 100" (roughly 20 characters)
-  // -------------------------------------------------------------------------------------------
-
-  //Turn on SD MOSFET.
-  digitalWrite(MOSFET_SD_PIN, HIGH);
-
-  // Try to turn on SD card. Should only need to be called once.
-  sd.begin(SD_CS_PIN, SPI_FULL_SPEED);
-  sd_writeToFile(BACKUP_FILENAME, dataString);
-  delay(1000);
-
-  // Turn off SD MOSFET.
-  digitalWrite(MOSFET_SD_PIN, LOW);
-  delay(500);
-
-  // 16. Are there 4 unsent data strings?
-  // 17. Yes. Send 4 unsent data strings in one SMS. Go to 18.
-  // -------------------------------------
-  if (numCachedReadings == SEND_DATA_AFTER_X_READINGS)
-  {
-    // 18. Prepare text message
-    // ---------------------
-    String textMessage = String(sensorReadings[0].timestamp) + " " + String(sensorReadings[0].distance) + " " + String(sensorReadings[0].temperature);
-    time_t startTime = sensorReadings[0].timestamp;
-    int minutesElapsed = 0;
-
-    // Format data to send as text message
-    for (int i = 1; i < numCachedReadings; ++i)
-    {
-      minutesElapsed = (sensorReadings[i].timestamp - startTime) / 60;
-      textMessage += String(DATA_DELIM) + String(minutesElapsed) + " " + String(sensorReadings[i].distance) + " " + String(sensorReadings[i].temperature);
-    }
-
-
-    // 19. Turn on GSM Shied.
-    // ---------------------
-
-    //Turn on GSM MOSFET.
-    digitalWrite(MOSFET_GSM_PIN, HIGH);
-    delay(1000);
-
-    // GSM baud rate. Start communication link with GSM shield.
-    Serial.begin(19200);
-    delay(100);
-
-    // Turn on GSM power pin.
-    digitalWrite(GSM_PWRKEY, HIGH);
-    delay(1000);
-
-    // Turn off GSM power pin.
-    digitalWrite(GSM_PWRKEY, LOW);
-    delay(1000);
-
-
-    // 20. Send text message if GSM Ready
-    if (gsm_ready(GSM_TIMEOUT) == true)
-    {
-      gsm_sendTextMessage(textMessage);
-      if (gsm_smsSent(SMS_TIMEOUT) == false)
-      {
-        // Log SMS failure
-        digitalWrite(MOSFET_SD_PIN, HIGH);
-        delay(1000);
-        sd.begin(SD_CS_PIN, SPI_FULL_SPEED);
-        sd_writeToFile(ERROR_FILENAME, String(unixTime) + ": " + ERROR_SMS);
-        sd_writeToFile(UNSENT_FILENAME, textMessage);
-        digitalWrite(MOSFET_SD_PIN, LOW);
-        delay(1000);
-      }
-    }
-    else
-    {
-      // Log GSM failure
-      digitalWrite(MOSFET_SD_PIN, HIGH);
-      delay(1000);
-      sd.begin(SD_CS_PIN, SPI_FULL_SPEED);
-      sd_writeToFile(ERROR_FILENAME, String(unixTime) + ": " + ERROR_GSM);
-      sd_writeToFile(UNSENT_FILENAME, textMessage);
-      digitalWrite(MOSFET_SD_PIN, LOW);
-      delay(1000);
-    }
-
-
-    // Reset number of cached readings
-    numCachedReadings = 0;
-
-
-    // 20. Turn off GSM.
-    // -----------------
-
-    // Turn on GSM power pin.
-    digitalWrite(GSM_PWRKEY, HIGH);
-    delay(1000);
-
-    // Turn off GSM power pin.
-    digitalWrite(GSM_PWRKEY, LOW);
-    delay(1000);
-
-    // Turn off GSM MOSFET.
-    digitalWrite(MOSFET_GSM_PIN, LOW);
-    delay(1000);
-  }
-}
-
-
-void gsm_sendTextMessage(String message)
-{
-  // Because we want to send the SMS in text mode
-  Serial.print("AT+CMGF=1\r");
-  delay(500);
-
-  // Send sms message, be careful need to add a country code before the cellphone number
-  Serial.println("AT + CMGS = \"" + String(PHONE_NUMBER) + "\"");
-  delay(500);
-
-  // The content of the message
-  Serial.println(message);
-  delay(500);
-
-  // The ASCII code of the ctrl+z is 26
-  Serial.println((char)26);
-  delay(500);
-}
-
-
-// Clears the GSM buffer to make sure we don't unexpected characters
-void gsm_clearBuffer()
-{
-   char c;
-   while (Serial.available() > 0)
-   {
-     c = Serial.read();
-   }
-}
-
-// Polls GSM buffer for "Call Ready" signal.
-boolean gsm_ready(int timeout)
-{
-  char gsmReady[] = "Call Ready";
-  char gsmReadyLength = 10;
-  int matched = 0;
-  char c;
-  while (timeout > 0)
-  {
-    while (Serial.available())
-    {
-        c = Serial.read();
-        if (c == gsmReady[matched])
-        {
-          matched += 1;
-          if (matched == gsmReadyLength)
-          {
-            return true;
-          }
-        } else {
-          matched = 0;
-        }
-      }
-      timeout -= 1;
-      delay(100);
-    }
-    return false;
-}
-
-
-// Polls GSM buffer for two "OK" messages or one "ERROR" to
-// check if SMS was sent successfully.
-boolean gsm_smsSent(int timeout)
-{
-  char smsOK[] = "OK";
-  int smsOKLength = 2;
-  int numOKNeeded = 2;
-
-  char smsError[] = "ERROR";
-  int smsErrorLength = 5;
-
-  char c;
-
-  int matchedError = 0;
-  int matchedOK = 0;
-  int foundOK = 0;
-
-  while (timeout > 0)
-  {
-    while (Serial.available())
-    {
-        c = Serial.read();
-        if (c == smsError[matchedError])
-        {
-          matchedError += 1;
-          matchedOK = 0;
-          if (matchedError == smsErrorLength)
-          {
-            return false;
-          }
-        }
-        else if (c == smsOK[matchedOK])
-        {
-          matchedOK += 1;
-          matchedError = 0;
-          if (matchedOK == smsOKLength)
-          {
-            foundOK += 1;
-          }
-
-          if (foundOK == smsOKLength)
-          {
-            return true;
-          }
-        } else {
-          matchedOK = 0;
-          matchedError = 0;
-        }
-      }
-      timeout -= 1;
-      delay(100);
-    }
-    return false;
-}
-
-
-// Saves data to specified file on SD Card
-//
-// Returns true if file written successfully, otherwise returns false.
-//
-boolean sd_writeToFile(char *filename, String data)
-{
-  if (fh.open(filename, O_RDWR | O_CREAT | O_AT_END))
-  {
-    fh.println(data);
-    fh.close();
-    return true;
-  }
-  else
-  {
-    return false;
-  }
-}
-
-// Reads file from sd card
-// TODO(richard-to): Need to test this implementation.
-//                   Not currently used in sketch.
-String sd_readFile(char *filename)
-{
-  char c;
-  String buffer = "";
-  if (fh.open(filename, O_READ))
-  {
-    while (fh.available())
-    {
-      c = fh.read();
-      buffer += c;
-    }
-    fh.close();
-  }
-  return buffer;
-}
-
-
-// Initializes RTC Clock
-int rtc_init()
-{
-  pinMode(RTC_CS_PIN, OUTPUT);
-
-  SPI.begin();
-  SPI.setBitOrder(MSBFIRST);
-  SPI.setDataMode(SPI_MODE3);
-
-  digitalWrite(RTC_CS_PIN, LOW);
-  SPI.transfer(0x8E);
-  SPI.transfer(0x60);
-  digitalWrite(RTC_CS_PIN, HIGH);
-  delay(10);
-}
-
-// Sets time on RTC CLOCK
-//
-// Notes:
-// * Year is calculated as `current year - 1970`. So 2014 would be 44 and not 14.
-// * Time is in UTC
-// * day(1-31), month(1-12), year(0-99), hour(0-23), minute(0-59), second(0-59)
-//
-int rtc_setTimeDate(int d, int mo, int y, int h, int mi, int s)
-{
-  int timedate[7] = {s, mi, h, 0, d, mo, y};
-  for (int i = 0; i <= 6; ++i)
-  {
-    if (i == 3)
-    {
-      i++;
-    }
-
-    int b = timedate[i] / 10;
-    int a = timedate[i] - b * 10;
-
-    if (i == 2)
-    {
-      if (b == 2)
-      {
-        b = B00000010;
-      }
-      else if (b == 1)
-      {
-        b = B00000001;
-      }
-    }
-
-    timedate[i] = a + (b << 4);
-
-    digitalWrite(RTC_CS_PIN, LOW);
-    SPI.transfer(i+0x80);
-    SPI.transfer(timedate[i]);
-    digitalWrite(RTC_CS_PIN, HIGH);
-  }
-}
-
-// Gets unix timestamp from RTC clock
-time_t rtc_readTimeDate()
-{
-  int timedate[7];
-  for (int i = 0; i <= 6; ++i)
-  {
-    if (i == 3)
-    {
-      i++;
-    }
-
-    digitalWrite(RTC_CS_PIN, LOW);
-    SPI.transfer(i + 0x00);
-    unsigned int n = SPI.transfer(0x00);
-    digitalWrite(RTC_CS_PIN, HIGH);
-    int a = n & B00001111;
-
-    if (i == 2)
-    {
-      int b = (n & B00110000) >> 4;
-      if (b == B00000010)
-      {
-        b = 20;
-      } else if (b == B00000001)
-      {
-        b = 10;
-      }
-      timedate[i] = a + b;
-    }
-    else if (i == 4)
-    {
-      int  b = (n & B00110000) >> 4;
-      timedate[i] = a + b * 10;
-    }
-    else if (i == 5)
-    {
-      int b = (n & B00010000) >> 4;
-      timedate[i] = a + b * 10;
-    }
-    else if (i == 6)
-    {
-      int b = (n & B11110000) >> 4;
-      timedate[i] = a + b * 10;
-    }
-    else
-    {
-      int b = (n & B01110000) >> 4;
-      timedate[i] = a + b * 10;
-    }
-  }
-
-  TimeElements tm;
-  tm.Year = timedate[6];
-  tm.Month = timedate[5];
-  tm.Day = timedate[4];
-  tm.Hour = timedate[2];
-  tm.Minute = timedate[1];
-  tm.Second = timedate[0];
-
-  return makeTime(tm);
-}
-
-


Clean up all warnings with newer toolchain

--- analogjson.ino
+++ analogjson.ino
@@ -1,8 +1,16 @@
 //
-// Copyright (c) 2015 Neil Webber.
+// Copyright (c) 2015, 2016 Neil Webber.
 //
 // See LICENSE file for licensing terms.
 //
+
+// oddly, without this at the top of the file, function definitions split
+// across lines after the type don't work. Some arduino environment bug.
+// The FIRST function encountered must have the type and the function name
+// on ONE line. Others after can be split. Very odd ... didn't chase down.
+// August 2016 toolchain 1.6.11 on Mac
+void FIRST_FUNCTION_BUG() {}
+

 #include <SPI.h>
 #include <Ethernet.h>
@@ -105,6 +113,7 @@
     }
 }

+
 // ---------------
 //  JSMN helpers
 // ---------------
@@ -233,6 +242,53 @@
 // -----------------------

+// get a character
+//
+// Get a character from the client, with timeout and disconnect checks.
+// Returns the character, or -1 if unsuccessful.
+//
+// To protect against clients that connect and send nothing this bails
+// out after "too long". No "real" browser ever causes this but you can
+// test it by telnetting to port 80, entering at least one character and
+// then just waiting.
+//
+
+#define HTTPPARSE_TIMEOUT_SECONDS    20L
+#define HTTPPARSE_TIMEOUT            (HTTPPARSE_TIMEOUT_SECONDS * 1000L)
+
+int
+clientgetc(EthernetClient &ec, unsigned long t0)
+{
+    // NOTE that this is in fact a busy loop, but in practice there should
+    //      already be data when we are here. In any case it's not like we
+    //      have anything else to do and the TIMEOUT eventually applies.
+
+    while ((elapsed_time(t0) <= HTTPPARSE_TIMEOUT) && ec.connected()) {
+        if (ec.available())
+            return ec.read();
+    }
+    return -1;
+}
+
+// get n characters from the client
+// buf must be n+1 long (NUL added, which may or may not make sense but
+// it is always added at the end nevertheless)
+int
+clientgetn(EthernetClient &ec, char *buf, int n, unsigned long t0)
+{
+    for ( ; n > 0 ; --n) {
+        int i = clientgetc(ec, t0);
+
+        if (i == -1)
+            return -1;
+
+        *buf++ = (char)i;
+    }
+    *buf = '\0';
+    return 0;
+}
+
+
 // eatline - consume characters until LF
 //
 // Strictly speaking we should be looking for CRLF but
@@ -271,51 +327,7 @@
      }
 }

-// get a character
-//
-// Get a character from the client, with timeout and disconnect checks.
-// Returns the character, or -1 if unsuccessful.
-//
-// To protect against clients that connect and send nothing this bails
-// out after "too long". No "real" browser ever causes this but you can
-// test it by telnetting to port 80, entering at least one character and
-// then just waiting.
-//
-
-#define HTTPPARSE_TIMEOUT_SECONDS    20L
-#define HTTPPARSE_TIMEOUT            (HTTPPARSE_TIMEOUT_SECONDS * 1000L)
-
-int
-clientgetc(EthernetClient &ec, unsigned long t0)
-{
-    // NOTE that this is in fact a busy loop, but in practice there should
-    //      already be data when we are here. In any case it's not like we
-    //      have anything else to do and the TIMEOUT eventually applies.
-
-    while ((elapsed_time(t0) <= HTTPPARSE_TIMEOUT) && ec.connected()) {
-        if (ec.available())
-            return ec.read();
-    }
-    return -1;
-}
-
-// get n characters from the client
-// buf must be n+1 long (NUL added, which may or may not make sense but
-// it is always added at the end nevertheless)
-int
-clientgetn(EthernetClient &ec, char *buf, int n, unsigned long t0)
-{
-    for ( ; n > 0 ; --n) {
-        int i = clientgetc(ec, t0);
-
-        if (i == -1)
-            return -1;
-
-        *buf++ = (char)i;
-    }
-    *buf = '\0';
-    return 0;
-}
+

 // ------------
 // HTTP Parsing
@@ -353,7 +365,7 @@
 //

 struct urlfuncs {
-    char *url;
+    char const *url;
     int whatop;
     void (* f)(struct http_rq *, struct urlfuncs *);
 };
@@ -383,7 +395,7 @@
 int
 parsefirstline(struct http_rq *rp)
 {
-    char *p = NULL;
+    char const *qq;
     char c;
     int i;

@@ -396,20 +408,20 @@
     c = (char)i;
     if (c == 'G') {
         rp->operation = HTTPPARSE_GET;
-        p = "ET";
+        qq = "ET";
     } else if (c == 'P') {
         // if PUT becomes an option, add more logic here; for now...
         rp->operation = HTTPPARSE_POST;
-        p = "OST";
+        qq = "OST";
     } else
         return -1;

     // at this point we are looking for the rest of GET/POST (or disconnected)
-    while (*p != '\0') {
+    while (*qq != '\0') {
         if ((i = clientgetc(rp->client, rp->t0)) == -1)
             return -1;
         c = (char)i;
-        if (c != *p++)        // i.e., not matching expected GET or POST
+        if (c != *qq++)        // i.e., not matching expected GET or POST
             return -1;
     }

@@ -424,7 +436,7 @@
     // causes the request to be discarded. Choose your compile-time
     // constants/sizes according to your application requirements.

-    p = rp->bufp;
+    char *p = rp->bufp;

     for(;;) {   // go until hit ' ' or timeout or buffer limit
         if ((i = clientgetc(rp->client, rp->t0)) == -1)
@@ -746,7 +758,7 @@
 //        or   { "modes" : [ { "pin" : pp, "mode" : mm }, ... ] }
 //
 // But the digitalWrite API uses the same general outline, except
-// that instead of "pinmode" it says "digitalwrite" and instead of
+// that instead of "modes" it says "writes" and instead of
 // "mode" it says "value", and the list of allowed substitutions
 // (e.g., HIGH/LOW) is different. And, of course, the function to
 // be called is different.
@@ -758,12 +770,12 @@
 //

 struct pinop_params {
-    char *topobj;           // e.g., "modes"
+    char const *topobj;           // e.g., "modes"
     void (* callback)(int, int, struct pinop_params *);
     void *callback_data;
     char *tokbuf;
-    char *key1;              // e.g., "pin"
-    char *key2;              // e.g., "mode" or "value"
+    char const *key1;              // e.g., "pin"
+    char const *key2;              // e.g., "mode" or "value"
 };


Add manual mode lock, clean up mode checks for output

--- autotop986.ino
+++ autotop986.ino
@@ -6,8 +6,9 @@
   This auto-presses the open or close buttons for the convertible top on a Porsche 986
   for the specified open/close seconds automatically if you quickly tap the button.

-  If the button tap is longer (eg it is held down), the button reacts like normal
-  and is only auto-pressed for the same amount of time as the user is pressing.
+  If the button tap is longer (eg it is held down), the button goes into manual mode and reacts like normal,
+  i.e. is only auto-pressed for the same amount of time as the user is pressing.
+  Once engaged, manual mode remains active until no input has been received for a defined amount of time.

   If the top is already automatically opening or closing, a second press of either
   button cancels the auto-open proceedure.
@@ -30,6 +31,9 @@
 #define openTime 15600
 // time taken to close top
 #define closeTime 16400
+
+// time to lock in manual mode once engaged
+#define manualModeLockTime 1000

 // operation modes
 #define modeWait 0
@@ -39,7 +43,8 @@
 #define modeManualClose 4
 #define modeHalt 5

-unsigned long ms, motorStartTime;
+unsigned long ms, motorStartTime, manualModeReleaseTime;
+bool outputRequired = false;

 int currentMode = modeWait;
 int previousMode = modeWait;
@@ -95,6 +100,8 @@

 void updateMode() {

+  previousMode = currentMode;
+
   switch (currentMode) {

     case modeWait:
@@ -117,17 +124,28 @@
       break;
   }

+  outputRequired = currentMode != previousMode;
 }

 void updateModeWait() {
   log("updateModeWait");
   if (openButtonIn.on()) {
-    currentMode = modeAutoOpen;
-    motorStartTime = millis();
+    //if in manual lock
+    if (ms - manualModeReleaseTime < manualModeLockTime) {
+      currentMode = modeManualOpen;
+    } else {
+      currentMode = modeAutoOpen;
+      motorStartTime = millis();
+    }
   }
   if (closeButtonIn.on()) {
-    currentMode = modeAutoClose;
-    motorStartTime = millis();
+    //if in manual lock
+    if (ms - manualModeReleaseTime < manualModeLockTime) {
+      currentMode = modeManualClose;
+    } else {
+      currentMode = modeAutoClose;
+      motorStartTime = millis();
+    }
   }
 }

@@ -173,6 +191,7 @@
   //wait on button release
   if (!openButtonIn.on()) {
     currentMode = modeWait;
+    manualModeReleaseTime = millis();
   }
 }

@@ -181,6 +200,7 @@
   //wait on button release
   if (!closeButtonIn.on()) {
     currentMode = modeWait;
+    manualModeReleaseTime = millis();
   }
 }

@@ -195,7 +215,7 @@
 /** Output Functions */

 void sendOutput() {
-  if (currentMode != previousMode) {
+  if (outputRequired) {
     log("mode changed");
     Serial.println(currentMode);

@@ -207,8 +227,6 @@
       sendStop();
     }
   }
-
-  previousMode = currentMode;
 }

 void sendOpen() {


Comment changes

Comment changes

--- examples/GprsExample.ino
+++ examples/GprsExample.ino
@@ -40,15 +40,15 @@

 	gprs.openHttpConnection();
 	ModuleSerialGprs::HttpResponse httpResponse =
-		gprs.sendHttpRequest(HTTP_GET, "httpbin.org/get?param=1&param=2", 6000);	// Choose a method, set the url and the request timeout in milliseconds.
+		gprs.sendHttpRequest(HTTP_GET, "httpbin.org/get?param=1&param=2", 6000);	// Method, url and timeout in milliseconds.

 	if (httpResponse.statusCode == 200)
 	{
-		Serial.println(F("HTTP_GET response success!"));
+		Serial.println(F("Request success!"));

 		char response[500] = "";
 		int length = httpResponse.contentLength + 50 > 500 ?
-			450 : httpResponse.contentLength;					// Read the first 450 characters of the response.
+			450 : httpResponse.contentLength;	// Read the first 450 characters of the response.

 		gprs.readHttpResponse(length, response, 500);

@@ -56,7 +56,7 @@
 	}
 	else
 	{
-		Serial.println(F("HTTP failed."));
+		Serial.println(F("Request failed."));
 	}

 	gprs.closeHttpConnection();
@@ -72,7 +72,7 @@

 	if (httpResponse.statusCode == 200)
 	{
-		Serial.println(F("HTTP_POST response success!"));
+		Serial.println(F("Request success!"));

 		char response[500] = "";
 		int length = httpResponse.contentLength + 50 > 500 ?
@@ -84,7 +84,7 @@
 	}
 	else
 	{
-		Serial.println(F("HTTP failed."));
+		Serial.println(F("Request failed."));
 	}

 	gprs.closeHttpConnection();


Added NMEA parsing and logging to CSV file

--- telemetryUnit.ino
+++ telemetryUnit.ino
@@ -14,7 +14,7 @@
 // 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
+// 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);
@@ -24,7 +24,7 @@
 // Set to 'true' if you want to debug and listen to the raw GPS sentences
 #define GPSECHO  true
 /* set to true to only log to SD when GPS has a fix, for debugging, keep it false */
-#define LOG_FIXONLY false
+#define LOG_FIXONLY false

 // this keeps track of whether we're using the interrupt
 // off by default!
@@ -35,7 +35,34 @@
 #define chipSelect 10
 #define ledPin 13

-File logfile;
+////////////////////////////
+// Lof File related stuff //
+////////////////////////////
+#define LOG_FILE_PREFIX "gpslog"
+#define MAX_LOG_FILES 100
+#define LOG_FILE_SUFFIX "csv"
+char logFileName[13];
+
+#define LOG_COLUMN_COUNT 10
+char * log_col_names[LOG_COLUMN_COUNT] = {
+  "longitude",
+  "latitude",
+  "altitude",
+  "speed",
+  "course",
+  "date",
+  "time",
+  "satellites",
+  "fix",
+  "fixquality"
+};
+
+//////////////////////
+// Log Rate Control //
+//////////////////////
+#define LOG_RATE 1000 // Log every second
+unsigned long lastLog = 0; // Global var to keep of last time we logged
+

 // read a Hex value and return the decimal equivalent
 uint8_t parseHex(char c) {
@@ -107,11 +134,11 @@

   logfile = SD.open(filename, FILE_WRITE);
   if( ! logfile ) {
-    Serial.print("Couldnt create ");
+    Serial.print("Couldnt create ");
     Serial.println(filename);
     error(3);
   }
-  Serial.print("Writing to ");
+  Serial.print("Writing to ");
   Serial.println(filename);

   // connect to the GPS at the desired rate
@@ -144,9 +171,9 @@
   // if you want to debug, this is a good time to do it!
   #ifdef UDR0
       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.
+        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
 }

@@ -157,7 +184,7 @@
     OCR0A = 0xAF;
     TIMSK0 |= _BV(OCIE0A);
     usingInterrupt = true;
-  }
+  }
   else {
     // do not call the interrupt function COMPA anymore
     TIMSK0 &= ~_BV(OCIE0A);
@@ -173,37 +200,140 @@
     if (GPSECHO)
       if (c) Serial.print(c);
   }
-
-  // if a sentence is received, we can check the checksum, parse it...
-  if (GPS.newNMEAreceived()) {
-    // a tricky thing here is if we print the NMEA sentence, or data
-    // we end up not listening and catching other sentences!
-    // so be very wary if using OUTPUT_ALLDATA and trying to print out data
-
-    // Don't call lastNMEA more than once between parse calls!  Calling lastNMEA
-    // will clear the received flag and can cause very subtle race conditions if
-    // new data comes in before parse is called again.
-    char *stringptr = GPS.lastNMEA();
-
-    if (!GPS.parse(stringptr))   // this also sets the newNMEAreceived() flag to false
-      return;  // we can fail to parse a sentence in which case we should just wait for another
-
-    // Sentence parsed!
-    Serial.println("OK");
-    if (LOG_FIXONLY && !GPS.fix) {
-      Serial.print("No Fix");
-      return;
-    }
-
-    // Rad. lets log it!
-    Serial.println("Log");
-
-    uint8_t stringsize = strlen(stringptr);
-    if (stringsize != logfile.write((uint8_t *)stringptr, stringsize))    //write the string to the SD file
-        error(4);
-    if (strstr(stringptr, "RMC") || strstr(stringptr, "GGA"))   logfile.flush();
+
+  { // If it's been LOG_RATE milliseconds since the last log:
+  if ((lastLog + LOG_RATE) <= millis())
+
+    // if a sentence is received, we can check the checksum, parse it...
+    if (GPS.newNMEAreceived() && GPS.parse(GPS.lastNMEA())) {
+
+      if (LOG_FIXONLY && !GPS.fix) {
+        Serial.println("No Fix");
+        return;
+      }
+
+      if (logGPSData()) // Log the GPS data
+      {
+        lastLog = millis(); // Update the lastLog variable
+      }
+      else // If we failed to log GPS
+      { // Print an error, don't update lastLog
+        Serial.println("Failed to log new GPS data.");
+      }
+
+    }
+  }
+}
+
+byte logGPSData()
+{
+  if (GPSECHO)
+  {
+    Serial.print(GPS.longitudeDegrees, 4);
+    Serial.print(',');
+    Serial.print(GPS.latitudeDegrees, 4);
+    Serial.print(',');
+    Serial.print(GPS.altitude, 1);
+    Serial.print(',');
+    Serial.print(GPS.speed, 1);
+    Serial.print(',');
+    Serial.print(GPS.angle, 1);
+    Serial.print(',');
+    Serial.print(GPS.day, DEC); Serial.print('/');
+    Serial.print(GPS.month, DEC); Serial.print("/20");
+    Serial.print(GPS.year, DEC);
+    Serial.print(',');
+    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(',');
+    Serial.print((int) GPS.satellites);
+    Serial.print(',');
+    Serial.print((int)GPS.fix);
+    Serial.print(',');
+    Serial.print((int)GPS.fixquality);
     Serial.println();
   }
+
+  File logFile = SD.open(logFileName, FILE_WRITE);
+  if (logFile)
+  {
+    logFile.print(GPS.longitudeDegrees, 4); logFile.print(GPS.lon);
+    logFile.print(',');
+    logFile.print(GPS.latitudeDegrees, 4); logFile.print(GPS.lat);
+    logFile.print(',');
+    logFile.print(GPS.altitude, 1);
+    logFile.print(',');
+    logFile.print(GPS.speed, 1);
+    logFile.print(',');
+    logFile.print(GPS.angle, 1);
+    logFile.print(',');
+    logFile.print(GPS.day, DEC); logFile.print('/');
+    logFile.print(GPS.month, DEC); logFile.print("/20");
+    logFile.print(GPS.year, DEC);
+    logFile.print(',');
+    logFile.print(GPS.hour, DEC); logFile.print(':');
+    logFile.print(GPS.minute, DEC); logFile.print(':');
+    logFile.print(GPS.seconds, DEC); logFile.print('.');
+    logFile.print(GPS.milliseconds);
+    logFile.print(',');
+    logFile.print((int) GPS.satellites);
+    logFile.print(',');
+    logFile.print((int)GPS.fix);
+    logFile.print(',');
+    logFile.print((int)GPS.fixquality);
+    logFile.println();
+    logFile.close();
+
+    return 1; // Return success
+  }
+
+  return 0; // If we failed to open the file, return fail
+}
+
+// printHeader() - prints our column names to the top of our log file
+void printHeader()
+{
+  File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file
+
+  if (logFile) // If the log file opened, print our column names to the file
+  {
+    int i = 0;
+    for (; i < LOG_COLUMN_COUNT; i++)
+    {
+      logFile.print(log_col_names[i]);
+      if (i < LOG_COLUMN_COUNT - 1) // If it's anything but the last column
+        logFile.print(','); // print a comma
+      else // If it's the last column
+        logFile.println(); // print a new line
+    }
+    logFile.close(); // close the file
+  }
+}
+
+// updateFileName() - Looks through the log files already present on a card,
+// and creates a new file with an incremented file index.
+void updateFileName()
+{
+  int i = 0;
+  for (; i < MAX_LOG_FILES; i++)
+  {
+    memset(logFileName, 0, strlen(logFileName)); // Clear logFileName string
+    // Set logFileName to "gpslogXX.csv":
+    sprintf(logFileName, "%s%d.%s", LOG_FILE_PREFIX, i, LOG_FILE_SUFFIX);
+    if (!SD.exists(logFileName)) // If a file doesn't exist
+    {
+      break; // Break out of this loop. We found our index
+    }
+    else // Otherwise:
+    {
+      Serial.print(logFileName);
+      Serial.println(" exists"); // Print a debug statement
+    }
+  }
+  Serial.print("File name: ");
+  Serial.println(logFileName); // Debug print the file name
 }


debugging

debugging

--- master/master.ino
+++ master/master.ino
@@ -233,7 +233,7 @@
 	otherRobot_tsopAngle  = (rx_packet[2] << 8) | rx_packet[3];
 	otherRobot_lineLocation = rx_packet[4];
 	otherRobot_powerOn = rx_packet[5];
-	Serial.print("received\t");
+	Serial.print(micros()); Serial.print('\t');
 	Serial.print(otherRobot_playMode); Serial.print('\t');
 	Serial.print(otherRobot_tsopStrength); Serial.print('\t');
 	Serial.print(otherRobot_tsopAngle); Serial.print('\t');


Typo fix

Typo fix

--- examples/ms5637_example/ms5637_example.ino
+++ examples/ms5637_example/ms5637_example.ino
@@ -18,17 +18,18 @@

   connected = m_ms5637.is_connected();
   if (connected) {
-    Serial.println(OK ? "Sensor Connected" : "Sensor Disconnected");
+    Serial.println(connected ? "Sensor Connected" : "Sensor Disconnected");

     status = m_ms5637.read_temperature_and_pressure(&temperature, &pressure);

     Serial.print("---Temperature = ");
     Serial.print(temperature, 1);
-    Serial.println(" C");
+    Serial.print((char)176);
+    Serial.println("C");

     Serial.print("---Pressure = ");
     Serial.print(pressure, 1);
-    Serial.println(" hPa");
+    Serial.println("hPa");
   } else {
     Serial.println(connected ? "Sensor Connected" : "Sensor Disconnected");
   }


add more RF sockets

add more RF sockets

--- Harmony_RF_Outlet/Harmony_RF_Outlet.ino
+++ Harmony_RF_Outlet/Harmony_RF_Outlet.ino
@@ -1,11 +1,11 @@
 /*
- * Build your own 'One-For-All HC8300 Light Control' with your Arduino!
- * Version 0.2
- *
- * This sketch lets you control wireless outlets with your Logitech Harmony Remote.
- * You need to add a 'One-For-All HC8300 Light Control'-Device to your Harmony,
- * because the IR-codes from this devices remote are used here.
- */
+   Build your own 'One-For-All HC8300 Light Control' with your Arduino!
+   Version 0.2
+
+   This sketch lets you control wireless outlets with your Logitech Harmony Remote.
+   You need to add a 'One-For-All HC8300 Light Control'-Device to your Harmony,
+   because the IR-codes from this devices remote are used here.
+*/
 #include "One_For_All_HC_8300_IR_Codes.h"

 // Libraries
@@ -18,13 +18,18 @@
 #define RF_TRANSMITTER_DATA 4

 // RF Socket Configuration
-char rfSystemCode[] = "00001";
-char rfSocket1[] = "10000"; // Main Poweroutlet
-char rfSocket2[] = "01000"; // Couch Lamps
-char rfSocket3[] = "00100"; // TV Lamp
+char rfSystemCode1[] = "00001";
+char rfSocket11[] = "10000"; // Main Poweroutlet
+char rfSocket12[] = "01000"; // Couch Lamps
+char rfSocket13[] = "00100"; // TV Lamp
+char rfSocket14[] = "00010"; // Lightstrip
+char rfSocket15[] = "00001"; // Unused
+
+char rfSystemCode2[] = "00010";
+char rfSocket21[] = "10000"; // Unused

 // Delay
-unsigned long powerOffDelay = 180000; // 3 mins
+unsigned long powerOffDelay = 60000; // 1 min

 decode_results results;
 long lastIRCode;
@@ -43,63 +48,102 @@
   if (irrecv.decode(&results)) {

     // REPEAT last IR code
-    if(results.value != REPEAT) {
+    if (results.value != REPEAT) {
       lastIRCode = results.value;
     }

     Serial.print("Received code ");
     Serial.println(lastIRCode, HEX);

-    switch(lastIRCode) {
+    switch (lastIRCode) {
       case HC8300_1ON: // Socket1 ON
         Serial.println("Switching Main-Poweroutlet on");
-        rcSwitch.switchOn(rfSystemCode, rfSocket1);
+        rcSwitch.switchOn(rfSystemCode1, rfSocket11);
         break;

       case HC8300_1OFF: // Socket1 OFF
         Serial.println("Switching Main-Poweroutlet off");
-        rcSwitch.switchOff(rfSystemCode, rfSocket1);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket11);
         break;

       case HC8300_2ON: // Socket2 ON
         Serial.println("Switching Couch Lamps on");
-        rcSwitch.switchOn(rfSystemCode, rfSocket2);
+        rcSwitch.switchOn(rfSystemCode1, rfSocket12);
         break;

       case HC8300_2OFF: // Socket2 OFF
         Serial.println("Switching Couch Lamps off");
-        rcSwitch.switchOff(rfSystemCode, rfSocket2);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket12);
         break;

       case HC8300_3ON: // Socket3 ON
         Serial.println("Switching TV Lamp on");
-        rcSwitch.switchOn(rfSystemCode, rfSocket3);
+        rcSwitch.switchOn(rfSystemCode1, rfSocket13);
         break;

       case HC8300_3OFF: // Socket3 OFF
         Serial.println("Switching TV Lamp off");
-        rcSwitch.switchOff(rfSystemCode, rfSocket3);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket13);
+        break;
+
+      case HC8300_4ON: // Socket4 ON
+        Serial.println("Switching Lightstrip on");
+        rcSwitch.switchOn(rfSystemCode1, rfSocket14);
+        break;
+
+      case HC8300_4OFF: // Socket4 OFF
+        Serial.println("Switching Lightstrip off");
+        rcSwitch.switchOff(rfSystemCode1, rfSocket14);
+        break;
+
+      case HC8300_5ON: // Socket5 ON
+        Serial.println("Switching Socket5 on");
+        rcSwitch.switchOn(rfSystemCode1, rfSocket15);
+        break;
+
+      case HC8300_5OFF: // Socket5 OFF
+        Serial.println("Switching Socket5 off");
+        rcSwitch.switchOff(rfSystemCode1, rfSocket15);
+        break;
+
+      case HC8300_6ON: // Socket6 ON
+        Serial.println("Switching Socket6 on");
+        rcSwitch.switchOn(rfSystemCode2, rfSocket21);
+        break;
+
+      case HC8300_6OFF: // Socket6 OFF
+        Serial.println("Switching Socket6 off");
+        rcSwitch.switchOff(rfSystemCode2, rfSocket21);
         break;

       case HC8300_9ON: // ALL ON
-        rcSwitch.switchOn(rfSystemCode, rfSocket1);
-        rcSwitch.switchOn(rfSystemCode, rfSocket2);
-        rcSwitch.switchOn(rfSystemCode, rfSocket3);
+        rcSwitch.switchOn(rfSystemCode1, rfSocket11);
+        rcSwitch.switchOn(rfSystemCode1, rfSocket12);
+        rcSwitch.switchOn(rfSystemCode1, rfSocket13);
+        rcSwitch.switchOn(rfSystemCode1, rfSocket14);
+        rcSwitch.switchOn(rfSystemCode1, rfSocket15);
+        rcSwitch.switchOn(rfSystemCode2, rfSocket21);
         break;

       case HC8300_9OFF: // ALL OFF
         Serial.println("Switching All OFF");
-        rcSwitch.switchOff(rfSystemCode, rfSocket3);
-        rcSwitch.switchOff(rfSystemCode, rfSocket2);
-        rcSwitch.switchOff(rfSystemCode, rfSocket1);
+        rcSwitch.switchOff(rfSystemCode2, rfSocket21);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket15);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket14);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket13);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket12);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket11);
         break;

       case HC8300_B1Off: // ALL OFF with Delay
         delay(powerOffDelay);
         Serial.println("Switching All OFF");
-        rcSwitch.switchOff(rfSystemCode, rfSocket3);
-        rcSwitch.switchOff(rfSystemCode, rfSocket2);
-        rcSwitch.switchOff(rfSystemCode, rfSocket1);
+        rcSwitch.switchOff(rfSystemCode2, rfSocket21);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket15);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket14);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket13);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket12);
+        rcSwitch.switchOff(rfSystemCode1, rfSocket11);
         break;

       default:


Randomize outputs process

Randomize outputs process

Randomized LED choice, as well as delay durations in the sketch.

--- outputs/outputs.ino
+++ outputs/outputs.ino
@@ -3,45 +3,32 @@
 outputs
 ========

-Sketches for Chapter 2 from the OSEPP "Arduino Companion" book,
+Randomly makes an array of LEDs twinkle for random durations.
+
+Besd on sketches for Chapter 2 from the OSEPP "Arduino Companion" book,
 *Arduino Basics*.

-
-Try to randomize delay and color on each loop
 */

-int LED0 = 2;
-int LED1 = 3;
-int LED2 = 4;
-int LED3 = 5;
-int delay_count = 200;
+int delay_count = 1200;

 void setup()
 {
-  pinMode(LED0, OUTPUT);
-  pinMode(LED1, OUTPUT);
-  pinMode(LED2, OUTPUT);
-  pinMode(LED3, OUTPUT);
-
+  int i;
+  // Start at pin 2, go up to 5
+  for (i = 2; i <= 5; i++)
+    pinMode(i, OUTPUT);
 }

 void loop()
 {
-  digitalWrite(LED0, HIGH);
-  delay(delay_count);
-  digitalWrite(LED0, LOW);
-  delay(delay_count);
-  digitalWrite(LED1, HIGH);
-  delay(delay_count);
-  digitalWrite(LED1, LOW);
-  delay(delay_count);
-  digitalWrite(LED2, HIGH);
-  delay(delay_count);
-  digitalWrite(LED2, LOW);
-  delay(delay_count);
-  digitalWrite(LED3, HIGH);
-  delay(delay_count);
-  digitalWrite(LED3, LOW);
-  delay(delay_count);
+  int led = random(2,6);
+  int delay_dur = random(0, delay_count);
+
+  digitalWrite(led, HIGH);
+  delay(delay_dur);
+  digitalWrite(led, LOW);
+  delay_dur = random(0, delay_count);
+  delay(delay_dur);
 }


refactor

refactor

--- RGB_matrix.ino
+++ RGB_matrix.ino
@@ -1,6 +1,6 @@
 #include "sounds.h"

-void setup() {
+void setup(){
     pinMode( 0, OUTPUT);
     pinMode( 1, OUTPUT);
     pinMode( 2, OUTPUT);
@@ -25,13 +25,15 @@
     digitalWrite(11, LOW);
     digitalWrite(12, LOW);
     digitalWrite(13, LOW);
+
+    analogReference(INTERNAL);
 }

-const int MODE0=0,MODE1=1,MODE2=2;
-
-void loop() {
+void loop(){
+    const int MODE0=0,MODE1=1,MODE2=2;
     static int mode = MODE0;

+    //このタイミングでスイッチ押されていれば、モード変更
     if(!digitalRead(9)) mode=(++mode)%3;

     if(mode==MODE0)      start1();
@@ -42,9 +44,8 @@
 }

 void start1(){
-    analogReference(INTERNAL);
-    int x=analogRead(5);
-    if(x<260) tone(8, 100,100);
+    int x = analogRead(5);
+    if(x<260)      tone(8, 100,100);
     else if(x<280) tone(8,  600,100);
     else if(x<300) tone(8, 1100,100);
     else if(x<320) tone(8, 1600,100);
@@ -54,7 +55,7 @@
     else if(x<400) tone(8, 3600,100);
     else if(x<420) tone(8, 4100,100);
     else if(x<440) tone(8, 4600,100);
-    else tone(8, 5100,100);
+    else           tone(8, 5100,100);
     delay(1000);
 }

@@ -65,82 +66,82 @@
             digitalWrite(6,LOW);
             digitalWrite(7,LOW);
         }
-        else if  (thisNote==5){
+        else if(thisNote==5){
             digitalWrite(5,HIGH);
             digitalWrite(6,LOW);
             digitalWrite(7,LOW);
         }
-        else if  (thisNote==10){
+        else if(thisNote==10){
             digitalWrite(5,LOW);
             digitalWrite(6,HIGH);
             digitalWrite(7,LOW);
         }
-        else if  (thisNote==15){
+        else if(thisNote==15){
             digitalWrite(5,LOW);
             digitalWrite(6,LOW);
             digitalWrite(7,HIGH);
         }
-        else if  (thisNote==20){
+        else if(thisNote==20){
             digitalWrite(5,HIGH);
             digitalWrite(6,LOW);
             digitalWrite(7,LOW);
         }
-        else if  (thisNote==25){
+        else if(thisNote==25){
             digitalWrite(5,LOW);
             digitalWrite(6,HIGH);
             digitalWrite(7,LOW);
         }
-        else if  (thisNote==30){
+        else if(thisNote==30){
             digitalWrite(5,LOW);
             digitalWrite(6,LOW);
             digitalWrite(7,HIGH);
         }
-        else if  (thisNote==35){
+        else if(thisNote==35){
             digitalWrite(5,HIGH);
             digitalWrite(6,LOW);
             digitalWrite(7,HIGH);
         }
-        else if  (thisNote==40){
+        else if(thisNote==40){
             digitalWrite(5,HIGH);
             digitalWrite(6,HIGH);
             digitalWrite(7,LOW);
         }
-        else if  (thisNote==45){
+        else if(thisNote==45){
             digitalWrite(5,LOW);
             digitalWrite(6,HIGH);
             digitalWrite(7,HIGH);
         }
-        else if  (thisNote==50){
+        else if(thisNote==50){
             digitalWrite(5,HIGH);
             digitalWrite(6,LOW);
             digitalWrite(7,HIGH);
         }
-        else if  (thisNote==55){
+        else if(thisNote==55){
             digitalWrite(5,HIGH);
             digitalWrite(6,HIGH);
             digitalWrite(7,LOW);
         }
-        else if  (thisNote==60){
+        else if(thisNote==60){
             digitalWrite(5,LOW);
             digitalWrite(6,HIGH);
             digitalWrite(7,HIGH);
         }
-        else if  (thisNote==65){
+        else if(thisNote==65){
             digitalWrite(5,HIGH);
             digitalWrite(6,LOW);
             digitalWrite(7,HIGH);
         }
-        else if  (thisNote==70){
+        else if(thisNote==70){
             digitalWrite(5,HIGH);
             digitalWrite(6,HIGH);
             digitalWrite(7,LOW);
         }
-        else if  (thisNote==75){
+        else if(thisNote==75){
             digitalWrite(5,LOW);
             digitalWrite(6,HIGH);
             digitalWrite(7,HIGH);
         }
-        else if  (thisNote==80){
+        else if(thisNote==80){
             digitalWrite(5,HIGH);
             digitalWrite(6,HIGH);
             digitalWrite(7,HIGH);


Rainbow button functionality.

Rainbow button functionality.

--- NeoPixelSwitchBox/NeoPixelSwitchBox.ino
+++ NeoPixelSwitchBox/NeoPixelSwitchBox.ino
@@ -73,7 +73,7 @@
   Switch randomButton(10, DEBOUNCE_TIME);

   //button on pin 11, debounce for DEBOUNCE_TIME
-  Switch rainbow(11, DEBOUNCE_TIME);
+  Switch rainbowButton(11, DEBOUNCE_TIME);

   /* Buttons */
   Switch toggleSpinButton(12, DEBOUNCE_TIME);
@@ -153,49 +153,47 @@
   }

   /* Broke this out into a separate method so it can be transmitted at startup */
-  vod handleSendSpinState() {
-      float spinKnobPercent = spinKnob.getPercentVal();
-      logger.log("spin knob changed to: ", spinKnobPercent);
-
-      /* If the knob is centered, send the special flag to the ring to stop spinning, and return */
-      if (potentiometerPercentAtMiddle(spinKnobPercent)) {
-        logger.log("Spin knob at center");
-        ring.spin(-1, true);
-        return;
-      }
-
-      /*
-        Clockwise if spin pot is >= midpoint
-        Determine "raw" amount spin knob is turned from center (.5 max since it's from 0-1)
-      */
-      boolean isClockwise;
-      float rawSpinKnobAmtTurnedFromCenter;
-      if (spinKnobPercent >= POTENTIOMETER_MIDDLE_PERCENT) {
-        isClockwise = true;
-        rawSpinKnobAmtTurnedFromCenter = spinKnobPercent - .5;
-        logger.log("Spin knob clockwise", rawSpinKnobAmtTurnedFromCenter);
-      } else {
-        isClockwise = false;
-        rawSpinKnobAmtTurnedFromCenter = .5 - spinKnobPercent;
-        logger.log("Spin knob counter clockwise", rawSpinKnobAmtTurnedFromCenter);
-      }
-
-      /* Percent the spin knob is away from center (0-1) */
-      float percentSpinKnobAmtTurnedFromCenter = rawSpinKnobAmtTurnedFromCenter / .5;
-      logger.log("Spin knob percentSpinKnobAmtTurnedFromCenter", percentSpinKnobAmtTurnedFromCenter);
-
-      /* How much of the increment time range to use (from min - max) is the "opposite" of the spin knob percent amt, since more is less time */
-      float percentOfIncrementTimeRange = 1 - percentSpinKnobAmtTurnedFromCenter;
-      logger.log("Spin knob percentOfIncrementTimeRange", percentOfIncrementTimeRange);
-
-      /* Use this percent to determine the actual increment time*/
-      long incrementDuration = FASTEST_SPIN_INCREMENT_DURATION_MS + (SPIN_INCREMENT_DURATION_RANGE_MS * percentOfIncrementTimeRange);
-      logger.log("Spin knob incrementDuration", incrementDuration);
-
-      ring.spin(incrementDuration, isClockwise);
-
-    }
-  }
+  void handleSendSpinState() {
+    float spinKnobPercent = spinKnob.getPercentVal();
+    logger.log("spin knob changed to: ", spinKnobPercent);
+
+    /* If the knob is centered, send the special flag to the ring to stop spinning, and return */
+    if (potentiometerPercentAtMiddle(spinKnobPercent)) {
+      logger.log("Spin knob at center");
+      ring.spin(-1, true);
+      return;
+    }
+
+    /*
+      Clockwise if spin pot is >= midpoint
+      Determine "raw" amount spin knob is turned from center (.5 max since it's from 0-1)
+    */
+    boolean isClockwise;
+    float rawSpinKnobAmtTurnedFromCenter;
+    if (spinKnobPercent >= POTENTIOMETER_MIDDLE_PERCENT) {
+      isClockwise = true;
+      rawSpinKnobAmtTurnedFromCenter = spinKnobPercent - .5;
+      logger.log("Spin knob clockwise", rawSpinKnobAmtTurnedFromCenter);
+    } else {
+      isClockwise = false;
+      rawSpinKnobAmtTurnedFromCenter = .5 - spinKnobPercent;
+      logger.log("Spin knob counter clockwise", rawSpinKnobAmtTurnedFromCenter);
+    }
+
+    /* Percent the spin knob is away from center (0-1) */
+    float percentSpinKnobAmtTurnedFromCenter = rawSpinKnobAmtTurnedFromCenter / .5;
+    logger.log("Spin knob percentSpinKnobAmtTurnedFromCenter", percentSpinKnobAmtTurnedFromCenter);
+
+    /* How much of the increment time range to use (from min - max) is the "opposite" of the spin knob percent amt, since more is less time */
+    float percentOfIncrementTimeRange = 1 - percentSpinKnobAmtTurnedFromCenter;
+    logger.log("Spin knob percentOfIncrementTimeRange", percentOfIncrementTimeRange);
+
+    /* Use this percent to determine the actual increment time*/
+    long incrementDuration = FASTEST_SPIN_INCREMENT_DURATION_MS + (SPIN_INCREMENT_DURATION_RANGE_MS * percentOfIncrementTimeRange);
+    logger.log("Spin knob incrementDuration", incrementDuration);
+
+    ring.spin(incrementDuration, isClockwise);
+   }

    void updateBlinkKnob() {
     blinkKnob.update();
@@ -255,6 +253,13 @@
      }
   }

+  void updateRainbowButton() {
+     rainbowButton.update();
+     if (rainbowButton.closedThisUpdate()) {
+       ring.rainbow();
+     }
+  }
+
   void updateRandomButton() {
      randomButton.update();
      if (randomButton.closedThisUpdate()) {
@@ -314,11 +319,10 @@
     // For the spin knob - if the spin knob isn't centered at start, actually send the state to the ring, and then stop spinning at init
     // This will allow the spin toggle button to function without having touched the spin knob first
     spinKnob.update();
-    if (!potentiometerPercentAtMiddle(spinKnobPercent)) {
+    if (!potentiometerPercentAtMiddle(spinKnob.getPercentVal())) {
       handleSendSpinState();
       ring.toggleSpin();
     }
-

     blinkKnob.update();
     brightnessKnob.update();


testing...

testing...

--- module/module.ino
+++ module/module.ino
@@ -199,7 +199,7 @@
 			Serial.print(periodY);
 			Serial.print(" Start Time: ");
 			Serial.print(startTime);
-			Serial.print(" Elapsed Time: ");
+			Serial.print(" Pulse Count: ");
 			Serial.println(periodCount);
 		}

@@ -234,7 +234,7 @@
 					startConnection();
 					updateThingSpeak(1, sendCount);
 					lastSend = millis();
-					//sendCount = 0;
+					delay(1000);
 					RFID.listen();
 					Serial.println("Done");
           			return sendCount;


cleaned up some code

cleaned up some code

--- v2/Motor_control/Distance_Test/Distance_Test.ino
+++ v2/Motor_control/Distance_Test/Distance_Test.ino
@@ -63,10 +63,16 @@
 int PWMB = 5; //Speed control
 int BIN1 = 11; //Direction
 int BIN2 = 12; //Direction
+
 char past; //what direction the robot was moving previously
 int count; //counter for how long before the rebot gives up searching in one direction
 int threshold; //threshold for line sensors
+int cur; // current time
+int initTime; // time after initialization
 short iter;
+int maxS;
+int minS;
+
 void setup() {
   Serial.begin(9600);
   pinMode(STBY, OUTPUT);
@@ -88,17 +94,14 @@
   leftDist = sensor2.getDist();
   perRightDist = sideright.getDist();
   perLeftDist = sideleft.getDist();
+  initTime = millis();
+  setSpeed(128, 20);
 }

 void loop() {
   // Get distance from sensor
-  iter++;
-  if (iter == 1) {
+  cur = millis();
     //print out values from sensors and motors to the console
-    rightDist = sensor.getDist();
-    leftDist = sensor2.getDist();
-    perRightDist = sideright.getDist();
-    perLeftDist = sideleft.getDist();
     Serial.print(past);
     Serial.print(", ");
     Serial.print(rightDist);
@@ -116,75 +119,81 @@
     Serial.print(analogRead(frontleft));
     Serial.print(", ");
     Serial.println(analogRead(frontright));
-  } else if (iter == 5) {
-    iter = 0;
-  }
-  if (analogRead(backleft) < threshold) { //first read from line sensors before doing anything else
-    //if line detected by back-left line sensor, turn left a bit
-    move(1, 40, 1); //motor 1, full speed, left
-    move(2, 120, 0); //motor 2, full speed, left
-    past = 'f'; //set default move to forward
-    delay(50); //wait 50ms for the IR sensors to take new reading
-  } else if (analogRead(backright) < threshold) {
-    //if line detected by back-right line sensor, turn right a bit
-    move(1, 120, 1); //motor 1, full speed, left
-    move(2, 40, 0); //motor 2, full speed, left
-    past = 'f';
-    delay(50);
-  } else if (analogRead(frontleft) < threshold) {
-    //if line dectected by front-left sensor, go back and to the left a bit
-    move(1, 40, 0); //motor 1, full speed, left
-    move(2, 120, 1); //motor 2, full speed, left
-    past = 'f';
-    delay(50);
-  } else if (analogRead(frontright) < threshold) {
-    //if line detected by front-right sensor, go back and to the right a bit
-    move(1, 120, 0); //motor 1, full speed, left
-    move(2, 40, 1); //motor 2, full speed, left
-    past = 'f';
-    delay(50);
-  } else if (iter == 1){
-    if (((past == 'f' || count >= 100) && (rightDist > 600 && leftDist > 600 && perRightDist > 600 && perLeftDist > 600))
-          || (rightDist <= 300 && leftDist <= 300)
-          || (abs(rightDist - leftDist) <= 150)) {
-      //if (robot moved forward in the past OR it's been searching for 100 iterations) AND (there isn't an object within 600mm of any IR sensor))
-      //OR there is an object within 300mm of both sensors
-      //OR the difference between the two distances measured by the IR sensors is within 150mm of each other
-      //move forward
-      move(1, 128, 1); //motor 1, full speed, left
-      move(2, 128, 0); //motor 2, full speed, left
-      past = 'f'; //set past movement to forward
-      count = 0; //reset abandon search count
-    } else if (past == 'l') {
-      //if robot has been moving left in the past, move left more
-      move(1, 20, 1); //motor 1, full speed, left
-      move(2, 128, 0); //motor 2, full speed, left
-      past = 'l'; //set past movement to left
-      count++; //increment abandon search count
-    } else if (past == 'r') {
-      //if robot has been moving right in the past, move right
-      move(1, 128, 1); //motor 1, full speed, left
-      move(2, 20, 0); //motor 2, full speed, left
-      past = 'r'; //set past movement to right
-      count++; //increment abandon search count
-    } else if (rightDist > 600) {
-      //if there is an object beyond 600mm of the right sensors (i.e. there is something closer in the left sensors), move left
-      move(1, 20, 1); //motor 1, full speed, left
-      move(2, 128, 0); //motor 2, full speed, left
-      past = 'l'; //set past movement to left
-      count = 0; //reset abandon search count because the robot has found an object
-    } else {
-      //else (i.e. there is an object closer in the right sensor), move right
-      move(1, 128, 1); //motor 1, full speed, left
-      move(2, 20, 0); //motor 2, full speed, left
-      past = 'r'; //set past movement to right
-      count = 0; //reset abandon search count
+  if ((cur - initTime) % 5 == 0) {
+    if (analogRead(backleft) < threshold) { //first read from line sensors before doing anything else
+      //if line detected by back-left line sensor, turn left a bit
+      move(1, 40, 1); //motor 1, full speed, left
+      move(2, 120, 0); //motor 2, full speed, left
+      past = 'f'; //set default move to forward
+      delay(50); //wait 50ms for the IR sensors to take new reading
+    } else if (analogRead(backright) < threshold) {
+      //if line detected by back-right line sensor, turn right a bit
+      move(1, 120, 1); //motor 1, full speed, left
+      move(2, 40, 0); //motor 2, full speed, left
+      past = 'f';
+      delay(50);
+    } else if (analogRead(frontleft) < threshold) {
+      //if line dectected by front-left sensor, go back and to the left a bit
+      move(1, 40, 0); //motor 1, full speed, left
+      move(2, 120, 1); //motor 2, full speed, left
+      past = 'f';
+      delay(50);
+    } else if (analogRead(frontright) < threshold) {
+      //if line detected by front-right sensor, go back and to the right a bit
+      move(1, 120, 0); //motor 1, full speed, left
+      move(2, 40, 1); //motor 2, full speed, left
+      past = 'f';
+      delay(50);
+    } else if ((cur - initTime) % 25 == 0){
+      rightDist = sensor.getDist();
+      leftDist = sensor2.getDist();
+      perRightDist = sideright.getDist();
+      perLeftDist = sideleft.getDist();
+      if (perLeftDist <= 300) {
+        //if there is an object within 300mm of the left peripheral sensor, move left
+        //turn left in place
+        leftInPlace();
+        past = 'l'; //set past movement to left
+        count = 0; //reset abandon search count because the robot has found an object
+      } else if (perRightDist <= 300) {
+        //if there is an object within 300mm of the right peripheral sensor, move right
+        //turn right in place
+        rightInPlace();
+        past = 'r'; //set past movement to left
+        count = 0; //reset abandon search count because the robot has found an object
+      } else if (((past == 'f' || count >= 100) && (rightDist > 600 && leftDist > 600 && perRightDist > 600 && perLeftDist > 600))
+            || (rightDist <= 300 && leftDist <= 300 && perRightDist > 600 && perLeftDist > 600)
+            || (abs(rightDist - leftDist) <= 150)) {
+        //if (robot moved forward in the past OR it's been searching for 100 iterations) AND (there isn't an object within 600mm of any IR sensor))
+        //OR there is an object within 300mm of both sensors
+        //OR the difference between the two distances measured by the IR sensors is within 150mm of each other
+        //move forward
+        forward();
+        past = 'f'; //set past movement to forward
+        count = 0; //reset abandon search count
+      } else if (past == 'l') {
+        //if robot has been moving left in the past, move left more
+        left();
+        past = 'l'; //set past movement to left
+        count++; //increment abandon search count
+      } else if (past == 'r') {
+        //if robot has been moving right in the past, move right
+        right();
+        past = 'r'; //set past movement to right
+        count++; //increment abandon search count
+      } else if (rightDist <= 600 || perRightDist <= 600) {
+        //if there is an object beyond 600mm of the left sensors (i.e. there is something closer in the right sensors), move right
+        right();
+        past = 'r'; //set past movement to right
+        count = 0; //reset abandon search count because the robot has found an object
+      } else if (leftDist <= 600 || perLeftDist <= 600) {
+        //if there is an object beyond 600mm of the right sensors (i.e. there is something closer in the left sensors), move left
+        left();
+        past = 'l'; //set past movement to left
+        count = 0; //reset abandon search count because the robot has found an object
+      }
     }
   }
-
-  // Print distance to Serial
-  // Wait some time
-  delay(5);
 }

 void move(int motor, int speed, int direction){
@@ -218,3 +227,34 @@
   //enable standby
   digitalWrite(STBY, LOW);
 }
+
+void forward() {
+  move(1, maxS, 1); //motor 1, full speed, left
+  move(2, maxS, 0); //motor 2, full speed, left
+}
+
+void left() {
+  move(1, minS, 1); //motor 1, full speed, left
+  move(2, maxS, 0); //motor 2, full speed, left
+}
+
+void right() {
+  move(1, maxS, 1); //motor 1, full speed, left
+  move(2, minS, 0); //motor 2, full speed, left
+}
+
+void leftInPlace() {
+  move(1, maxS, 0); //motor 1, full speed, left
+  move(2, maxS, 0); //motor 2, full speed, left
+}
+
+void rightInPlace() {
+  move(1, maxS, 1); //motor 1, full speed, left
+  move(2, maxS, 1); //motor 2, full speed, left
+}
+
+void setSpeed(int ma, int mi) {
+  maxS = ma;
+  minS = mi;
+}
+


dded some comments to the current firmware code

--- firmware/MultiRomVC4000/MultiRomVC4000.ino
+++ firmware/MultiRomVC4000/MultiRomVC4000.ino
@@ -1,9 +1,24 @@
+/**
+ * proof of concept for writing data to an SRAM with
+ * 3 74HC595 shift registers and reading data out
+ * via different Arduino Pins.
+**/
+
+
+//
+// pins used for the shiftout
+//
 #define CLOCK 4
 #define LATCH 3
 #define DATA  5

+//
+// pins used for write pulse of the SRAM
+// and the output enable of the data-bus shift register
+//
 #define WR    2
 #define OEDATA 14
+

 void setup() {
  pinMode(CLOCK,OUTPUT);
@@ -24,6 +39,7 @@
  Serial.begin(9600);
  delay(100);

+ // first write 256 bytes to the first 256 addresses

  Serial.println("writing data");
  for (int i=0;i<=255;i++) {
@@ -34,6 +50,7 @@
     write2RAM(i,(byte)i);
  }

+ // read back all 256 bytes
  Serial.println("reading data:");
  for (int i=0;i<=255;i++) {
     byte d = readRAM(i);
@@ -43,41 +60,61 @@
     if(i%15==0) Serial.println();

  }
-/**
- for(int i=0;i<256;i++) {
- write2RAM(0,i);
- Serial.println(readRAM(0),HEX);
- }
- **/
+
  Serial.println("done");
-
+
+ //just stop here
  while(1) {};
 }
-
-

 void loop() {

 }

+/**
+ * write one byte to a specific address of the SRAM
+ * @param address - unsigned integer with address 0x0000 - 0xffff
+ * @param data    - byte that should be written
+ **/
 void write2RAM(unsigned int address, byte data) {
+  //take care that the shift register output is enabled (low active)
   digitalWrite(OEDATA,LOW);
+
+  //set SRAM to READ mode
   digitalWrite(WR,HIGH);
+
+  //set address and data to the address- and data-bus of the SRAM
   shiftout(address,data);
+
+  //generate write pulse
   digitalWrite(WR,LOW);
-  //delay(5);
   digitalWrite(WR,HIGH);

 }

+/**
+ * read one byte from a specific address
+ * @param address - unsigned integer with address 0x0000 - 0xffff
+ * @return byte   - data read from SRAM
+ **/
 byte readRAM(unsigned int address) {
+  //take care that the shift register output is enabled (low active)
   digitalWrite(OEDATA,LOW);
+
+  //set SRAM to READ mode
   digitalWrite(WR,HIGH);
+
+  //set address-bus, data-bus is not needed but 8 bits need to b shifted out
   shiftout(address,0);
+
+  //disable output of shiftregister for data-bus, so the SARM can drive the databus
   digitalWrite(OEDATA,HIGH);
+
   delay(1);
- return ((digitalRead(13) << 7) +
+
+  //read all 8 data bits and return the complete byte
+  return ((digitalRead(13) << 7) +
       (digitalRead(12) << 6) +
       (digitalRead(11) << 5) +
       (digitalRead(10) << 4) +
@@ -87,15 +124,23 @@
        digitalRead(6));
 }

+/**
+ * wrapper function to shift out a 16 bit address and 8 bit data
+ * @param address - unsigned integer with address 0x0000 - 0xffff
+ * @param data    - one byte for data-bus
+ **/
 void shiftout(unsigned int address, byte data) {

+  //split address to high- and low-byte
   byte lowbyte = address & 0xff;
   byte highbyte = address >> 8;

+  //shift out all 3 bytes in the right order
   digitalWrite(LATCH,LOW);
   shiftOut(DATA,CLOCK,MSBFIRST,highbyte);
   shiftOut(DATA,CLOCK,MSBFIRST,lowbyte);
   shiftOut(DATA,CLOCK,MSBFIRST,data);
+  //latch out the data
   digitalWrite(LATCH,HIGH);
   delay(10);
   digitalWrite(LATCH,LOW);


update fix bug sprintf .3f to s

update fix bug sprintf .3f to s

--- mwsIWMIv3/mwsIWMIv3.ino
+++ mwsIWMIv3/mwsIWMIv3.ino
@@ -746,13 +746,13 @@
   smartdelay(800);
   dtostrf(rainin, 3, 2, rainbuf);
   //sprintf(sz, "HOTEL_TEST\nxxx mm/h");//[4]
-  sprintf(sz, "UO_LABUNORUWA\n%.3f mm/h",rainbuf);//[4]
-  //sprintf(sz, "UO_MAHAKANADARAWA\n%.3f mm/h",rainbuf);//[4]
+  sprintf(sz, "UO_LABUNORUWA\n%s mm/h",rainbuf);//[4]
+  //sprintf(sz, "UO_MAHAKANADARAWA\n%s mm/h",rainbuf);//[4]
   //sprintf(sz, "UO_ATHURUWELLA\n%s mm/h",rainbuf);//[4]
   //sprintf(sz, "NALLAMUDAWA_MAWATHAWEWA\n%s mm/h",rainbuf);//[4]
   //sprintf(sz, "THIRAPPANE_FARM\n%s mm/h",rainbuf);//[4]
-  //sprintf(sz, "UO_NUWARAWEWA_SALIYAPURA\n%.3f mm/h",rainbuf);//[4]
-  //sprintf(sz, "SRI_SADANANDA_PIRIVENA\n%.3f mm/h",rainbuf);//[4]
+  //sprintf(sz, "UO_NUWARAWEWA_SALIYAPURA\n%s mm/h",rainbuf);//[4]
+  //sprintf(sz, "SRI_SADANANDA_PIRIVENA\n%s mm/h",rainbuf);//[4]

   //Serial.println(sz);
   lcd.clear();


MultiCultiVitamine

MultiCultiVitamine

--- Buddy/Iris_buddy_workFile/Iris_buddy_workFile.ino
+++ Buddy/Iris_buddy_workFile/Iris_buddy_workFile.ino
@@ -2,15 +2,18 @@
 #define ledPin 6                 /*ledjes*/
 //#define _infrared (0)             //infrared cable 0

-Adafruit_NeoPixel strip = Adafruit_NeoPixel(27, ledPin, NEO_GRB + NEO_KHZ800); /* (total LED's,*/
-byte ledPositions[7][4] = {
-  { 0, 12, 13, 26},
-  { 1, 11, 14, 25},
-  { 2, 10, 15, 24},
-  { 3, 9, 16, 23},
-  { 4, 8, 17, 22},
-  { 5, 7, 18, 21},
-  { 27, 6, 19, 20} ,
+
+
+
+Adafruit_NeoPixel strip = Adafruit_NeoPixel(68, ledPin, NEO_GRB + NEO_KHZ800); /* (total LED's,*/
+byte ledPositions[7][10] = {
+  { 0, 12, 13, 26, 27, 40, 41, 54, 55, 67},
+  { 1, 11, 14, 25, 28, 39, 42, 53, 56, 66},
+  { 2, 10, 15, 24, 29, 38, 43, 52, 57, 65},
+  { 3,  9, 16, 23, 30, 37, 44, 51, 58, 64},
+  { 4,  8, 17, 22, 31, 36, 45, 50, 59, 63},
+  { 5,  7, 18, 21, 32, 35, 46, 49, 60, 62},
+  { 255, 6, 19, 20, 33, 34, 47, 48, 61, 255} ,
 };

@@ -26,6 +29,8 @@
 bool _changed;
 byte _fadeValue;

+int _infraredMin = 100;
+int _infraredMax = 450;

 void setup()
@@ -36,22 +41,36 @@
   // strip.show(); // Initialize all pixels to 'off'
 }

+void loop()
+{

-void loop()
-{
-  static int oldvalue = 0;
-  int _infrared = (oldvalue + (analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0)) / 8) / 2; //
-
-  int _infrared = 0;
-  for (int i = 0; i < 8; i++) _infrared += analogRead(0);
-  _infrared /= 8;
-
-  oldvalue = _infrared;
-  Serial.println(_infrared); //0-1023
   //Serial.println( analogRead _infrared);
   //analogRead (_infrared);//0-1023  Serial.println(analogRead(0));
-  _stand = Stand ( _infrared, _previousStand, _backward, _fadeValue, _changed);
-  _stagnated = Stagnation (_teller, _infrared, _previousStand);    /*om te zorgen dat hij herkent dat alles stilstaat*/
-  Airflow();
+  //_stand = Stand ( _infrared, _previousStand, _backward, _fadeValue, _changed);
+  //_stagnated = Stagnation (_teller, _infrared, _previousStand);    /*om te zorgen dat hij herkent dat alles stilstaat*/
+  //Airflow();
+  int infrared = 0;
+  for (int i = 0; i < 8; i++) infrared += analogRead(0);
+  infrared /= 8;
+  Serial.println(infrared);
+
+  valueToLedScale(map(infrared, _infraredMin, _infraredMax, 0, 1023));
 }
+
+
+
+void valueToLedScale(int value) {
+
+  int calc = map(value, 0, 1023, 0, 8 * 256 - 1);
+
+  for (int i = 0; i < 7; i++) strip.setPixelColor(ledPositions[i][0], strip.Color(0, 255, 0));
+  for (int i = 0; i < 7; i++) strip.setPixelColor(ledPositions[i][9], strip.Color(0, 0, 255));
+
+  for (int j = 0; j < 8; j++) {
+    for (int i = 0; i < 7; i++) strip.setPixelColor(ledPositions[i][1 + j], strip.Color(0, constrain(calc - 256 * j, 0, 255), 255 - constrain(calc - 256 * j, 0, 255)));
+  }
+
+  strip.show();
+}
+


Cleaned up original code & added changes related to
running/testing both Leonardo & Uno boards;
Simiplified Interrupt service routine.

Signed-off-by: jmhrvy <6a3cd8a1b2d47d05877db3d1fefa06cbe0a9a3f0@epbfi.com>

--- CNCSpindleSpeedControl/CNCSpindleSpeedControl.ino
+++ CNCSpindleSpeedControl/CNCSpindleSpeedControl.ino
@@ -2,18 +2,19 @@
 This Program when loaded on an Arduino/Leonardo is a Tach based speed controller.
 It was originally written to operate a 400W/48VDC CNC spindle motor through
 a simple electronic controller, readily found on E-Bay
-This program assumes that the +PWM lead of this controller is connected to
-pin D13 of the Leonardo, and the collector output of the speed sensor
+This program assumes that the +PWM lead of the controller is connected to
+pin D13 of the Leonardo (or Pin D11 on the UNO), and the collector output of the speed sensor
 [OPB704 is a direct pin-for-pin replacement for the once popular,
 but now discontinued, QRB1114; the Parallax Inc 550-27401 or FairChild qrd1114
 might also maybe adapted to work] is connected to pin D3.
 Note this collector is also tied +5Volts through a 20K pull-up resistor.
 It Furhter assumes that a Sansmart 16x2 LCD/KeyPad sheild has been installed.
 This display & keypad provides a simple user interface, where the Up/Down buttons
-will ramp the speed from 1400 to 10,000RPM in steps of 200RPM, and the Left/Right
-Button select the display mode.
-
-Note: The LCDKeypadR1 Library is a derivative of the files found here:
+can be used to ramp the Set Speed from 1400 to 10,000 RPM, in steps of 200 RPM,
+while the Left/Right Buttons will select the display mode.
+
+Note: The LCDKeypadR1 Library, contained in this file set,
+is a derivative of the files found here:

 http://sainsmart.com/zen/documents/20-011-901/keypad_lcd.zip

@@ -43,28 +44,35 @@
   //Code in here will only be compiled if an Arduino Leonardo is used.
   #define TimerReg   TCCR4B
   #define BoardType 0
+  #define InterruptId 0
 #endif
 #if defined(__AVR_ATmega16U4__)
   //Code in here will only be compiled if an Arduino Uno is used.
   #define TimerReg  TCCR2B
   #define BoardType 1
+  #define InterruptId 1
+#endif
+
+#if defined(__AVR_ATmega328P__)
+  //Code in here will only be compiled if an Arduino Uno is used.
+  #define TimerReg  TCCR2B
+  #define BoardType 1
+  #define Interrupt 1
+  #define InterruptId 1
 #endif

 LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //initialize Sansmart LCD Display
 LCDKeypad Keypad;
 int trgtRPM = 5000;
-//unsigned long now = millis();
-//unsigned long now = micros(); //will overflow ~ every 70 minutes
-
-//int timeChange = (now - lastTime);
-//if(timeChange>=SampleTimeP)
 unsigned long timeval = 0;
 unsigned long Start = 0;
 unsigned long Stop;
+unsigned long WaitInterval =0;
 unsigned long startPrgm = millis()/1000;
 unsigned long now;
-//unsigned long CalcStrt;
-//unsigned long CalcFnsh;
+int SampleCnt = 10; // Number Spindle Relolutions needed to make a new RPM calculation
+unsigned long period;
+unsigned long Maxperiod;

 int PWMpin; // Digital Pin that PWM signal appears on (Pin 13 = Leonardo; Pin 11 = Uno)
 int calcrpm = 0;
@@ -81,12 +89,9 @@
 double Kp = 0.02;//0.06;
 double Ki = 0.05;//0.05;
 double Kd = 0.0005;//0.0005;
-//double OS = 18;
-//double BrkPt = 22;
-//double X = 0.0;
 double PIDOut = 0.0;
-double Max = 254.0;
-double Min = 0.0;
+double Max = 254.0; //max allowed PWM value
+double Min = 1.0; //min allowed PWM value
 int SampleTime = 60;// measured in milliseconds [FWIW: 10,000 RPM measured over 10 revolutions = 60 ms]
 int MstrSampleTime = SampleTime;

@@ -95,26 +100,21 @@
 int MaxRunTime = 0;//60*60*10;// number of seconds the program is allowed to run be
 int SpndlPWM;
 int newdutycycle = 0;
-//int range = 800; //the number Substeps the Mark/Space ratio can be divided into
-//int Maxdutycycle =  630;
-//int Mindutycycle = 23;
 int dutycycle = 30; // percentage of time clock is high
-int StrtDC = 0; // the calculated Start dutycycle needed to hit the target rpm $
-//int TooHighCnt = 0;
-//int TooLowCnt = 0;
-//int MaxChngLmt = 0;
-int LastRPM = 0;
-int AltRPM = 0;
-int SpeedChange = 0;
-int SuspectRdCnt = 0;
-bool increaseSpeed = true;
+//int StrtDC = 0; // the calculated Start dutycycle needed to hit the target rpm $
+
+//int LastRPM = 0;
+//int AltRPM = 0;
+//int SpeedChange = 0;
+//int SuspectRdCnt = 0;
+//bool increaseSpeed = true;
 bool NewTrgtVal = true; //used to determine if display needs updating
 bool ExitNow = false;
 bool NuInput = true;
-char *intFlgStat;
-int ThrtlLpCnt= 0;
-int Startup = 0; // Locks out pid calcs on startup to give the default throttle setting a chance to take effect before correcting it
-int CalcIntrvl = 0;
+//char *intFlgStat;
+//int ThrtlLpCnt= 0;
+//int Startup = 0; // Locks out pid calcs on startup to give the default throttle setting a chance to take effect before correcting it
+//int CalcIntrvl = 0;
 int BackLight = 6;  // set Display BackGround color to 1=Red; 2=Green; 4=Blue
 int Mode = 7;

@@ -202,81 +202,45 @@
 // ================================================================

 // SpindleTachInterrupt:  called every time an event occurs
-
 void SpindleTachInterrupt(void)
 {
-   int ThisRPM = 0;
-   double pulseperiod = 0;
-//   if (Startup>0) // PID Lock out counter
-//   {
-//     LoopCounter = 1;
-//     Startup -= 1;
-//     return;
-//   }
-   if (eventCounter == 0)
+//   detachInterrupt(InterruptId);
+   unsigned long ThisIntTime = micros();
+   if (ThisIntTime < WaitInterval) return;
+   WaitInterval = ThisIntTime+3000; //move the next valid interrupt out by 3 milliSeconds (the squivalent of the spindle turning @ 20K RPM )
+   if (eventCounter == 1)
      {
-      Start = micros();//gettimeofday(&Start, NULL);
+      Start = ThisIntTime;
      }
-   if (eventCounter == 10)
+   if (eventCounter == SampleCnt+1)
      {
-      Stop = micros();//gettimeofday(&Stop, NULL);
+      period = ThisIntTime-Start;
      }
-   eventCounter +=1;//eventCounter++;
-///////////////////////////////////////////////////////////////////////////////
-    if (eventCounter < 11)// Let's see if there's enough samples to calc the current RPM
+   eventCounter +=1;
+   if (eventCounter >= SampleCnt+2)
+    {
+    if (period ==0) sprintf (buf,"Too Small");
+    else
      {
-      if (eventCounter < 3)
-       {
-        return; //No, there isn't enough samples
-       }
-      else
-       {
-        // yes there is, but does it seem like a reasonable value
-        Stop = micros(); //gettimeofday(&CalcStrt, NULL);
-        //pulseperiod = ((Stop.tv_sec-Start.tv_sec)*1000000ULL+(Stop.tv_usec-Start.tv_usec));
-        pulseperiod = (Stop-Start);
-        ThisRPM  = (60000000*(eventCounter-1))/pulseperiod;
-        if (ThisRPM <1200 || ThisRPM > 4200)
-         {
-          return; // its too slow, or its going fast enough that we need to go for a full ten
-                  // samples before deciding what to do with it
-         }
-       }
+      //int Freq  = (SampleCnt*1000000)/period; //Simple Frequency Counter (Hz) code
+      //sprintf (buf,"Hz: %d  ", Freq); //Simple Frequency Counter code
+     calcrpm =  (SampleCnt*60000000)/period;
+     if (calcrpm <=2800.0) SampleCnt = 2;
+     else SampleCnt = 10;
+
      }
-   if (eventCounter >= 11 || ThisRPM >0 )// There's enough samples to calc the current RPM
-     {
-      if (eventCounter >= 11)
-       {
-        pulseperiod = (Stop-Start);
-        calcrpm = 600000000/pulseperiod;// calculate rpm based on having measured the period of 10 revolutions
-       }
-       else
-       {
-        calcrpm = ThisRPM;
-       }
-
-      SpeedChange =  calcrpm -  LastRPM;
-      //LastRPM = curspeed;
-      LastRPM = calcrpm;
-      eventCounter = 0;
-      LoopCounter = 1;
-      //return; // temp stop for testing just the Tachometer portion of the code
-
-      if (pulseperiod<0 )//|| pulseperiod > 600000
-       {
-         sprintf (buf, "Pulse Period Err");
-         //Serial1.println(buf);
-        return; // disregard this result; it appears to be bogus
-       }
-
-      SampleTime = MstrSampleTime;
-      SetTunings(Kp, Ki, Kd);
-      SpndlPWM = CalcMtrPID(calcrpm);//Max+CalcMtrPID(calcrpm);
-      analogWrite(PWMpin, SpndlPWM);
-      dutycycle = (int)((SpndlPWM*100)/(Max));//(int)((SpndlPWM*100)/(2*Max));// convert PWM signal to a precentage
-     }
-
-   }
+     SampleTime = MstrSampleTime;
+     SetTunings(Kp, Ki, Kd);
+     SpndlPWM = CalcMtrPID(calcrpm);//Max+CalcMtrPID(calcrpm);
+     analogWrite(PWMpin, SpndlPWM);
+     dutycycle = (int)((SpndlPWM*100)/(Max));//(int)((SpndlPWM*100)/(2*Max));// convert PWM signal to a precentage
+    LoopCounter = 1;//reset loopcounter so main loop will know that Motor is still running
+    eventCounter = 0;
+    }
+//   delay(3); //wait at least the equivalent of 20K rpm before reacting to another spindle interrupt
+//    attachInterrupt(InterruptId, SpindleTachInterrupt, FALLING);
+}
+
 // ================================================================
 // ===               END INTERRUPT DETECTION ROUTINE            ===
 // ================================================================
@@ -289,26 +253,30 @@

 void setup()
 {
-  //Serial1.begin(9600); // enable when bluetooth diagnostic is needed
+  byte Divisor;
+  //Serial1.begin(9600); // enable when [Leonardo] bluetooth diagnostic is needed
+  //Serial.begin(9600);  // enable when/if diagnostic is needed
    // set up the lcd's number of columns and rows:
   lcd.begin(16, 2);
-  byte Divisor;
-  //setup PWM frequency to ~60Hz for OutPut pins 13 & 11
-  //TCCR4B = TCCR4B & 0b11111000 | 0x06; // Leonardo; Set Digital pin 13 [Spindle] PWM period @ ~2ms
-  //TCCR2B = TCCR2B & 0b11111000 | 0x08; //UNO
-  if (BoardType == 0) // Leonardo
+  //calcrpm =  (SampleCnt*1000000*60)/period;//Formula used in interrupt routine to estimate current Spindle RMPM
+  calcrpm = 500; //minimum expected RPM
+  Maxperiod =(SampleCnt*1000000*60)/calcrpm;
+
+  pinMode(3, INPUT_PULLUP);//Set Interrupt input pin to have an active pullupresistor
+ if (BoardType == 0) // Leonardo
   {
    PWMpin = 13;
-   Divisor = 0x06;
-   attachInterrupt(0, SpindleTachInterrupt, FALLING); //Leonardo-digital pin 3; Uno Digital pin 2
+   Divisor = 0x06;//0x06 original divisor used on Leonardo; new faster pwm divisor 0x04
+   //Serial.println("Leonardo");
   }
   else //Uno
   {
    PWMpin = 11;
-   Divisor = 0x08;
-   attachInterrupt(1, SpindleTachInterrupt, FALLING); //UNO digital pin 3;
+   Divisor = 0x03;
+   //Serial.println("Uno");
   }
-
+  attachInterrupt(InterruptId, SpindleTachInterrupt, FALLING); //UNO digital pin 3;
+
   TimerReg = TimerReg & 0b11111000 | Divisor;
   pinMode(PWMpin, OUTPUT);
 // install  user defined special characters
@@ -328,6 +296,8 @@
   //startPrgm = 1000*millis();
   long MaxRunTime = 60*60*10;// number of seconds the program is allowed to run be
 }
+
+
 // ================================================================
 // ===                    MAIN PROGRAM LOOP                     ===
 // ================================================================
@@ -335,10 +305,8 @@
 {
   int UsrInput = 0;
   int stopCnt = 0;
-  //  lcdPosition (lcdHandle, 0, 0) ; lcdPuts (lcdHandle, "Speed Cntl Ready") ;
   lcd.setCursor(0,1);
   lcd.print("Speed Cntl Ready");
-  //  lcdPosition (lcdHandle, 0, 1) ; lcdPrintf (lcdHandle, " Set RPM: %d",trgtRPM) ;
   lcd.setCursor(0,0);
   sprintf (buf,"Set RPM: %d", trgtRPM);
   lcd.print(buf);
@@ -346,33 +314,20 @@
   //then LCD setup seemed to go OK, & you're ready to start the speed control stuff

   // Calc initial dutycycle based on trgtRPM
-  //dutycycle = (int) 75*(trgtRPM/9800.0)*(trgtRPM/9800.0) ;
-  //int valA = (trgtRPM - 1500)/140;
-   //StrtDC =((valA*valA)/14)+22;
-   //StrtDC = 30;
    SpndlPWM = (int) 95.0*(trgtRPM/9800.0)*(trgtRPM/9800.0) ; //190.5*(trgtRPM/9800.0)*(trgtRPM/9800.0)

-  //pinMode (GPIOpin, PWM_OUTPUT) ; //configure pin 1 as a PWM output
-  //pwmSetMode (PWM_MODE_MS); //configure PWM output to operate in Mark / Space mode
-  //pwmSetMode (PWM_MODE_BAL); //configure PWM output to operate in Mark / Balanced Mode
-  //pwmSetRange (range) ;// This sets the range register in the PWM generator. The default is 1024.
- // pwmSetClock (5) ;// This sets the divisor for the PWM clock.
-
-// pinMode (GPIOpinSlow, OUTPUT) ; //configure pin 1 as a simple output pin
-// digitalWrite (GPIOpinSlow, LOW); //set/force pin 4 output High[Under Speed LED off]
-// pinMode (GPIOpinOK, OUTPUT) ; //configure pin 5 as a simple output pin
-// digitalWrite (GPIOpinOK, LOW); //set/force pin 5 output  High[Speed Ok LED off]
-// pinMode (GPIOpinFast, OUTPUT) ; //configure pin 6 as a simple output pin
-// digitalWrite (GPIOpinFast, LOW); //set/force pin 6 output  High[Over Speed LED off]
-
-
-
-  // display counter value every 1/4 second.
+   // display counter value every 1/4 second.
   //sprintf (buf, "Time %d Max %d\n", TotalRunTime, MaxRunTime);
   //Serial1.println(buf);
   while ( TotalRunTime <= MaxRunTime && !ExitNow )
   {

+    if(micros()-Start>=Maxperiod ){// if true, it looks like the motor isn't turning
+      eventCounter = 0;
+      LoopCounter = 0;
+      Start = micros();
+      NewTrgtVal = true;
+    }
     while (eventCounter == 0 && LoopCounter == 0 &&  TotalRunTime <= MaxRunTime && !ExitNow)
      {
       //Motor is not running, So initialize PID for next startup
@@ -382,13 +337,13 @@
       ITerm = 0.0; //kill any residual Integral component that might be left over from a previous run
       lastTime = millis();// reset/establish time mark for initial PID calculation
       analogWrite(PWMpin, SpndlPWM); //start the PWM output
+      //sprintf (buf, "PWMpin:%02i PWM:%02i", PWMpin, SpndlPWM);
+      //Serial.println(buf);
       //Startup, in this version of the code is not used
       //Startup = 60; // Locks out pid calcs on startup to give the default throttle setting a chance to take effect before correcting it
       delay(100);
       if (NewTrgtVal)
        {
-//         lcdPosition (lcdHandle, 0, 0) ;  lcdPrintf (lcdHandle, "Trgt RPM: %d   ", trgtRPM) ;
-//         lcdPosition (lcdHandle, 0, 1) ; lcdPuts (lcdHandle, "Speed Cntl Ready") ;
          lcd.setCursor(0,0); //lcd.setCursor(pos,line)
          sprintf (buf, "%s %04i ", "Trgt RPM:", trgtRPM);
          lcd.print(buf);
@@ -398,33 +353,13 @@
        }
       UsrInput =  ScanButtons();
       UpDateSettings(UsrInput, Mode);
-      if (stopCnt == 0)
-       {
-//         Serial1.print( "Eventcount:%d ; Duty Cycle %d \n", eventCounter, dutycycle );
-//         digitalWrite (GPIOpinSlow, HIGH); //set/force pin 4 output High[Under Speed LED On]
-//         digitalWrite (GPIOpinOK, HIGH); //set/force pin 5 output  High[Speed Ok LED On]
-//         digitalWrite (GPIOpinFast, HIGH); //set/force pin 6 output  High[Over Speed LED On]
-       }
-      if (stopCnt == 5)
-       {
-//      delay( 500 ); // wait 1/2 second(s)
-//         digitalWrite (GPIOpinSlow, LOW); //set/force pin 4 output Low[Under Speed LED off]
-//         digitalWrite (GPIOpinOK, LOW); //set/force pin 5 output  Low[Speed Ok LED off]
-//         digitalWrite (GPIOpinFast, LOW); //set/force pin 6 output  Low[Over Speed LED off]
-       }
       long TotalRunTime = calcruntime();
-      SuspectRdCnt = 3;
+      //SuspectRdCnt = 3;
       stopCnt = stopCnt+1;
-      if (stopCnt == 10)
-       {
-        stopCnt = 0;
-       }
-     } // end 2nd inner While looop
-//   Serial1.print( "rpm: %d; trgtRPM: %d; Duty Cycle: %d; SpdChng: %d %s; EvntCnt: %d \n", calcrpm, trgtRPM,$
-   //lcdClear (lcdHandle) ;
+     } // end of 2nd inner While looop
+  //   Serial1.print( "rpm: %d; trgtRPM: %d; Duty Cycle: %d; SpdChng: %d %s; EvntCnt: %d \n", calcrpm, trgtRPM,$
    if (NewTrgtVal)
     {
-      //lcdPosition (lcdHandle, 0, 0) ; lcdPrintf (lcdHandle, "Trgt RPM: %d   ", trgtRPM) ;
       lcd.setCursor(0,0); //lcd.setCursor(pos,line)
       sprintf (buf, "%s %04i ", "Trgt RPM:", trgtRPM);
       lcd.print(buf);
@@ -467,7 +402,6 @@
       }
      else
       {
-//      strncpy(SgndErStr, SpdErStr, 6);
        strncpy(SgndErStr, " ", 8);
        strcat(SgndErStr, SpdErStr);
       }
@@ -557,9 +491,10 @@
       //Serial1.print("Looks as if Motor has Stopped\n");
      }
    long TotalRunTime = calcruntime();
-  }
+  } //end of 1st while loop
  //kill the PWM signal
- digitalWrite (PWMpin, LOW);
+  detachInterrupt(InterruptId);
+  digitalWrite (PWMpin, LOW);
 // pinMode (GPIOpin, OUTPUT) ; //configure pin 1 as a simple output pin
 // digitalWrite (GPIOpin, LOW); //set/force pin 1 output to ground [low]
 // digitalWrite (GPIOpinSlow, LOW); //set/force pin 4 output High[Under Speed LED off]
@@ -576,6 +511,7 @@
  lcd.setCursor(0,1); //lcd.setCursor(pos,line)
  sprintf (buf, "CYCLE PWR 2 STRT");
  lcd.print(buf);
+ delay(10000);
  return;
 }
 // ================================================================


Fix timeout bug due to improper bracketing

--- VehicleController/VehicleController.ino
+++ VehicleController/VehicleController.ino
@@ -166,13 +166,15 @@
             Serial.println("Throttle timeout!");
         }

-        if (!brakeTimer)
+        if (!brakeTimer) {
             state = VC_ABORT_STATE;
             myDAC.analogWrite(0, 0);
             Serial.println("Brake timeout!");
-    }
-}
-
+        }
+    }
+}
+
+// Called at the beginning of every loop
 void checkIncomingBytes(){
     if (Serial.available()){
         char in = Serial.read();


Added LED_TYPE declaration

Added LED_TYPE declaration

Added option near top of script to change the type of LEDs used.

--- TWANG.ino
+++ TWANG.ino
@@ -30,6 +30,7 @@
 #define MIN_REDRAW_INTERVAL  16    // Min redraw interval (ms) 33 = 30fps / 16 = 63fps
 #define USE_GRAVITY          1     // 0/1 use gravity (LED strip going up wall)
 #define BEND_POINT           550   // 0/1000 point at which the LED strip goes up the wall
+#define LED_TYPE             APA102//type of LED strip to use(APA102 - DotStar, WS2811 - NeoPixel)

 // GAME
 long previousMillis = 0;           // Time of the last redraw
@@ -102,7 +103,7 @@
     accelgyro.initialize();

     // Fast LED
-    FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, LED_COLOR_ORDER>(leds, NUM_LEDS);
+    FastLED.addLeds<LED_TYPE, DATA_PIN, CLOCK_PIN, LED_COLOR_ORDER>(leds, NUM_LEDS);
     FastLED.setBrightness(BRIGHTNESS);
     FastLED.setDither(1);


more fixes for Teensy; switched to Serial2; working

--- IcomTest/IcomTest.ino
+++ IcomTest/IcomTest.ino
@@ -38,8 +38,8 @@

 SoftwareSerial rxSerial(10, 11); // RX, TX for the RX
 #else
- // use RX1,TX1 on the Teensy 3.1/3.2 board
- #define rxSerial  Serial1;
+ // use RX2,TX2 on the Teensy 3.1/3.2 board, Serial1 is identical to Serial and wired to USB
+ #define rxSerial  Serial2
 #endif // (__AVR__)

 IcomCAT Icom706(rxSerial,IC706MK2G_ADDR);
@@ -181,9 +181,11 @@

     default: ;
   }
-
+
+#if defined (__AVR__)
   rxSerial.listen();
-
+#endif // (__AVR__)
+
   // check if 'Serial1' has data to receive
   if (rxSerial.available()) {


fix code

fix code


Beautify SimpleWebServerWiFi example webpage.

--- hardware/cc3200/libraries/WiFi/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino
+++ hardware/cc3200/libraries/WiFi/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino
@@ -76,8 +76,10 @@
             client.println();

             // the content of the HTTP response follows the header:
-            client.print("Click here turn the RED LED on
");
-            client.print("Click here turn the RED LED off
");
+            client.println("<title>Energia CC3200 WiFi Web Server</title>");
+            client.println("
Welcome to the CC3200 WiFi Web Server
");
+            client.print("RED LED <button onclick=\"location.href='/H'\">HIGH</button>");
+            client.println(" <button onclick=\"location.href='/L'\">LOW</button>
");

             // The HTTP response ends with another blank line:
             client.println();


Score to 5000 removed velocity

Score to 5000 removed velocity


Ajout d'un stop pour eteindre le ruban

Ajout d'un stop pour eteindre le ruban

--- stripNeopixel/stripNeopixel.ino
+++ stripNeopixel/stripNeopixel.ino
@@ -166,6 +166,7 @@
 int currentSpeed = 20;
 bool isAnimation = true;
 int counter = 0; // Compteur pour la mise a jour du random
+bool pause = false;

 uint8_t buffer[BUFFER_SIZE+1];
 int bufindex = 0;
@@ -437,10 +438,18 @@
   return httpServer.available().available();
 }

+void togglePause(void) {
+  pause = !pause;
+
+  if (pause) {
+    for(uint8_t i=0; i < PIXEL_COUNT; i++) {
+      strip.setPixelColor(i, strip.Color(0, 0, 0));
+      strip.show();
+    }
+  }
+}
+
 void loop() {
-  #ifdef DEBUG
-    Serial.println(F("loop"));
-  #endif
   //wdt_enable(WDTO_2S);
   // Try to get a client which is connected.
   Adafruit_CC3000_ClientRef client = httpServer.available();
@@ -525,6 +534,18 @@
             PRINT_DEBUG("currentSpeed: ", value);
           #endif
         }
+        else if (strcmp(type, "pause") == 0) {
+          togglePause();
+          #ifdef DEBUG
+            Serial.println(F("Toggle pause"));
+          #endif
+        }
+        if (pause && strcmp(type, "pause") != 0 && strcmp(type, "status") != 0) {
+          togglePause();
+          #ifdef DEBUG
+            Serial.println(F("Toggle pause auto"));
+          #endif
+        }

         if (callback != NULL) {
           if (!isAnimation) {
@@ -587,44 +608,46 @@
     Serial.println(F("Client disconnected"));
     client.close();
   }
-  // Update pixels based on current state.
-  if (!isAnimation) {
-    if (currentPattern == BARS) {
-      bars(schemes[currentScheme], barWidthValues[currentWidth], currentSpeed);
-    } else if (currentPattern == GRADIENT) {
-      gradient(schemes[currentScheme], gradientWidthValues[currentWidth], currentSpeed);
-    }
-  } else {
-    if (currentAnimation == RANDOM) {
-      // Some example procedures showing how to display to the pixels:
-      colorWipe(strip.Color(255, 0, 0), 50); // Red
-      colorWipe(strip.Color(0, 255, 0), 50); // Green
-      colorWipe(strip.Color(0, 0, 255), 50); // Blue
-      // Send a theater pixel chase in...
-      theaterChase(strip.Color(127, 127, 127), 50); // White
-      theaterChase(strip.Color(127, 0, 0), 50); // Red
-      theaterChase(strip.Color(0, 0, 127), 50); // Blue
-
-      rainbows(20);
-      rainbowCycle(20);
-      theaterChaseRainbow(50);
+  if (!pause) {
+    // Update pixels based on current state.
+    if (!isAnimation) {
+      if (currentPattern == BARS) {
+        bars(schemes[currentScheme], barWidthValues[currentWidth], currentSpeed);
+      } else if (currentPattern == GRADIENT) {
+        gradient(schemes[currentScheme], gradientWidthValues[currentWidth], currentSpeed);
+      }
     } else {
-      switch(currentAnimation) {
-        case RAINBOWS:
-          rainbows(currentSpeed);
-          break;
-        case RAINBOW_CYCLE:
-          rainbowCycle(currentSpeed);
-          break;
-        case COLOR_WIPE:
-          colorWipe(Wheel(randomByte()), currentSpeed);
-          break;
-        case THEATER_CHASE:
-          theaterChase(Wheel(randomByte()), currentSpeed); // Blue
-          break;
-        case THEATER_CHASE_RAINBOW:
-          theaterChaseRainbow(currentSpeed);
-          break;
+      if (currentAnimation == RANDOM) {
+        // Some example procedures showing how to display to the pixels:
+        colorWipe(strip.Color(255, 0, 0), 50); // Red
+        colorWipe(strip.Color(0, 255, 0), 50); // Green
+        colorWipe(strip.Color(0, 0, 255), 50); // Blue
+        // Send a theater pixel chase in...
+        theaterChase(strip.Color(127, 127, 127), 50); // White
+        theaterChase(strip.Color(127, 0, 0), 50); // Red
+        theaterChase(strip.Color(0, 0, 127), 50); // Blue
+
+        rainbows(20);
+        rainbowCycle(20);
+        theaterChaseRainbow(50);
+      } else {
+        switch(currentAnimation) {
+          case RAINBOWS:
+            rainbows(currentSpeed);
+            break;
+          case RAINBOW_CYCLE:
+            rainbowCycle(currentSpeed);
+            break;
+          case COLOR_WIPE:
+            colorWipe(Wheel(randomByte()), currentSpeed);
+            break;
+          case THEATER_CHASE:
+            theaterChase(Wheel(randomByte()), currentSpeed); // Blue
+            break;
+          case THEATER_CHASE_RAINBOW:
+            theaterChaseRainbow(currentSpeed);
+            break;
+        }
       }
     }
   }


Tweaks

Tweaks

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -202,19 +202,19 @@
   laser.fire(0);
   panTilt.detach();
   unsigned long startTime = millis();
-  for(unsigned int i = 0; i < delayVal; i++){}
-  while(millis() - startTime < 60000){
-    heartBeat();
-    delay(10000);
-  }
-  startTime = millis();
-}
+  for(unsigned int i = 0; i < delayVal; i++){
+    while(millis() - startTime < 60000){
+      heartBeat();
+      delay(10000);
+    }
+    startTime = millis();
+  }
   panTilt.begin();
   laser.fire(1);

 }

-void heartbeat(){
+void heartBeat(){
   uint8_t ledPin = 13;
   pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, HIGH);