Revert "Another attempt at progmem"

Revert "Another attempt at progmem"

This reverts commit 48001d9101a8e1818950a74bfce222043c852254.

--- projects/SumpPumpController/Arduino/Arduino.ino
+++ projects/SumpPumpController/Arduino/Arduino.ino
@@ -35,68 +35,6 @@
 // Buffer for char conversions
 char buf [100];

-// PROGMEM string declarations
-const char str_alertPresent[] PROGMEM = "alertPresent";
-const char str_alarmPresent[] PROGMEM = "alarmPresent";
-const char str_YES_Ack_ed[] PROGMEM = "YES, Ack'ed";
-const char str_YES[] PROGMEM = "YES";
-const char str_NO[] PROGMEM = "NO";
-const char str_alertReason[] PROGMEM = "alertReason";
-const char str_getDistance[] PROGMEM = "getDistance";
-const char str_getPressure[] PROGMEM = "getPressure";
-const char str_getBattVoltage[] PROGMEM = "getBattVoltage";
-const char str_dmV[] PROGMEM = "%dmV";
-const char str_getAcPumpOnTime[] PROGMEM = "getAcPumpOnTime";
-const char str_d[] PROGMEM = "%d";
-const char str_getLastSelfTest[] PROGMEM = "getLastSelfTest";
-const char str_forceAlert[] PROGMEM = "forceAlert";
-const char str_Force_command[] PROGMEM = "Force command";
-const char str_OK[] PROGMEM = "OK";
-const char str_resetAlert[] PROGMEM = "resetAlert";
-const char str_startSelfTest[] PROGMEM = "startSelfTest";
-const char str_set[] PROGMEM = "set";
-const char str_debug[] PROGMEM = "debug";
-const char str_Unrecognized_command[] PROGMEM = "Unrecognized command";
-const char str_setAlertBatteryVoltage[] PROGMEM = "setAlertBatteryVoltage:";
-const char str_ERROR[] PROGMEM = "ERROR";
-const char str_setAlertWaterLevel[] PROGMEM = "setAlertWaterLevel:";
-const char str_setBaudRate[] PROGMEM = "setBaudRate:";
-const char str_setAcPumpOnThreshold[] PROGMEM = "setAcPumpOnThreshold:";
-const char str_setAlertPressureLevel[] PROGMEM = "setAlertPressureLevel:";
-const char str_setAcPumpOnTimeWarning[] PROGMEM = "setAcPumpOnTimeWarning:";
-const char str_setSelftestTimeBetween[] PROGMEM = "setSelftestTimeBetween:";
-const char str_setSelfTestTimeLimit[] PROGMEM = "setSelfTestTimeLimit:";
-const char str_setSelfTestMinDepth[] PROGMEM = "setSelfTestMinDepth:";
-const char str_setSelfTestDepthDiff[] PROGMEM = "setSelfTestDepthDiff:";
-const char str_setDepthMeasureTime[] PROGMEM = "setDepthMeasureTime:";
-const char str_setBuzzerEnabled[] PROGMEM = "setBuzzerEnabled:";
-const char str_setZeroPressure[] PROGMEM = "setZeroPressure:";
-const char str_setPointsPerCm[] PROGMEM = "setPointsPerCm:";
-const char str_setDcPumpOnTimeWarning[] PROGMEM = "setDcPumpOnTimeWarning:";
-const char str_ERROR_1_3600_expected[] PROGMEM = "ERROR: 1-3600 expected.";
-const char str_time_lu[] PROGMEM = "time=%lu";
-const char str_rangeLH_0_d_d[] PROGMEM = "rangeLH[0]=%d,%d";
-const char str_rangeLH_1_d_d[] PROGMEM = "&rangeLH[1]=%d,%d";
-const char str_DcHeight_d_d[] PROGMEM = "&DcHeight=%d,%d";
-const char str_pressure_d[] PROGMEM = "&pressure=%d";
-const char str_AcPumpCycles_d[] PROGMEM = "&AcPumpCycles=%d";
-const char str_lastAlertTime_lu[] PROGMEM = "&lastAlertTime=%lu";
-const char str_rawDepthPressure_d[] PROGMEM = "&rawDepthPressure=%d";
-const char str_timeSince_lu[] PROGMEM = "timeSince=%lu&";
-const char str_cyclesSince_d[] PROGMEM = "cyclesSince=%d&";
-const char str_voltage_d[] PROGMEM = "voltage=%d&";
-const char str_length_d[] PROGMEM = "length=%d&";
-const char str_pumpedHeight_d[] PROGMEM = "pumpedHeight=%d&";
-const char str_result_d[] PROGMEM = "result=%d";
-const char str_Weak_battery_dmV[] PROGMEM = "Weak battery: %dmV";
-const char str_DC_Pump_failure_dCM_pumped_in_d_sec[] PROGMEM = "DC Pump failure: %dCM pumped in %d sec.";
-const char str_DC_Pump_ON[] PROGMEM = "DC Pump ON";
-const char str_DC_pump_ON_too_long[] PROGMEM = "DC pump ON too long";
-const char str_Battery_voltage[] PROGMEM = "Battery voltage";
-const char str_Water_level_d[] PROGMEM = "Water level: %d";
-const char str_High_pressure[] PROGMEM = "High pressure";
-const char str_AC_pump_ON_for_too_long[] PROGMEM = "AC pump ON for too long";
-
 void setup()
 {
   readConfig();
@@ -144,49 +82,49 @@
 {
   // Process RS-485 commands
   if (net.messageReceived()) {
-    if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_alertPresent)))) || net.assertCommand(PSTR((char*)pgm_read_word(&(str_alarmPresent))))) {
+    if (net.assertCommand(PSTR("alertPresent")) || net.assertCommand(PSTR("alarmPresent"))) {
       if (alert.present) {
         if (alert.acknowledged) {
-          net.sendResponse(PSTR((char*)pgm_read_word(&(str_YES_Ack_ed))));
+          net.sendResponse(PSTR("YES, Ack'ed"));
         } else {
-          net.sendResponse(PSTR((char*)pgm_read_word(&(str_YES))));
+          net.sendResponse(PSTR("YES"));
         }
       } else {
-        net.sendResponse(PSTR((char*)pgm_read_word(&(str_NO))));
+        net.sendResponse(PSTR("NO"));
       }
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_alertReason))))) {
+    } else if (net.assertCommand(PSTR("alertReason"))) {
       net.sendResponse(alert.condition);
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_getDistance))))) {
+    } else if (net.assertCommand(PSTR("getDistance"))) {
       net.sendResponse(itoa(readDistance(), buf, 10));
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_getPressure))))) {
+    } else if (net.assertCommand(PSTR("getPressure"))) {
       net.sendResponse(itoa(readPressure(), buf, 10));
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_getBattVoltage))))) {
-      sprintf(buf, (char*)pgm_read_word(&(str_dmV)), readBatteryVoltage());
+    } else if (net.assertCommand(PSTR("getBattVoltage"))) {
+      sprintf(buf, "%dmV", readBatteryVoltage());
       net.sendResponse(buf);
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_getAcPumpOnTime))))) {
+    } else if (net.assertCommand(PSTR("getAcPumpOnTime"))) {
       if (acpump.currentlyOn) {
-        sprintf(buf, (char*)pgm_read_word(&(str_d)), acpump.onSeconds + (now() - acpump.switchOnTime));
+        sprintf(buf, "%d", acpump.onSeconds + (now() - acpump.switchOnTime));
       } else {
-        sprintf(buf, (char*)pgm_read_word(&(str_d)), acpump.onSeconds);
+        sprintf(buf, "%d", acpump.onSeconds);
       }
       net.sendResponse(buf);
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_getLastSelfTest))))) {
+    } else if (net.assertCommand(PSTR("getLastSelfTest"))) {
       sendSelfTestResponse();
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_forceAlert))))) {
-      raiseAlert(ExternallyForced, PSTR((char*)pgm_read_word(&(str_Force_command))));
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_resetAlert))))) {
+    } else if (net.assertCommand(PSTR("forceAlert"))) {
+      raiseAlert(ExternallyForced, PSTR("Force command"));
+      net.sendResponse(PSTR("OK"));
+    } else if (net.assertCommand(PSTR("resetAlert"))) {
       resetAlert();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_startSelfTest))))) {
+      net.sendResponse(PSTR("OK"));
+    } else if (net.assertCommand(PSTR("startSelfTest"))) {
       dcSelfTestStart();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_set))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else if (net.assertCommandStarts(PSTR("set"), buf)) {
       processSetCommands();
-    } else if (net.assertCommand(PSTR((char*)pgm_read_word(&(str_debug))))) {
+    } else if (net.assertCommand(PSTR("debug"))) {
       sendDebugResponse();
     } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_Unrecognized_command))));
+      net.sendResponse(PSTR("Unrecognized command"));
     }
   }

@@ -231,25 +169,25 @@
 // Write to the configuration when we receive new parameters
 void processSetCommands()
 {
-  if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setAlertBatteryVoltage))), buf)) {
+  if (net.assertCommandStarts(PSTR("setAlertBatteryVoltage:"), buf)) {
     unsigned int tmp = strtol(buf, NULL, 10);
     if (tmp > 9000 && tmp < 15000) {
       conf.alertBatteryVoltage = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setAlertWaterLevel))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setAlertWaterLevel:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp > -100 && tmp < 100) {
       conf.alertWaterLevel = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setBaudRate))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setBaudRate:"), buf)) {
     long tmp = strtol(buf, NULL, 10);
     // Supported: 9600, 14400, 19200, 28800, 38400, 57600, or 115200
     if (tmp == 9600 ||
@@ -262,143 +200,143 @@
     ) {
       conf.baudRate = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
+      net.sendResponse(PSTR("OK"));
       Serial.end();
       Serial.begin(tmp);
     } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setAcPumpOnThreshold))), buf)) {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setAcPumpOnThreshold:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp > 0 && tmp < 1025) {
       conf.acPumpOnThreshold = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setAlertPressureLevel))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setAlertPressureLevel:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp > 0 && tmp < 1025) {
       conf.alertPressureLevel = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setAcPumpOnTimeWarning))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setAcPumpOnTimeWarning:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp > 0 && tmp < 30000) {
       conf.acPumpOnTimeWarning = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setSelftestTimeBetween))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setSelftestTimeBetween:"), buf)) {
     long tmp = strtol(buf, NULL, 10);
     if (tmp > 0 && tmp < 1000000L) {
       conf.selftestTimeBetween = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setSelfTestTimeLimit))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setSelfTestTimeLimit:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     // More than 6 seconds, as we're checking that DC pump is on at 6 second mark.
     if (tmp > 6 && tmp < 200) {
       conf.selfTestTimeLimit = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setSelfTestMinDepth))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setSelfTestMinDepth:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp > -100 && tmp < 100) {
       conf.selfTestMinDepth = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setSelfTestDepthDiff))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setSelfTestDepthDiff:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp > 0 && tmp < 100) {
       conf.selfTestDepthDiff = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setDepthMeasureTime))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setDepthMeasureTime:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp >= 0 && tmp < 120) {
       conf.depthMeasureTime = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setBuzzerEnabled))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setBuzzerEnabled:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp == 1 || tmp == 0) {
       conf.buzzerEnabled = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setZeroPressure))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setZeroPressure:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp >= 0 && tmp < 1023) {
       conf.zeroPressure = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setPointsPerCm))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setPointsPerCm:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp >= -1024 && tmp < 1024) {
       conf.pointsPerCm = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR))));
-    }
-  } else if (net.assertCommandStarts(PSTR((char*)pgm_read_word(&(str_setDcPumpOnTimeWarning))), buf)) {
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR"));
+    }
+  } else if (net.assertCommandStarts(PSTR("setDcPumpOnTimeWarning:"), buf)) {
     int tmp = strtol(buf, NULL, 10);
     if (tmp >= 1 && tmp < 3600) {
       conf.dcPumpOnTimeWarning = tmp;
       saveConfig();
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_OK))));
-    } else {
-      net.sendResponse(PSTR((char*)pgm_read_word(&(str_ERROR_1_3600_expected))));
+      net.sendResponse(PSTR("OK"));
+    } else {
+      net.sendResponse(PSTR("ERROR: 1-3600 expected."));
     }
   } else {
-    net.sendResponse(PSTR((char*)pgm_read_word(&(str_Unrecognized_command))));
+    net.sendResponse(PSTR("Unrecognized command"));
   }
 }

 void sendDebugResponse()
 {
-  sprintf(buf, PSTR((char*)pgm_read_word(&(str_time_lu))), now());
-  net.responseSendPart(buf);
-  sprintf(buf, PSTR((char*)pgm_read_word(&(str_rangeLH_0_d_d))), range.lows[0], range.highs[0]);
-  net.responseSendPart(buf);
-  sprintf(buf, PSTR((char*)pgm_read_word(&(str_rangeLH_1_d_d))), range.lows[1], range.highs[1]);
-  net.responseSendPart(buf);
-  sprintf(buf, PSTR((char*)pgm_read_word(&(str_DcHeight_d_d))), selftest.startingHeight, selftest.endingHeight);
-  net.responseSendPart(buf);
-  sprintf(buf, PSTR((char*)pgm_read_word(&(str_pressure_d))), analogRead(PRESSURE_SENSOR_PIN));
-  net.responseSendPart(buf);
-  sprintf(buf, PSTR((char*)pgm_read_word(&(str_AcPumpCycles_d))), acpump.onCycles);
-  net.responseSendPart(buf);
-  sprintf(buf, PSTR((char*)pgm_read_word(&(str_lastAlertTime_lu))), alert.timeTriggered);
-  net.responseSendPart(buf);
-  sprintf(buf, PSTR((char*)pgm_read_word(&(str_rawDepthPressure_d))), analogRead(DEPTH_PRESSURE_SENSOR_PIN));
+  sprintf(buf, PSTR("time=%lu"), now());
+  net.responseSendPart(buf);
+  sprintf(buf, PSTR("rangeLH[0]=%d,%d"), range.lows[0], range.highs[0]);
+  net.responseSendPart(buf);
+  sprintf(buf, PSTR("&rangeLH[1]=%d,%d"), range.lows[1], range.highs[1]);
+  net.responseSendPart(buf);
+  sprintf(buf, PSTR("&DcHeight=%d,%d"), selftest.startingHeight, selftest.endingHeight);
+  net.responseSendPart(buf);
+  sprintf(buf, PSTR("&pressure=%d"), analogRead(PRESSURE_SENSOR_PIN));
+  net.responseSendPart(buf);
+  sprintf(buf, PSTR("&AcPumpCycles=%d"), acpump.onCycles);
+  net.responseSendPart(buf);
+  sprintf(buf, PSTR("&lastAlertTime=%lu"), alert.timeTriggered);
+  net.responseSendPart(buf);
+  sprintf(buf, PSTR("&rawDepthPressure=%d"), analogRead(DEPTH_PRESSURE_SENSOR_PIN));
   net.responseSendPart(buf);
 //  sprintf(buf, );
 //  net.responseSendPart(buf);
@@ -412,17 +350,17 @@

 void sendSelfTestResponse()
 {
-   sprintf(buf, PSTR((char*)pgm_read_word(&(str_timeSince_lu))), (now() - selftest.lastTestTime));
+   sprintf(buf, PSTR("timeSince=%lu&"), (now() - selftest.lastTestTime));
    net.responseSendPart(buf);
-   sprintf(buf, PSTR((char*)pgm_read_word(&(str_cyclesSince_d))), acpump.onCycles-selftest.acCycles);
+   sprintf(buf, PSTR("cyclesSince=%d&"), acpump.onCycles-selftest.acCycles);
    net.responseSendPart(buf);
-   sprintf(buf, PSTR((char*)pgm_read_word(&(str_voltage_d))), selftest.batteryVoltageMv);
+   sprintf(buf, PSTR("voltage=%d&"), selftest.batteryVoltageMv);
    net.responseSendPart(buf);
-   sprintf(buf, PSTR((char*)pgm_read_word(&(str_length_d))), (int)selftest.testLength);
+   sprintf(buf, PSTR("length=%d&"), (int)selftest.testLength);
    net.responseSendPart(buf);
-   sprintf(buf, PSTR((char*)pgm_read_word(&(str_pumpedHeight_d))), selftest.startingHeight - selftest.endingHeight);
+   sprintf(buf, PSTR("pumpedHeight=%d&"), selftest.startingHeight - selftest.endingHeight);
    net.responseSendPart(buf);
-   sprintf(buf, PSTR((char*)pgm_read_word(&(str_result_d))), selftest.passed);
+   sprintf(buf, PSTR("result=%d"), selftest.passed);
    net.responseSendPart(buf);
    net.responseEnd();
 }
@@ -484,14 +422,14 @@
     // Battery voltage should not drop too much
     if (selftest.batteryVoltageMv < conf.alertBatteryVoltage) {
       selftest.passed = false;
-      sprintf(buf, PSTR((char*)pgm_read_word(&(str_Weak_battery_dmV))), selftest.batteryVoltageMv);
+      sprintf(buf, PSTR("Weak battery: %dmV"), selftest.batteryVoltageMv);
       raiseAlert(DcPumpMalfunction, buf);
       return;
     }
     // Determine if water level was reduced enough
     if (selftest.startingHeight - selftest.endingHeight < 5) {
       selftest.passed = false;
-      sprintf(buf, PSTR((char*)pgm_read_word(&(str_DC_Pump_failure_dCM_pumped_in_d_sec))), (selftest.startingHeight - selftest.endingHeight), (int)selftest.testLength);
+      sprintf(buf, PSTR("DC Pump failure: %dCM pumped in %d sec."), (selftest.startingHeight - selftest.endingHeight), (int)selftest.testLength);
       raiseAlert(DcPumpMalfunction, buf);
       return;
     }
@@ -530,13 +468,13 @@
   // If voltage is more than 0, then pump is on, and we need to sound an alert
   // Need to make sure to wait a few seconds after self test to see if DC pump is ON
   if (mv > 9000 && (now() - selftest.lastTestTime) > (conf.selfTestTimeLimit + 6)) {
-    raiseAlert(DcPumpActivated, PSTR((char*)pgm_read_word(&(str_DC_Pump_ON))));
+    raiseAlert(DcPumpActivated, PSTR("DC Pump ON"));
     // Record that the pump is on, or process alert, if it was already on.
     if (!dcpump.currentlyOn) {
       dcpump.currentlyOn = true;
       dcpump.switchOnTime = now();
     } else if ((now() - dcpump.switchOnTime) > conf.dcPumpOnTimeWarning) {
-      raiseAlert(DcPumpOverload, PSTR((char*)pgm_read_word(&(str_DC_pump_ON_too_long))));
+      raiseAlert(DcPumpOverload, PSTR("DC pump ON too long"));
     }
   } else {
     dcpump.currentlyOn = false;
@@ -549,7 +487,7 @@
 {
   unsigned int mv = getVoltage( BATTERY_VOLTAGE_PIN );
   if (mv < conf.alertBatteryVoltage) {
-    raiseAlert(DischargedBattery, PSTR((char*)pgm_read_word(&(str_Battery_voltage))));
+    raiseAlert(DischargedBattery, PSTR("Battery voltage"));
   }
   return mv;
 }
@@ -573,7 +511,7 @@

   if (range.distance > conf.alertWaterLevel) {
     char tmp[40];
-    sprintf(tmp, PSTR((char*)pgm_read_word(&(str_Water_level_d))), range.distance);
+    sprintf(tmp, PSTR("Water level: %d"), range.distance);
     raiseAlert(WaterLevel, tmp);
   }
   return range.distance;
@@ -585,7 +523,7 @@

   // Alert business
   if (acpump.lastPressure > conf.alertPressureLevel) {
-    raiseAlert(HighPressure, PSTR((char*)pgm_read_word(&(str_High_pressure))));
+    raiseAlert(HighPressure, PSTR("High pressure"));
   }

   boolean currentlyOn;
@@ -621,7 +559,7 @@
   // Check if AC pump was on for too long
   if (currentlyOn) {
     if ((now() - acpump.switchOnTime) > conf.acPumpOnTimeWarning) {
-      raiseAlert(AcPumpOverload, PSTR((char*)pgm_read_word(&(str_AC_pump_ON_for_too_long))));
+      raiseAlert(AcPumpOverload, PSTR("AC pump ON for too long"));
     }
   }


Added more message types to HMTL_Command_CLI

--- utilities/HMTL_Command_CLI/HMTL_Command_CLI.ino
+++ utilities/HMTL_Command_CLI/HMTL_Command_CLI.ino
@@ -51,7 +51,7 @@
 config_hdr_t config;

 void setup() {
-  Serial.begin(9600);
+  Serial.begin(57600);
   DEBUG2_PRINTLN("*** HMTL_Command_CLI starting ***");

   config_max_t readoutputs[HMTL_MAX_OUTPUTS];
@@ -60,6 +60,11 @@
                                      &rs485, NULL, NULL,
                                      &rgb_output, NULL,
                                      NULL);
+
+  if (!(outputs_found & (1 << HMTL_OUTPUT_RS485))) {
+    DEBUG_ERR("No RS485 config found");
+    DEBUG_ERR_STATE(1);
+  }

   /* Setup the RS485 connection */
   rs485.setup();
@@ -131,13 +136,51 @@
   DEBUG_PRINT_END();

   switch (msg->type) {
+
+    case MSG_TYPE_OUTPUT: {
+      DEBUG1_PRINT(" * OUTPUT");
+      break;
+    }
+
+    case MSG_TYPE_POLL: {
+      DEBUG1_PRINT(" * POLL:");
+      if (msg->flags & MSG_FLAG_ACK) {
+        if (msg->length < HMTL_MSG_POLL_MIN_LEN) {
+          DEBUG1_VALUE("Bad length: ", msg->length);
+          DEBUG1_VALUE(" < ", HMTL_MSG_POLL_MIN_LEN);
+          break;
+        }
+
+        msg_poll_response_t *poll = (msg_poll_response_t *)(msg + 1);
+        hmtl_print_header(&poll->config);
+        DEBUG1_VALUE(" type:", poll->object_type);
+        DEBUG1_VALUE(" rcvbuff:", poll->recv_buffer_size);
+        DEBUG1_VALUE(" msgver:", poll->msg_version);
+      }
+      break;
+    }
+
+    case MSG_TYPE_SET_ADDR: {
+      DEBUG1_PRINT(" * SET_ADDR:");
+
+      if (msg->length != HMTL_MSG_SET_ADDR_LEN) {
+        DEBUG1_VALUE("Wrong length: ", msg->length);
+        DEBUG1_VALUE(" not ", HMTL_MSG_SET_ADDR_LEN);
+        break;
+      }
+
+      msg_set_addr_t *set = (msg_set_addr_t *)(msg + 1);
+      DEBUG1_VALUE(" dev_id:", set->device_id);
+      DEBUG1_VALUE(" addr:", set->address);
+      break;
+    }
+
     case MSG_TYPE_SENSOR: {
-      DEBUG1_PRINTLN(" * Sensor data:");
+      DEBUG1_PRINTLN(" * SENSOR:");

       msg_sensor_data_t *sense = NULL;
-      while (sense = hmtl_next_sensor(msg, sense)) {
-        DEBUG1_VALUE(" ptr:", (int)sense);
-        DEBUG1_VALUE(" type:", sense->sensor_type);
+      while ((sense = hmtl_next_sensor(msg, sense))) {
+        DEBUG1_VALUE("   type:", sense->sensor_type);
         DEBUG1_VALUE(" datalen:", sense->data_len);

         switch (sense->sensor_type) {
@@ -169,10 +212,7 @@
       }
       break;
     }
-    case MSG_TYPE_POLL: {
-      DEBUG1_PRINT("POLL");
-      break;
-    }
+
   }

   DEBUG_PRINT_END();


Update to tested and working code

Update to tested and working code

--- firmware/examples/blank/blank.ino
+++ firmware/examples/blank/blank.ino
@@ -3,22 +3,19 @@
 // Fingerprint sensor connected to RX/TX (Serial1)
 // on the Spark

-void setup() {
-  // initialize both serial ports:
+void setup()
+{
+  // Open serial communications and wait for port to open:
   Serial.begin(57600);
   Serial1.begin(57600);
+
 }

-void loop() {
-  // read from Serial1 (Fingerprint reader), send to Serial (USB to PC)
-  if (Serial1.available()) {
-    int inByte = Serial1.read();
-    Serial.write(inByte);
-  }
+void loop() // run over and over
+{
+  while (Serial1.available())
+    Serial.write(Serial1.read());

-  // read from Serial (USB to PC), send to Serial1 (Fingerprint reader)
-  if (Serial.available()) {
-    int inByte = Serial.read();
-    Serial1.write(inByte);
-  }
-}+  while (Serial.available())
+    Serial1.write(Serial.read());
+}


Delete LORA_repeater_bot.ino

Delete LORA_repeater_bot.ino

--- LORA_repeater/LORA_repeater_bot.ino
+++ LORA_repeater/LORA_repeater_bot.ino
@@ -1,59 +0,0 @@
-#include <RHReliableDatagram.h>
-#include <RH_RF95.h>
-#include <SPI.h>
-
-#define MY_ADDRESS 1
-#define TARGET_ADDRESS 2
-#define MAX_LEN 40
-
-RH_RF95 driver;
-RHReliableDatagram manager(driver, MY_ADDRESS);
-
-bool check = 0;
-uint8_t data[MAX_LEN];
-uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
-
-String outstr="";
-int SNR;
-char ricevuto[MAX_LEN];
-
-void setup() {
-
-  manager.init();
-  driver.setTxPower(23, false);
-
-  //Serial.begin(9600);
-
-}
-
-void loop() {
-
-  if (manager.available()) {
-
-    uint8_t len = sizeof(buf);
-    uint8_t from;
-
-    check = manager.recvfromAckTimeout(buf, &len, 2000, &from);
-
-    //Serial.println((char*)buf);
-
-    if (check) {
-
-      SNR = driver.lastSNR();
-
-      outstr = "A,";
-      outstr.concat((char*)buf);
-      outstr.concat(",");
-      outstr.concat(SNR);
-      outstr.concat(",Z");
-      outstr.getBytes(data, outstr.length()+10);
-
-      manager.sendtoWait(data, sizeof(data), TARGET_ADDRESS);
-
-      check = 0;
-
-    }
-
-  } // Manager available
-
-}


Increase sample rate, decrease print rate

--- inverted-pendulum.ino
+++ inverted-pendulum.ino
@@ -36,9 +36,9 @@

 // PID control for cart position
 float kp = 2, ki = 200, kd = 0; // Initial/default PID gain coeffs
-unsigned long timeStep = 20; // ms
-PIDControl cartPid(kp, ki, kd, 0, timeStep);
-elapsedMillis pidTimer = 0;
+PIDControl cartPid(kp, ki, kd, 0, 10); // p,i,d, initial setpoint, timestep [ms]
+elapsedMillis printTimer = 0;
+unsigned int printerval = 50; // ms

 // Command callbacks for use by SimpleShell
 ExecStatus setPID(CommandLine *cl)
@@ -283,9 +283,9 @@
   float pwmSetting = op < 0.01 ? 0 : (op + 0.1)*maxPwm;
   analogWrite(PWM_PIN, pwmSetting);

-  if (pidTimer >= timeStep)
-  {
-    pidTimer -= timeStep;
+  if (printTimer >= printerval)
+  {
+    printTimer -= printerval;
     printStatus(cartPid);
   }
 }


Removed unused uin8_t.

Removed unused uin8_t.

--- aquacontrol32.ino
+++ aquacontrol32.ino
@@ -155,7 +155,6 @@
 const uint8_t oledTaskPriority         = 3;
 const uint8_t wifiTaskPriority         = 2;
 const uint8_t loggerTaskPriority       = 1;
-const uint8_t versionCheckPriority     = 1;
 const uint8_t spiffsTaskPriority       = 0;


don't show temperature decimal place for initial sceen

--- short-circuit-limiter/short-circuit-limiter.ino
+++ short-circuit-limiter/short-circuit-limiter.ino
@@ -130,8 +130,8 @@
       sprintf(fullBuff,"Curr Temp: %sC", valueBuff);
       u8g2.drawStr(0,31, fullBuff);

-      dtostrf(TEMP_WARN, 2, 1, valueBuff);
-      dtostrf(TEMP_MAX, 2, 1, valueBuff2);
+      dtostrf(TEMP_WARN, 2, 0, valueBuff);
+      dtostrf(TEMP_MAX, 2, 0, valueBuff2);
       sprintf(fullBuff,"Temp Warn/Max : %s/%s C", valueBuff, valueBuff2);
       u8g2.drawStr(0,39, fullBuff);


Fix missing semi-colon

Fix missing semi-colon

When I removed my passwords I accidentally removed the closing curly
brace and when I added it back I forgot the semi-colon.

--- TeensyKeySketch/TeensyKeySketch.ino
+++ TeensyKeySketch/TeensyKeySketch.ino
@@ -25,7 +25,7 @@
 "1234",
 "TOP SECRET",
 "Samsung1"
-}
+};

 void loop() {
   int n, password_index;


Require Teensy 3.1

Require Teensy 3.1

--- arduino/DiskInterface/DiskInterface.ino
+++ arduino/DiskInterface/DiskInterface.ino
@@ -30,6 +30,10 @@

 */

+#if !defined(__MK20DX256__)
+#error Oops!  Make sure you have 'Teensy 3.1' selected from the 'Tools -> Board' menu.
+#endif
+
 #include "./Timer.h"
 #include "./Bounce2.h"
 #include "DiskInterface.h"


Use Arduino101 CurieIMU new APIs.

Use Arduino101 CurieIMU new APIs.

--- Arduino/Arduino101_Accelerometer/Arduino101_Accelerometer.ino
+++ Arduino/Arduino101_Accelerometer/Arduino101_Accelerometer.ino
@@ -1,22 +1,22 @@
-#include "CurieImu.h"
+#include "CurieIMU.h"

-int16_t ax, ay, az;
+int ax, ay, az;

 void setup() {
   Serial.begin(9600);
   while (!Serial);

-  CurieImu.initialize();
+  CurieIMU.begin();

-  if (!CurieImu.testConnection()) {
+  if (!CurieIMU.testConnection()) {
     Serial.println("CurieImu connection failed");
   }

-  CurieImu.setFullScaleAccelRange(BMI160_ACCEL_RANGE_8G);
+  CurieIMU.setAccelerometerRange(8);
 }

 void loop() {
-  CurieImu.getAcceleration(&ax, &ay, &az);
+  CurieIMU.readAccelerometer(ax, ay, az);
   Serial.print(ax);
   Serial.print("\t");
   Serial.print(ay);


FW-32: Turn off LCD after 20 seconds and turn it back on when any event happens

--- src/IoTBox.ino
+++ src/IoTBox.ino
@@ -210,6 +210,9 @@
 int configureTime(String time);
 void syncTimeWithCloudIfNeeded();

+volatile int displayTimerCounter = 0;
+int displayState = 0; // 0 = off, 1 = on
+
 struct ConfigurationTime {
     uint8_t version;
     int hour;
@@ -231,11 +234,8 @@
     pinMode(SWITCHPIN, INPUT);
     attachInterrupt(SWITCHPIN, updateSwitchState, CHANGE);

-    //pinMode(BUTTONPIN, INPUT_PULLDOWN);
-    //attachInterrupt(BUTTONPIN, updateButtonState, RISING);
+    // Setup button timers (all in milliseconds / ms)
     pinMode(BUTTONPIN, INPUT);
-    // Setup button timers (all in milliseconds / ms)
-    // (These are default if not set, but changeable for convenience)
     button.debounceTime   = 20;   // Debounce timer in ms
     button.multiclickTime = 250;  // Time limit for multi clicks
     button.longClickTime  = 1000; // time until "held-down clicks" register
@@ -245,7 +245,8 @@

     // Setup the lcd
     lcd.begin(16, 2); // Set up the LCD's number of columns and rows.
-    lcd.setRGB(200, 200, 200); // Set up background backlight color.
+    //lcd.setRGB(100, 100, 100); // Set up background backlight color.
+    displayState = 1;

     // Setup timezone
     Time.zone(+2.00);
@@ -356,6 +357,11 @@
         publishData();

         if (!isLCDBusy) {
+            if (!displayState) {
+                lcd.display();
+                lcd.setColorWhite();
+                displayState = 1;
+            }
             isLCDBusy = true;
             if (switchState == HIGH) {
                 lcd.setCursor(0,1);
@@ -384,13 +390,35 @@

     //requestDisplayTime = true;

+    checkDisplayCondition();
+
     checkOpenCondition();
 }

+void checkDisplayCondition() {
+    // Only check to turn off the display when the display is currently on
+    if (displayState == 1) {
+        displayTimerCounter++;
+        Serial.println(displayTimerCounter);
+        if (displayTimerCounter > 20) {
+            displayTimerCounter = 0;
+            displayState = 0;
+            lcd.setColorAll();
+            lcd.noDisplay();
+            Serial.println("should turn off display now");
+        }
+    }
+}
+
 void displayTime() {
+    if (!displayState) {
+        return;
+    }
+
     if (!requestDisplayConfigurationTime) {
         if (requestDisplayTime) {
             if (!isLCDBusy) {
+
                 isLCDBusy = true;
                 lcd.setCursor(0,0);
                 lcd.print("          ");
@@ -411,6 +439,11 @@
         startBuzzerForConfiguration();

         if (!isLCDBusy) {
+            if (!displayState) {
+                lcd.display();
+                lcd.setColorWhite();
+                displayState = 1;
+            }
             isLCDBusy = true;
             lcd.setCursor(11,0);
             lcd.print(configurationTime.hour);
@@ -441,11 +474,8 @@
 void updateSwitchState() {
     switchState = digitalRead(SWITCHPIN);
     requestDisplayStatus = true;
-}
-
-// void updateButtonState() {
-//     startOpenOperation("");
-// }
+    displayTimerCounter = 0;
+}

 int startOpenOperation(String command) {
     requestOpeningOperation = true;
@@ -460,6 +490,9 @@

 int configureTime(String time)
 {
+    // Keep the display on
+    displayTimerCounter = 0;
+
     // Declare the variables of the parts of the String
     String hourString, minuteString;
     int hour, minute;


Update SW01_Altitude_Measurement.ino

Update SW01_Altitude_Measurement.ino


sketch uses Serial1 again. it used Serial previously, which was good for debugging but not good for actually using it.

--- explorad_inputDevice.ino
+++ explorad_inputDevice.ino
@@ -2,7 +2,7 @@

 #include "inputType.h"

-#define SerialOutputDevice Serial// SerialDevice
+#define SerialOutputDevice Serial1// SerialDevice

 #define PIN_LEFT 0
 #define PIN_UP 1


Delete sketch_jan20a.ino

Delete sketch_jan20a.ino

--- src/Sensors/sketch_jan20a.ino
+++ src/Sensors/sketch_jan20a.ino
@@ -1,94 +0,0 @@
-int lastInterruptIndex = -1;
-int headIntIndex = -1;
-char InterruptLog[256] = {0};
-unsigned long TimeLog[256] = {0};
-bool ramOverflow = false;
-
-void setup()
-{
-  Serial.begin(9600);
-  Serial.println("i am 12 and wat is this");
-  InitialiseIO();
-  InitialiseInterrupt();
-}
-
-void loop() {
-   delay(500);
-   int kek = analogRead(A0);
-   Serial.println(kek);
-   Serial.println("oh shit");
-   if (ramOverflow){
-    Serial.println("Overflowed SRAM buffer!");
-    ramOverflow = false; //reset, this is not strictly unrecoverable.
-   }
-   if (lastInterruptIndex < 0){
-    return; //restart the loop don't do unneccessary work
-   }
-   int A0 = 0;
-   int A1 = 0;
-   int A2 = 0;
-   for( int i = headIntIndex; i < lastInterruptIndex; i++){
-    char toTwiddle = InterruptLog[i];
-    char temp0 = toTwiddle & 0x1;
-    char temp1 = (toTwiddle & 0x2) >> 1;
-    char temp2 = (toTwiddle & 0x4) >> 2;
-    A0 += temp0;
-    A1 += temp1;
-    A2 += temp2;
-   }
-   unsigned long timeElapsed = (TimeLog[lastInterruptIndex] - TimeLog[0])/(10^6);
-   float avg0 = A0/timeElapsed;
-   float avg1 = A1/timeElapsed;
-   float avg2 = A2/timeElapsed;
-   Serial.println(avg0, 2);
-   Serial.println(avg1, 2);
-   Serial.println(avg2, 2);
-   return;
-}
-
-void InitialiseIO(){
-  pinMode(A0, INPUT);     // Pin A0 is input to which a switch is connected
-  digitalWrite(A0, HIGH);   // Configure internal pull-up resistor
-  pinMode(A1, INPUT);    // Pin A1 is input to which a switch is connected
-  digitalWrite(A1, HIGH);   // Configure internal pull-up resistor
-  pinMode(A2, INPUT);    // Pin A2 is input to which a switch is connected
-  digitalWrite(A2, HIGH);      // Configure internal pull-up resistor
-}
-
-void InitialiseInterrupt(){
-  cli();    // switch interrupts off while messing with their settings
-  PCICR =0x02;          // Enable PCINT1 interrupt
-  PCMSK1 = 0b00000111;
-  sei();    // turn interrupts back on
-}
-
-ISR(PCINT1_vect) {    // Interrupt service routine. Every single PCINT8..14 (=ADC0..5) change
-            // will generate an interrupt: but this will always be the same interrupt routine
-  volatile char store = 0x0;
-
-  if (digitalRead(A0)==0){
-    store |= 0x1;
-    Serial.println("A0");
-  }
-
-  if (digitalRead(A1)==0){
-    store |= 0x2;;
-    Serial.println("A1");
-  }
-
-  if (digitalRead(A2)==0) {
-    store |= 0x4;
-    Serial.println("A2");
-  }
-
-  if (store > 0x0){
-    if (lastInterruptIndex >= 255){
-       lastInterruptIndex = -1; //if we are about to overflow buffer, overwrite oldest.
-       ramOverflow = true;
-    }
-    lastInterruptIndex++;
-    InterruptLog[lastInterruptIndex] = store;
-    TimeLog[lastInterruptIndex] = micros();
-  }
-}
-


Split motor definitions into multiple lines

--- firmware/src/sampler.ino
+++ firmware/src/sampler.ino
@@ -3,10 +3,9 @@
 #include "config.h"
 #include <DcMotor.h>

-DcMotor xMotor(X_AXIS_PWM, X_AXIS_FWD, X_AXIS_REV),
-  yMotor(Y_AXIS_PWM, Y_AXIS_FWD, Y_AXIS_REV),
-  zMotor(Z_AXIS_PWM, Z_AXIS_FWD, Z_AXIS_REV);
-
+DcMotor xMotor(X_AXIS_PWM, X_AXIS_FWD, X_AXIS_REV);
+DcMotor yMotor(Y_AXIS_PWM, Y_AXIS_FWD, Y_AXIS_REV);
+DcMotor zMotor(Z_AXIS_PWM, Z_AXIS_FWD, Z_AXIS_REV);

 void setup() {
   Serial.begin(BAUDRATE);


Se agrega sketch para contrar la matriz rgb 16x32


COH-71

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1246,11 +1246,7 @@
 #endif

   // Have 32678Hz clock at least running before going any further.
-#if defined(ENABLE_WAKEUP_32768HZ_XTAL)
   if(!::OTV0P2BASE::HWTEST::check32768HzOsc()) { panic(F("xtal")); } // Async clock not running correctly.
-#else
-  DEBUG_SERIAL_PRINTLN_FLASHSTRING("(No xtal.)");
-#endif

 //  // Signal that xtal is running AND give it time to settle.
 //  posPOST(0 /*, F("about to test radio module") */);


Filtro de média móvel arrumado

Filtro de média móvel arrumado

--- src/arduino/thermocoupleReader/thermocoupleReader.ino
+++ src/arduino/thermocoupleReader/thermocoupleReader.ino
@@ -14,7 +14,7 @@
 #define PIN_LM35      A0
 #define PIN_MTK01     A1

-#define INTERVAL      500  //ms
+#define INTERVAL      200  //ms
 #define SIZE_BUFFER   10
 #define SIZE_BUFFER_F 10   // Parâmentro Filtro Média Móvel
 #define ALPHA         0.8  // Parâmentro Filtro Média Móvel Ponderada
@@ -49,13 +49,13 @@
   pinMode(PIN_LM35,INPUT);
   pinMode(PIN_MTK01,INPUT);

-  // Zera Buffers
+  // Zera Buffers e Inicia Filtros
   for(k=0;k<SIZE_BUFFER;k++){
-    bufferLM35[k] = 0;
-    bufferMTK01[k] = 0;
+    bufferLM35[k] = analogRead(PIN_LM35);
+    bufferMTK01[k] = analogRead(PIN_MTK01);
     bufferAvgFilter[k] = 0;
-    bufferMvAvgFilter[k] = 0;
-    bufferMvAvgExpFilter[k] = 0;
+    bufferMvAvgFilter[k] = bufferLM35[k];
+    bufferMvAvgExpFilter[k] = bufferLM35[k];
   }

   // Zera Contadores
@@ -84,7 +84,7 @@
     // Filtragem
     bufferLM35[k] = rawTemp1;
     bufferMTK01[k] = rawTemp2;
-
+
     filterAverenge(bufferLM35,index,k);
     filterMovingAverenge(bufferLM35,k);
     filterMovingAverengeExp(bufferLM35,k);
@@ -108,7 +108,7 @@
   }
 }

-// Funções Auxliares ---------------------------------------------------------------------
+// Funções Auxiliares ---------------------------------------------------------------------

 /**
  * Filtro Média Simples
@@ -149,7 +149,7 @@
   int a3 = (k>2)?k-3:SIZE_BUFFER_F+k-3;

   // Aplica Filtro
-  bufferMvAvgExpFilter[k] = buffer[a3]*pMvAvgExpFilter[0];
+  bufferMvAvgExpFilter[k] = bufferMvAvgExpFilter[a3]*pMvAvgExpFilter[0];
   bufferMvAvgExpFilter[k] += buffer[a2]*pMvAvgExpFilter[1];
   bufferMvAvgExpFilter[k] += buffer[a1]*pMvAvgExpFilter[2];
   bufferMvAvgExpFilter[k] += buffer[k]*pMvAvgExpFilter[3];


Test input conversion

Test input conversion


Use static BPM until noise is fixed

Use static BPM until noise is fixed

--- heartbeat_with_pulse.ino
+++ heartbeat_with_pulse.ino
@@ -231,10 +231,14 @@
     bpm = staticBpm;
   }

+  // TODO Fix BPM noise
+  bpm = staticBpm;
+
   if (pulseBeatFound == true){
+//    offset = 0;
 //    serialOutputWhenBeatHappens();
+//    Serial.println(bpm);
     pulseBeatFound = false;
-//    Serial.println(bpm);
   }

   int i;


Update BM1422GMV.ino

Update BM1422GMV.ino

--- examples/BM1422GMV/BM1422GMV.ino
+++ examples/BM1422GMV/BM1422GMV.ino
@@ -1,66 +1,66 @@
-/*
- * BM1422GMV example
- *
- * This sketch shows you how to correctly setup iterrupts to use BM1422GMV magnetometer.
- *
- * Before powering up your Arduino, make sure to select 1.8V on jumper J15 on the shield!
- *
- * NOTE: The interrupt settings on the shield are following:
- *          J3 jumper connects interrupts to Arduino interrupt 0 (pin D2)
- *          J4 jumper connects interrupts to Arduino interrupt 1 (pin D3)
- *          INTRx pins on J3 and J4 are used to connect CMOS output interrupts for sensors KX022_1020 and BM1422GMV on header I2C_x
- *          INTx pins on J3 and J4 are used to connect interrupts which require external pull-up, these are for sensors BH1745NUC and BM1422GMV on header I2C_x
- *          J16 jumper is ON/OFF switch for the pull-up, when shorted, it will be ON: the pull-up resistor is 1kΩ, the logic HIGH will be 5V.
- *
- *        If we want to use the BM1422GMV magnetometer, we can connect it to the header I2C_1.
- *        Since BM1422GMV doesn't need an external pull-up, we can directly short INTR1 on J3 if we want to use Arduino interrupt 0 (default setting), or INTR1 on J4 if we want to use Arduino interrupt 1.
- */
-
-// define the sensor we will use
-#define INCLUDE_BM1422GMV
-
-// include the library
-#include <RohmMultiSensor.h>
-
-//instantiate the sensor's class
-BM1422GMV mag;
-
-// define the interrupt service routine
-void isr(void) {
-  mag.setFlagDrdy();
-}
-
-
-void setup() {
-  // begin serial communication
-  Serial.begin(9600);
-  Serial.println();
-
-  // begin the TWI (I2C) interface.
-  // this function has to be called before any calls to .init()!
-  Wire.begin();
-
-  // initialize BM1422GMV with the default values
-  // note that we have to provide the interrupt service routine to the .init() method
-  mag.init(isr);
-
-  Serial.println("X[uT]\tY[uT]\tZ[uT]");
-}
-
-void loop() {
-  // measure the sensor values
-  float* magValue = mag.measure();
-
-  // print the values to the serial port
-  Serial.print(magValue[0]);
-  Serial.print('\t');
-  Serial.print(magValue[1]);
-  Serial.print('\t');
-  Serial.println(magValue[2]);
-
-  // safely deallocate memory allocated for the dynami array 'magValue'
-  delete[] magValue;
-
-  // wait 100 ms before the next measurement
-  delay(100);
+/*
+ * BM1422GMV example
+ *
+ * This sketch shows you how to correctly setup iterrupts to use BM1422GMV magnetometer.
+ *
+ * Before powering up your Arduino, make sure to select 1.8V on jumper J15 on the shield!
+ *
+ * NOTE: The interrupt settings on the shield are following:
+ *          J3 jumper connects interrupts to Arduino interrupt 0 (pin D2)
+ *          J4 jumper connects interrupts to Arduino interrupt 1 (pin D3)
+ *          INTRx pins on J3 and J4 are used to connect CMOS output interrupts for sensors KX022_1020 and BM1422GMV on header I2C_x
+ *          INTx pins on J3 and J4 are used to connect interrupts which require external pull-up, these are for sensors BH1745NUC and BM1422GMV on header I2C_x
+ *          J16 jumper is ON/OFF switch for the pull-up, when shorted, it will be ON: the pull-up resistor is 1kΩ, the logic HIGH will be 5V.
+ *
+ *        If we want to use the BM1422GMV magnetometer, we can connect it to the header I2C_1.
+ *        Since BM1422GMV doesn't need an external pull-up, we can directly short INTR1 on J3 if we want to use Arduino interrupt 0 (default setting), or INTR1 on J4 if we want to use Arduino interrupt 1.
+ */
+
+// define the sensor we will use
+#define INCLUDE_BM1422GMV
+
+// include the library
+#include <RohmMultiSensor.h>
+
+//instantiate the sensor's class
+BM1422GMV mag;
+
+// define the interrupt service routine
+void isr(void) {
+  mag.setFlagDrdy();
 }
+
+
+void setup() {
+  // begin serial communication
+  Serial.begin(9600);
+  Serial.println();
+
+  // begin the TWI (I2C) interface.
+  // this function has to be called before any calls to .init()!
+  Wire.begin();
+
+  // initialize BM1422GMV with the default values
+  // note that we have to provide a pointer to the interrupt service routine for the .init() method
+  mag.init(*isr);
+
+  Serial.println("X[uT]\tY[uT]\tZ[uT]");
+}
+
+void loop() {
+  // measure the sensor values
+  float* magValue = mag.measure();
+
+  // print the values to the serial port
+  Serial.print(magValue[0]);
+  Serial.print('\t');
+  Serial.print(magValue[1]);
+  Serial.print('\t');
+  Serial.println(magValue[2]);
+
+  // safely deallocate memory allocated for the dynami array 'magValue'
+  delete[] magValue;
+
+  // wait 100 ms before the next measurement
+  delay(100);
+}


MIDIPiano minor wording update in comment

In MIDIPiano example, changed comment discussing calculation of
instrument number to replace the word "reported" with "displayed".

--- examples/MIDIPiano/MIDIPiano.ino
+++ examples/MIDIPiano/MIDIPiano.ino
@@ -138,8 +138,8 @@

   // Calculate the instrument ID and name
   // Using instrument numbers 1 to 128.
-  //  With id of type char (8 bits), instrument 128 is reported as -128.
-  //  Need id to be type int so instrument 128 is reported as 128.
+  //  With id of type char (8 bits), instrument 128 is displayed as -128.
+  //  Need id to be type int so instrument 128 is displayed as 128.
   int id;
   String fullName;
   if (index >= instruments_cnt) {


Namespaced defines

Namespaced defines

--- examples/SmokeTest/SmokeTest.ino
+++ examples/SmokeTest/SmokeTest.ino
@@ -1,47 +1,49 @@

-#define LED_S_GREEN   13 // D7
-#define LED_S_RED     12 // D6
-#define LED_RGB_RED   15 // D8
-#define LED_RGB_GREEN 14 // D5
-#define LED_RGB_BLUE  10 // SD3
-#define SW1 2
-#define SW2 16
+#define DENBIT_GREEN     13 // D7
+#define DENBIT_RED       12 // D6
+#define DENBIT_RGB_RED   15 // D8
+#define DENBIT_RGB_GREEN 14 // D5
+#define DENBIT_RGB_BLUE  10 // SD3
+#define DENBIT_SW1 2
+#define DENBIT_SW2 16

 void setup() {
-Serial.begin(115200);
-  pinMode(LED_S_GREEN, OUTPUT);
-  pinMode(LED_S_RED, OUTPUT);
+  // Single LEDs
+  pinMode(DENBIT_GREEN, OUTPUT);
+  pinMode(DENBIT_RED, OUTPUT);

-// RGB led
-  pinMode(LED_RGB_RED, OUTPUT);
-  pinMode(LED_RGB_GREEN, OUTPUT);
-  pinMode(LED_RGB_BLUE, OUTPUT);
+  // RGB led
+  pinMode(DENBIT_RGB_RED, OUTPUT);
+  pinMode(DENBIT_RGB_GREEN, OUTPUT);
+  pinMode(DENBIT_RGB_BLUE, OUTPUT);

-// Switches
-  pinMode(SW1, INPUT_PULLUP);
-  pinMode(SW2, INPUT_PULLUP);
+  // Switches
+  pinMode(DENBIT_SW1, INPUT_PULLUP);
+  pinMode(DENBIT_SW2, INPUT_PULLUP);
+
+  Serial.begin(115200);
 }

 void loop() {

-  digitalWrite(LED_S_GREEN, HIGH);
-  digitalWrite(LED_S_RED, HIGH);
+  digitalWrite(DENBIT_GREEN, HIGH);
+  digitalWrite(DENBIT_RED, HIGH);

-  digitalWrite(LED_RGB_RED, HIGH);
-  digitalWrite(LED_RGB_GREEN, HIGH);
-  digitalWrite(LED_RGB_BLUE, HIGH);
+  digitalWrite(DENBIT_RGB_RED, HIGH);
+  digitalWrite(DENBIT_RGB_GREEN, HIGH);
+  digitalWrite(DENBIT_RGB_BLUE, HIGH);

   delay(1000);

- byte sw1_state = digitalRead(SW1);
- byte sw2_state = digitalRead(SW2);
+ byte sw1_state = digitalRead(DENBIT_SW1);
+ byte sw2_state = digitalRead(DENBIT_SW2);

   // Do not flash if the button is not held down.
   if (sw1_state) {
-    digitalWrite(LED_S_GREEN, LOW);
+    digitalWrite(DENBIT_GREEN, LOW);
   }
   if (sw2_state) {
-    digitalWrite(LED_S_RED, LOW);
+    digitalWrite(DENBIT_RED, LOW);
   }

   int analog = analogRead(A0);
@@ -54,9 +56,9 @@
   Serial.print(analog);
   Serial.println();

-  digitalWrite(LED_RGB_RED, LOW);
-  digitalWrite(LED_RGB_GREEN, LOW);
-  digitalWrite(LED_RGB_BLUE, LOW);
+  digitalWrite(DENBIT_RGB_RED, LOW);
+  digitalWrite(DENBIT_RGB_GREEN, LOW);
+  digitalWrite(DENBIT_RGB_BLUE, LOW);

   delay(1000);
 }


modification pour mysensors 2.X

modification pour mysensors 2.X

--- examples/mySensors/mySensors.ino
+++ examples/mySensors/mySensors.ino
@@ -7,9 +7,12 @@
 //#define SLEEP_TIME 20000UL
 #define SLEEP_TIME 10000UL

+#define MY_RADIO_NRF24
+#define MY_RF24_PA_LEVEL RF24_PA_LOW
+
 // mysensors
 #include <SPI.h>
-#include <MySensor.h>
+#include <MySensors.h>

 // teleinfo
 #include <SoftwareSerial.h>
@@ -19,8 +22,6 @@

 // longueur max des données qu'on reçoit
 #define BUFSIZE 15
-
-MySensor gw;

 // paramètres des données téléinfo
 // - ne pas toucher :)
@@ -92,8 +93,7 @@
 	Serial.begin( 115200 );
 #endif

-	gw.begin();
-	gw.sendSketchInfo( "Teleinfo Sensor", TI.VERSION );
+	sendSketchInfo( "Teleinfo Sensor", TI.VERSION );

 	// une première lecture va nous donner l'option tarifaire
 	// on va s'en servir pour présenter uniquement les bons messages a la gateway
@@ -101,38 +101,38 @@
 	currentTI = TI.get();

 	// communs a tout le monde
-	gw.present( CHILD_ID_ADCO, S_POWER );
-	gw.present( CHILD_ID_OPTARIF, S_POWER );
-	gw.present( CHILD_ID_ISOUSC, S_POWER );
-	gw.present( CHILD_ID_PTEC, S_POWER );
-	gw.present( CHILD_ID_IINST, S_POWER );
-	gw.present( CHILD_ID_ADPS, S_POWER );
-	gw.present( CHILD_ID_IMAX, S_POWER );
-	gw.present( CHILD_ID_PAPP, S_POWER );
+	present( CHILD_ID_ADCO, S_POWER );
+	present( CHILD_ID_OPTARIF, S_POWER );
+	present( CHILD_ID_ISOUSC, S_POWER );
+	present( CHILD_ID_PTEC, S_POWER );
+	present( CHILD_ID_IINST, S_POWER );
+	present( CHILD_ID_ADPS, S_POWER );
+	present( CHILD_ID_IMAX, S_POWER );
+	present( CHILD_ID_PAPP, S_POWER );

 	if ( strcmp( currentTI.OPTARIF, "BASE" ) == 0 ) {
-		gw.present( CHILD_ID_BASE, S_POWER );
+		present( CHILD_ID_BASE, S_POWER );

 		tarif = TARIF_BASE;
 	} else if ( strcmp( currentTI.OPTARIF, "HC.." ) == 0 ) {
-		gw.present( CHILD_ID_HC_HC, S_POWER );
-		gw.present( CHILD_ID_HC_HP, S_POWER );
+		present( CHILD_ID_HC_HC, S_POWER );
+		present( CHILD_ID_HC_HP, S_POWER );

 		tarif = TARIF_HCHP;
 	} else if ( strcmp( currentTI.OPTARIF, "EJP." ) == 0 ) {
-		gw.present( CHILD_ID_EJP_HN, S_POWER );
-		gw.present( CHILD_ID_EJP_HPM, S_POWER );
-		gw.present( CHILD_ID_PEJP, S_POWER );
+		present( CHILD_ID_EJP_HN, S_POWER );
+		present( CHILD_ID_EJP_HPM, S_POWER );
+		present( CHILD_ID_PEJP, S_POWER );

 		tarif = TARIF_EJP;
 	} else if ( strstr( currentTI.OPTARIF, "BBR" ) != NULL ) { // ! c'est BBRx (x varie) d'ou un strstr et non strcmp
-		gw.present( CHILD_ID_BBR_HC_JB, S_POWER );
-		gw.present( CHILD_ID_BBR_HP_JB, S_POWER );
-		gw.present( CHILD_ID_BBR_HC_JW, S_POWER );
-		gw.present( CHILD_ID_BBR_HP_JW, S_POWER );
-		gw.present( CHILD_ID_BBR_HC_JR, S_POWER );
-		gw.present( CHILD_ID_BBR_HP_JR, S_POWER );
-		gw.present( CHILD_ID_DEMAIN, S_POWER );
+		present( CHILD_ID_BBR_HC_JB, S_POWER );
+		present( CHILD_ID_BBR_HP_JB, S_POWER );
+		present( CHILD_ID_BBR_HC_JW, S_POWER );
+		present( CHILD_ID_BBR_HP_JW, S_POWER );
+		present( CHILD_ID_BBR_HC_JR, S_POWER );
+		present( CHILD_ID_BBR_HP_JR, S_POWER );
+		present( CHILD_ID_DEMAIN, S_POWER );

 		tarif = TARIF_TEMPO;
 	}
@@ -153,7 +153,7 @@

 	// cas particulier, appartient a EJP et TEMPO
 	if ( (tarif & TARIF_EJP) || (tarif & TARIF_TEMPO) ) {
-		gw.present( CHILD_ID_HHPHC, S_POWER );
+		present( CHILD_ID_HHPHC, S_POWER );
 	}
 }

@@ -172,7 +172,7 @@
 #endif

 	last = value;
-	gw.send( msg.setSensor( SENSOR_ID ).set( last ) );
+	send( msg.setSensor( SENSOR_ID ).set( last ) );

 	return true;
 }
@@ -189,7 +189,7 @@
 #endif

 	last = value;
-	gw.send( msg.setSensor( SENSOR_ID ).set( last ) );
+	send( msg.setSensor( SENSOR_ID ).set( last ) );

 	return true;
 }
@@ -206,7 +206,7 @@
 #endif

 	last = value;
-	gw.send( msg.setSensor( SENSOR_ID ).set( last ) );
+	send( msg.setSensor( SENSOR_ID ).set( last ) );

 	return true;
 }
@@ -225,7 +225,7 @@
 	memset( last, 0, BUFSIZE );
 	strcpy( last, value );

-	gw.send( msg.setSensor( SENSOR_ID ).set( last ) );
+	send( msg.setSensor( SENSOR_ID ).set( last ) );

 	return true;
 }
@@ -234,7 +234,7 @@
 	teleInfo_t currentTI;

 	// Process incoming messages (like config from server)
-	gw.process();
+	//process();

 	// read téléinfo
 	currentTI = TI.get();
@@ -275,4 +275,4 @@

 	delay( SLEEP_TIME );
 	//gw.sleep( SLEEP_TIME );
-}+}


decrease light threshold, change on time

--- sensor_clock_2.ino
+++ sensor_clock_2.ino
@@ -25,13 +25,13 @@
 #define SLEEP_INTERVAL 250 //0.25s
 #define SLEEP_LONG_INTERVAL 45000 //45s

-#define LIGHT_THRESHOLD 100
+#define LIGHT_THRESHOLD 70

 #define OFF_HOUR 00
 #define OFF_MIN 00

-#define ON_HOUR 06 //Must be bigger than OFF_HOUR
-#define ON_MIN 30
+#define ON_HOUR 07 //Must be bigger than OFF_HOUR
+#define ON_MIN 00

 #define TURN_OFF_AT_TIMES true  //Set to false if you don't want the screen and readings to stop at certain times.


Cleanup code; properly pass string lengths

--- firmware/environmental-array.ino
+++ firmware/environmental-array.ino
@@ -23,8 +23,8 @@
 #include "particulates-pms7003.h"
 #include "humidity-temperature-sht31d.h"

-const int printbufSize = 256;
-char global_printbuf[printbufSize];
+const int g_printbuf_sz = 256;
+char g_printbuf[g_printbuf_sz];

 //const char degsym[] = "\xB0";  // Serial
 //const char degsym[] = "°"; // HTML
@@ -48,19 +48,19 @@
 int globalErrorCount = 0;
 bool initializing = true;

-bool readRht2Sensor(char outbuf[], int len) {
+bool readRht2Sensor(char outbuf[], int outbuf_sz) {
     rht2Sensor.readData();
-    rht2Sensor.snprintfData(outbuf, len);
+    rht2Sensor.snprintfData(outbuf, outbuf_sz);
     return rht2Sensor.checksumErr;
 }

-bool readPMSensor(char outbuf[], int len) {
+bool readPMSensor(char outbuf[], int outbuf_sz) {
     pmSensor.readData();
-    pmSensor.snprintfData(outbuf, len);
+    pmSensor.snprintfData(outbuf, outbuf_sz);
     return pmSensor.checksumErr;
 }

-bool readCO2Sensor(char outbuf[], int address) {
+bool readCO2Sensor(char outbuf[], int outbuf_sz, int address) {
     int rcw = 0;
     int co2errors = 0;
     unsigned char buffer[4];
@@ -71,8 +71,8 @@
     rcw = Wire.endTransmission();
     rcw = 0;
     if (rcw) {
-        snprintf(global_printbuf, printbufSize, "! CO2 COMMS error1 - RC = %d", rcw);
-        Particle.publish(DataSource, global_printbuf, 60, PRIVATE);
+        snprintf(g_printbuf, g_printbuf_sz, "! CO2 COMMS error1 - RC = %d", rcw);
+        Particle.publish(DataSource, g_printbuf, 60, PRIVATE);
         co2errors++;
         Wire.end();
         delay(500);
@@ -90,8 +90,8 @@
     Wire.write(0x2A);
     rcw = Wire.endTransmission();
     if (rcw) {
-        snprintf(global_printbuf, printbufSize, "! CO2 COMMS error2 - RC = %d", rcw);
-        Particle.publish(DataSource, global_printbuf, 60, PRIVATE);
+        snprintf(g_printbuf, g_printbuf_sz, "! CO2 COMMS error2 - RC = %d", rcw);
+        Particle.publish(DataSource, g_printbuf, 60, PRIVATE);
         co2errors++;
         rcw = Wire.endTransmission();
         rcw = Wire.endTransmission();
@@ -124,7 +124,7 @@
         rc = false;
     }

-    snprintf(outbuf, 64, "%d %02X%02X%02X%02X",
+    snprintf(outbuf, outbuf_sz, "%d %02X%02X%02X%02X",
              co2ppm,
              buffer[0], buffer[1], buffer[2], buffer[3]);

@@ -140,50 +140,51 @@
 }

-bool readBaroSensor(char outbuf[]) {
+bool readBaroSensor(char outbuf[], int outbuf_sz) {
     // Gather MS5637 sensor data
     if (!baroSensor.sensorReady) {
         baroSensor.resetDevice();
         delay(500);
         if (baroSensor.sensorReady) {
             uint16_t *vals = baroSensor.promV;
-            snprintf(global_printbuf, printbufSize,
+            snprintf(g_printbuf, g_printbuf_sz,
                 "! MS5637 READY - PROM=[%04X,%04X,%04X,%04X,%04X,%04X,%04X]",
                 vals[0], vals[1], vals[2], vals[3], vals[4], vals[5], vals[6]);
-            Particle.publish(DataSource, global_printbuf, 60, PRIVATE);
+            Particle.publish(DataSource, g_printbuf, 60, PRIVATE);
             delay(500);
         }
         else {
             uint16_t *vals = baroSensor.promV;
-            snprintf(global_printbuf, printbufSize,
+            snprintf(g_printbuf, g_printbuf_sz,
                 "! MS5637 FAIL! - PROM=[%04X,%04X,%04X,%04X,%04X,%04X,%04X]",
                 vals[0], vals[1], vals[2], vals[3], vals[4], vals[5], vals[6]);
-            Particle.publish(DataSource, global_printbuf, 60, PRIVATE);
+            Particle.publish(DataSource, g_printbuf, 60, PRIVATE);
             delay(500);
         }
     }
     // Is self-heating may be a problem at higher OSR values?
     baroSensor.readPressureAndTemperature(baroSensor.OSR8192);
-    snprintf(outbuf, 64, "%.2f %.2f %08X %08X",
+    snprintf(outbuf, outbuf_sz, "%.2f %.2f %08X %08X",
              baroSensor.pressureMbar, baroSensor.temperatureC,
              baroSensor.rawPressure,  baroSensor.rawTemperature);
     return true;
 }

-bool readRhtSensor(char outbuf[]) {
+bool readRhtSensor(char outbuf[], int outbuf_sz) {
     rhtSensor.update();
     double rhtTemperature = rhtSensor.getTemperature();
     double rhtHumidity = rhtSensor.getHumidity();
     uint8_t * rhtRawData = rhtSensor.getRaw();
-    snprintf(outbuf, 64, "%.2f %.2f  %02X%02X%02X%02X%02X",
+    snprintf(outbuf, outbuf_sz, "%.2f %.2f  %02X%02X%02X%02X%02X",
              rhtTemperature, rhtHumidity,
              rhtRawData[0], rhtRawData[1], rhtRawData[2], rhtRawData[3], rhtRawData[4]);
     return true;
 }

-bool disable9DOFSensor(char outbuf[]) {
-    snprintf(outbuf, 128, "BNO-055:");
+
+bool disable9DOFSensor(char outbuf[], int outbuf_sz) {
+    snprintf(outbuf, outbuf_sz, "BNO-055:");
     int BNO_i2c = 0x29;
     int rcw = 0;
     const int MAX_VALS = 8;
@@ -199,25 +200,25 @@
             vals[i] = Wire.read();
         }
     }
-    snprintf(outbuf, 128, "%s [", outbuf);
+    snprintf(outbuf, outbuf_sz, "%s [", outbuf);
     for (int i = 0; i < MAX_VALS-1; i++) {
-        snprintf(outbuf, 128, "%s%02X ", outbuf, vals[i]);
-    }
-    snprintf(outbuf, 128, "%s%02X]", outbuf, vals[MAX_VALS-1]);
+        snprintf(outbuf, outbuf_sz, "%s%02X ", outbuf, vals[i]);
+    }
+    snprintf(outbuf, outbuf_sz, "%s%02X]", outbuf, vals[MAX_VALS-1]);

     Wire.beginTransmission(BNO_i2c);
     rcw = Wire.write(0x3D);
     Wire.endTransmission();
     rcw = Wire.requestFrom(BNO_i2c, 1);
     aval = Wire.read() & 0x0f;
-    snprintf(outbuf, 128, "%s OPR=%02X", outbuf, aval);
+    snprintf(outbuf, outbuf_sz, "%s OPR=%02X", outbuf, aval);

     Wire.beginTransmission(BNO_i2c);
     rcw = Wire.write(0x3E);
     Wire.endTransmission();
     rcw = Wire.requestFrom(BNO_i2c, 1);
     aval = Wire.read() & 0x03;
-    snprintf(outbuf, 128, "%s PWR_prev=%02X", outbuf, aval);
+    snprintf(outbuf, outbuf_sz, "%s PWR_prev=%02X", outbuf, aval);

     Wire.beginTransmission(BNO_i2c);
     rcw = Wire.write(0x3E);
@@ -229,7 +230,7 @@
     Wire.endTransmission();
     rcw = Wire.requestFrom(BNO_i2c, 1);
     aval = Wire.read() & 0x03;
-    snprintf(outbuf, 128, "%s PWR_curr=%02X", outbuf, aval);
+    snprintf(outbuf, outbuf_sz, "%s PWR_curr=%02X", outbuf, aval);

     return true;
 }
@@ -240,8 +241,9 @@
     Wire.setSpeed(i2cDataRate);
     Wire.begin();
     delay(500);
-    char outbuf_tester[128];
-    disable9DOFSensor(outbuf_tester);
+    const int outbuf_9dof_sz = 128;
+    char outbuf_tester[outbuf_9dof_sz];
+    disable9DOFSensor(outbuf_tester, outbuf_9dof_sz);
     Particle.publish(DataSource, outbuf_tester, 60, PRIVATE);
     delay(2000);
 }
@@ -259,47 +261,52 @@
     currTimeS = Time.now();

     if (initializing) {
-        snprintf(global_printbuf, printbufSize, "SEQ_NUM %s %s %s %s",
+        snprintf(g_printbuf, g_printbuf_sz, "SEQ_NUM %s %s %s %s",
             header_co2, header_baro, header_rht, header_rht2);
-        Particle.publish(DataSource, global_printbuf, 60, PRIVATE);
+        Particle.publish(DataSource, g_printbuf, 60, PRIVATE);
         // 12345678 9999 FFFFFFFF 9999.99 -999.99 FFFFFFFF FFFFFFFF -999.99 44.50 FFFFFFFFFF
         initializing = false;
         delay(2000);
     }

     // Gather CO2 sensor data
-    char outbuf_co2[64];
-    readCO2Sensor(outbuf_co2, co2SensorAddr);
+    const int outbuf_co2_sz = 64;
+    char outbuf_co2[outbuf_co2_sz];
+    readCO2Sensor(outbuf_co2, outbuf_co2_sz, co2SensorAddr);
     delay(1000);

     // Gather MS5637 sensor data
-    char outbuf_baro[64];
-    readBaroSensor(outbuf_baro);
+    const int outbuf_baro_sz = 64;
+    char outbuf_baro[outbuf_baro_sz];
+    readBaroSensor(outbuf_baro, outbuf_baro_sz);
     delay(500);

     // Gather RHT sensor data
-    char outbuf_rht[64];
-    readRhtSensor(outbuf_rht);
+    const int outbuf_rht_sz = 64;
+    char outbuf_rht[outbuf_rht_sz];
+    readRhtSensor(outbuf_rht, outbuf_rht_sz);
     delay(500);

     // Gather PM sensor data
-    char outbuf_pm[192];
-    readPMSensor(outbuf_pm, 192);
+    const int outbuf_pm_sz = 192;
+    char outbuf_pm[outbuf_pm_sz];
+    readPMSensor(outbuf_pm, outbuf_pm_sz);
     delay(500);

     // Gather RHT2 sensor data
-    char outbuf_rht2[64];
-    readRht2Sensor(outbuf_rht2, 64);
+    const int outbuf_rht2_sz = 64;
+    char outbuf_rht2[outbuf_rht2_sz];
+    readRht2Sensor(outbuf_rht2, outbuf_rht2_sz);
     delay(500);

     // Return whatever data we got
-    snprintf(global_printbuf, printbufSize, "%08X OK K30:{%s} MS5637:{%s} RHT03:{%s} SHT31:{%s}",
+    snprintf(g_printbuf, g_printbuf_sz, "%08X OK K30:{%s} MS5637:{%s} RHT03:{%s} SHT31:{%s}",
              currTimeS, outbuf_co2, outbuf_baro, outbuf_rht, outbuf_rht2);
-    Particle.publish(DataSource, global_printbuf, 60, PRIVATE);
-
-    snprintf(global_printbuf, printbufSize, "%08X OK PMS7003:{%s}",
+    Particle.publish(DataSource, g_printbuf, 60, PRIVATE);
+
+    snprintf(g_printbuf, g_printbuf_sz, "%08X OK PMS7003:{%s}",
              currTimeS, outbuf_pm);
-    Particle.publish(DataSource, global_printbuf, 60, PRIVATE);
+    Particle.publish(DataSource, g_printbuf, 60, PRIVATE);

     // Global error handling
     if (globalErrorCount >= MaxErrCnt) {


first run!

first run!

--- coni/arduino/test/remote/button.ino
+++ coni/arduino/test/remote/button.ino
@@ -3,6 +3,9 @@
 #define SEL_B 31 //0 su 2
 #define BT_A A14 //0 premuto
 #define BT_B A8 //1 premuto
+
+long muovi(char let, int vel, int posA, int posB, int posC = 0);
+long t0 = 0;

 void setup() {
   pinMode(MAINSW, INPUT_PULLUP);
@@ -16,14 +19,28 @@
   Serial2.begin(4800);
 }

+int act = 0;
+long att1 = 0;
+long att2 = 0;
+bool inviato = false;
+
 void loop() {
   while (digitalRead(MAINSW)) //SHOW
   {
-    Serial.println("show!");
-    delay(500);
+    if (act == 0) {
+      t0 = millis();
+      Serial.println("ACT 0");
+      inviato = false;
+      act++;
+    }
+    show();
   }
   while (!digitalRead(MAINSW)) //TEST
   {
+    act = 0;
+    if (Serial.available() > 0) {
+      Serial2.write(Serial.read());
+    }
     if ((digitalRead(SEL_A) == 0) && (digitalRead(SEL_B) == 1)) //A
     {
       if (digitalRead(BT_A) == 0)  //premuto
@@ -143,3 +160,255 @@
     }
   }
 }
+
+void show() {
+
+  //eppur si muove
+  if (act == 1) {
+    if (inviato == false) {
+      Serial.print("ACT ");
+      Serial.print(act);
+      Serial.print(" tempo: att1: ");
+
+      att1 = muovi('p',3500,-90,360);
+
+      Serial.print(att1);
+
+      att2 = 0;
+
+      Serial.print(" att2: ");
+      Serial.println(att2);
+
+      inviato = true;
+    }
+
+    if ((millis() - t0) > magg(att1,att2)) {
+      act++;
+      inviato = false;
+      t0 = millis();
+    }
+  }
+
+  //ti riconosco
+  if (act == 2) {
+    if (inviato == false) {
+      Serial.print("ACT ");
+      Serial.print(act);
+      Serial.print(" tempo: att1: ");
+
+      att1 = muovi('p',1500,-90,0);
+
+      Serial.print(att1);
+
+      att2 = muovi('g',1800,90,-100,0);
+
+      Serial.print(" att2: ");
+      Serial.println(att2);
+
+      inviato = true;
+    }
+
+    if ((millis() - t0) > magg(att1,att2)) {
+      act++;
+      inviato = false;
+      t0 = millis() + 3000;
+    }
+  }
+
+  //il pubblico
+  if (act == 3) {
+    if (inviato == false) {
+      Serial.print("ACT ");
+      Serial.print(act);
+      Serial.print(" tempo: att1: ");
+
+      att1 = muovi('p',2000,90,0);
+
+      Serial.print(att1);
+
+      att2 = muovi('g',2000,-90,0,110);
+
+      Serial.print(" att2: ");
+      Serial.println(att2);
+
+      inviato = true;
+    }
+
+    if ((millis() - t0) > magg(att1,att2)) {
+      act++;
+      inviato = false;
+      t0 = millis() + 5000;
+    }
+  }
+
+  //più pubblico
+  if (act == 4) {
+    if (inviato == false) {
+      Serial.print("ACT ");
+      Serial.print(act);
+      Serial.print(" tempo: att1: ");
+
+      att1 = muovi('p',3000,0,90);
+
+      Serial.print(att1);
+
+      att2 = muovi('g',3000,-90,100,0);
+
+      Serial.print(" att2: ");
+      Serial.println(att2);
+
+      inviato = true;
+    }
+
+    if ((millis() - t0) > magg(att1,att2)) {
+      act++;
+      inviato = false;
+      t0 = millis() + 4000;
+    }
+  }
+
+  //danza #1
+  if (act == 5) {
+    if (inviato == false) {
+      Serial.print("ACT ");
+      Serial.print(act);
+      Serial.print(" tempo: att1: ");
+
+      att1 = muovi('p',5000,360,720);
+
+      Serial.print(att1);
+
+      att2 = muovi('g',4800,-630,720,-830);
+
+      Serial.print(" att2: ");
+      Serial.println(att2);
+
+      inviato = true;
+    }
+
+    if ((millis() - t0) > magg(att1,att2)) {
+      act++;
+      inviato = false;
+      t0 = millis();
+    }
+  }
+
+  //danza #2
+  if (act == 6) {
+    if (inviato == false) {
+      Serial.print("ACT ");
+      Serial.print(act);
+      Serial.print(" tempo: att1: ");
+
+      att1 = muovi('p',5200,360,720);
+
+      Serial.print(att1);
+
+      att2 = muovi('g',5000,-630,720,-830);
+
+      Serial.print(" att2: ");
+      Serial.println(att2);
+
+      inviato = true;
+    }
+
+    if ((millis() - t0) > magg(att1,att2)) {
+      act++;
+      inviato = false;
+      t0 = millis();
+    }
+  }
+
+
+
+
+
+
+}
+
+long magg(long a, long b) {
+  if (a >= b) {
+    return a;
+  }
+  else {
+    return b;
+  }
+}
+
+long muovi(char let, int vel, int posA, int posB, int posC = 0) {
+  String payload = "";
+
+  if (let == 'p') {
+    char LET = 'P';
+
+    payload += LET;
+    payload += " ";
+    payload += String(vel);
+    payload += '\r';
+
+    Serial2.print(payload);
+
+    delay(100);
+
+    payload = "";
+
+    payload += let;
+    payload += " ";
+    payload += String(posA);
+    payload += " ";
+    payload += String(posB);
+    payload += '\r';
+
+    Serial2.print(payload);
+
+  }
+  else if (let == 'g') {
+    char LET = 'G';
+
+    payload += LET;
+    payload += " ";
+    payload += String(vel);
+    payload += '\r';
+
+    Serial2.print(payload);
+
+    delay(100);
+
+    payload = "";
+
+    payload += let;
+    payload += " ";
+    payload += String(posA);
+    payload += " ";
+    payload += String(posB);
+    payload += " ";
+    payload += String(posC);
+    payload += '\r';
+
+    Serial2.print(payload);
+  }
+
+  int maxx = 0;
+  if (abs(posA) >= abs(posB)) {
+    if (abs(posA) >= abs(posC)) {
+      maxx = abs(posA);
+    }
+    else {
+      maxx = abs(posC);
+    }
+  }
+  else {
+    if (abs(posB) >= abs(posC)) {
+      maxx = abs(posB);
+    }
+    else {
+      maxx = abs(posC);
+    }
+  }
+
+
+
+  return ((maxx * 100800 / 360) / vel) * 1000;
+
+
+}


FIXED the RGB declaration. The strip is in BGR order.

--- arduino/hellodotstar/hellodotstar.ino
+++ arduino/hellodotstar/hellodotstar.ino
@@ -7,18 +7,14 @@
 #define CLOCKPIN   MOSI
 #define NUMPIXELS 30 // Number of LEDs in strip

-#define red  0xFF0000
-#define green  0x00FF00
-#define blue  0x0000FF
+#define RED  0xFF0000
+#define GREEN  0x00FF00
+#define BLUE  0x0000FF

 uint32_t frame[NUMPIXELS];
+uint32_t colors[3] = {RED, GREEN, BLUE };

-
-uint32_t colors[3] = {green, red, blue };
-
-Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);
-
-
+Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BGR);

 void setup() {
   strip.begin(); // Initialize pins for output
@@ -26,10 +22,25 @@

   //initialize strip array
   for (int ii = 0; ii < NUMPIXELS; ii++) {
-    frame[ii] = 0xFF0000; //initialize all to red
+    frame[ii] = RED; //initialize all to red
     strip.setPixelColor(ii, frame[ii]);
   }
   strip.show();
+  delay(1000);
+  //initialize strip array
+  for (int ii = 0; ii < NUMPIXELS; ii++) {
+    frame[ii] = GREEN; //initialize all to GREEN
+    strip.setPixelColor(ii, frame[ii]);
+  }
+  strip.show();
+  delay(1000);
+  //initialize strip array
+  for (int ii = 0; ii < NUMPIXELS; ii++) {
+    frame[ii] = BLUE; //initialize all to BLUE
+    strip.setPixelColor(ii, frame[ii]);
+  }
+  strip.show();
+  delay(1000);

 }


Updated Arduino sketch so that it keeps track of the last command, which prevents repetitive calls (specifically for flash commands) from skipping blinks.

--- arduino/trafficLight/trafficLight.ino
+++ arduino/trafficLight/trafficLight.ino
@@ -11,6 +11,7 @@
 boolean flashingHigh;
 const unsigned long flashDuration = 750;
 unsigned long flashStartTime;
+String lastCommand;

 void setup() {
     Serial.begin(9600);
@@ -35,6 +36,13 @@
     if (Serial.available()) {

         String command = Serial.readStringUntil('$');
+
+        if (command == lastCommand) {
+            return;
+        }
+        else {
+            lastCommand = command;
+        }

         if (command == "light red") {
             lightPinExclusive(RED_PIN);


Add comments

Add comments

--- arduino_distance/arduino_distance.ino
+++ arduino_distance/arduino_distance.ino
@@ -1,15 +1,20 @@
 /* arduino_distance
- * Uses VL53L0X Time-of-Flight Lidar sensor for distance measurement
- * Stepper motor rotation
+ * Uses VL53L0X Time-of-Flight Lidar sensor for distance measurement. Hand crafted averaging for greater precision
+ * Stepper motor rotation. In progress.
  * Work in progress - Matthew Timmons-Brown
  */

+// Import I2C and sensor library
 #include <Wire.h>
 #include <VL53L0X.h>
+
+// Set a constant - number of trials before averaging
 #define average_trials 3

+// Initialise sensor
 VL53L0X sensor;

+// Setup loop
 void setup()
 {
   Serial.begin(9600);
@@ -21,10 +26,11 @@

 void loop()
 {
+  // Initiliase variables
   int avg;
-  int lidar_array[average_trials];
-  populate_lidar_array(lidar_array);
-  avg = average_lidar_array(lidar_array);
+  int lidar_array[average_trials]; // Create array
+  populate_lidar_array(lidar_array); // Pass array into populate_lidar_array function and fill with distance values
+  avg = average_lidar_array(lidar_array); // Average array values and store in avg variable
   Serial.print(avg);
   Serial.println();
 }
@@ -33,6 +39,7 @@
 {
   for (int i = 0; i < average_trials; i = i +1)
   {
+    // For each index of the array, get distance and store distance at that index
     lidar_array[i] = get_distance();
   }
 }
@@ -42,15 +49,17 @@
   int sum = 0;
   for (int i = 0; i < average_trials; i = i + 1)
   {
+    // Sum each value in the array
     sum += lidar_array[i];
   }
-  int result;
+  int result; // Work out mean average and return result
   result = ((float) sum) / average_trials;
   return result;
 }

 int get_distance()
 {
+  // Get distance in millimeters from lidar sensor
   return sensor.readRangeSingleMillimeters();
 }


Remove simpletimer

Remove simpletimer


Revert "Replace sleep function with asm"

This reverts commit c2221ec5542dd1f08528faa582d65f5138153568.


unipolar arduino

unipolar arduino

--- arduino/ch_13_uni_stepper/ch_13_uni_stepper.ino
+++ arduino/ch_13_uni_stepper/ch_13_uni_stepper.ino
@@ -1,9 +1,9 @@
 #include <Stepper.h>

-const int in1Pin = 9;
-const int in2Pin = 11;
-const int in3Pin = 8;
-const int in4Pin = 10;
+const int in1Pin = 2;
+const int in2Pin = 3;
+const int in3Pin = 4;
+const int in4Pin = 7;

 Stepper motor(513, in1Pin, in2Pin, in3Pin, in4Pin);


removed Arduino-specific constant from .ino

--- arduino/serial_control.ino
+++ arduino/serial_control.ino
@@ -125,7 +125,7 @@
   long result = (high<<8) | low;

   // calibrated scale constant for this Arduino (volt meter value / readVcc value)
-  float scale_constant = 1.1 * (4.881 / 4.854) * 1023 * 1000;
+  float scale_constant = 1.1 * 1023 * 1000;

   result = scale_constant / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
   return result; // Vcc in milivolts


릴레이 모듈 최종 완성 Signed-off-by: yoowonyoung <wonyoung0105@gmail.com>

릴레이 모듈 최종 완성
Signed-off-by: yoowonyoung <ad197563590a6860fa7b20962aa2162389840fd1@gmail.com>

--- Arduino/module_control+Wi_Fi/module_control/module_control.ino
+++ Arduino/module_control+Wi_Fi/module_control/module_control.ino
@@ -1,8 +1,9 @@
 #include <SoftwareSerial.h>

 SoftwareSerial softSerial(2, 3); // RX, TX
-String WSSID = "LEE JEONG HYU";
-String WPASS = "9220230s*";
+String WSSID = "raspie";
+String WPASS = "11111111";
+String res = "";
 bool r;
 int relay1 = 4;
 int relay2 = 5;
@@ -25,23 +26,30 @@
 }

 void loop() {
-  digitalWrite(relay2, HIGH);
-  digitalWrite(relay1, HIGH);
   r = espSendCommand( "AT+CIPSTART=\"TCP\",\"wy.iptime.org\",8099" , "OK" , 5000 );
   String getRequest = "GET /Test/Test HTTP/1.0\r\n";
   int getRequestLength = getRequest.length() + 2;
   r = espSendCommand( "AT+CIPSEND=" + String(getRequestLength) , "OK" , 5000 );
-  if(espSendCommand( getRequest , "ON" , 20000 )){
-     Serial.println("WTF");
-     digitalWrite(relay1, HIGH); // 릴레이를 작동
-
-     delay(1000); // 2초 대기
-     digitalWrite(relay1, LOW); // 없을 경우 릴레이를 끔
-
+  if(espSendCommand( getRequest , "HEATON" , 5000 )){
+     Serial.println("HEATON");
+     digitalWrite(relay2, LOW); // 릴레이 키기
   }else {
-     digitalWrite(relay2, HIGH); // 릴레이를 작동
-     delay(1000); // 2초 대기
-     digitalWrite(relay2, LOW); // 없을 경우 릴레이를 끔
+    int resLen = res.length();
+    String testFanON = res.substring(resLen - 14, resLen - 8);
+    String testFanOFF = res.substring(resLen - 15, resLen - 8);
+    String testHeatOFF = res.substring(resLen - 16, resLen - 8);
+    int isFanON = testFanON.equals("FANON\n");
+    int isFanOFF = testFanOFF.equals("FANOFF\n");
+    int isHeatOFF = testHeatOFF.equals("HEATOFF\n");
+    if(isFanON == 1) {
+      Serial.println("FANON");
+      digitalWrite(relay1, LOW); // 릴레이 킴
+    }else if(isFanOFF == 1) {
+      digitalWrite(relay1, HIGH); // 릴레이 끔
+    }else if(isHeatOFF == 1) {
+      digitalWrite(relay2, HIGH); // 릴레이 끔
+    }
+    res = "";
   }
   if ( !r ) {
     Serial.println( "Something wrong...Attempting reset...");
@@ -75,6 +83,7 @@
       if ( response.length() > 0 ) {
         Serial.println("espSendCommand: RESPONSE:");
         Serial.println( response );
+        res = response;
       } else {
         Serial.println("espSendCommand: NO RESPONSE");
       }


Update LCD display

Update LCD display

--- Arduino/coopController/coopController.ino
+++ Arduino/coopController/coopController.ino
@@ -266,10 +266,10 @@
 }

 void updateLCD() {
+  char tempStr[5];
   lcd.clear();
   lcd.setCursor(0,0);
-  lcd.print("T ");
-  lcd.print(tempF);
+  lcd.print(dtostrf(tempF, 5, 1, tempStr));
   lcd.print("F | L ");
   lcd.print(brightness);
   lcd.print("%");


added some serial functions

added some serial functions

--- control/sonar/ROV_sonar/ROV_sonar.ino
+++ control/sonar/ROV_sonar/ROV_sonar.ino
@@ -22,14 +22,14 @@

 int SetupPin = 6; //a pin tells arduino to setup Standard Signal
 int StandardInputPin = 5;
-int SignalFlagPin = 4;//when it is high start reading signals from 4 channels
+int sigSent = 0;//when true, signal was sent from ROV
 //from the top right corner, piezos are labeled as 0, 1, 2, 3 clock-wisely
 int SignalInput0 = 0;
 int SignalInput1 = 1;
 int SignalInput2 = 2;
 int SignalInput3 = 3;

-
+int serialWen = 7;
 //need pins to get temperature data

 float getTemp();
@@ -38,7 +38,17 @@
 		int Result[]);
 float angle(float time1, float time2, float d, float v);
 void maxIndex(int array[], int LengthX, int* MaxValue, int* Index);
+int serialListen();
+bool serialSend(float angle1, float angle2);

+
+int serialListen(){
+//waits for line to send command, either pingHappened or return angles
+}
+
+bool serialSend(float angle1, float angle2){
+//sends the angle data down the RS485 line
+}

 float getTemp()
 {
@@ -97,7 +107,8 @@
 	pinMode(SignalInput1, INPUT);
 	pinMode(SignalInput2, INPUT);
 	pinMode(SignalInput3, INPUT);
-	pinMode(SignalFlagPin, INPUT);
+
+	pinMode(serialWen,OUTPUT);

 }

@@ -110,14 +121,13 @@
 	int Signal3[SignalReadLength];
 	float Volocity;

+	sigSent = serialListen();
+
+	if (sigSent == 1) //is the SetupPin 'HIGH' cover the whole signal or just mark the start point?
+	{

-	float Temp = getTemp();
-	Volocity=1.402385*1000 + 5.038813*Temp - 5.799136/100*Temp*Temp + 3.287156/10000*Temp*Temp*Temp; //sound speed in water under atm pressure
-
-
-
-	if (digitalRead(SignalFlagPin) == HIGH) //is the SetupPin 'HIGH' cover the whole signal or just mark the start point?
-	{
+		float Temp = getTemp();
+		Volocity=1.402385*1000 + 5.038813*Temp - 5.799136/100*Temp*Temp + 3.287156/10000*Temp*Temp*Temp; //sound speed in water under atm pressure

 		for(int i=0; i<SignalReadLength; i++) //sampling rate need to be measured
 		{
@@ -163,9 +173,9 @@
 		     Index3 = Index3 - SignalSetupLength;
 		 */
 		Time0 = Index0 * TIMEGAP2;
-		Time1 = Index1 * TIMEGAP2 + TIMEGAP1;
-		Time2 = Index2 * TIMEGAP2 + 2 * TIMEGAP1;
-		Time3 = Index3 * TIMEGAP2 + 3 * TIMEGAP1;
+		Time1 = Index1 * TIMEGAP2;// + TIMEGAP1;
+		Time2 = Index2 * TIMEGAP2;//+ 2 * TIMEGAP1;
+		Time3 = Index3 * TIMEGAP2;// + 3 * TIMEGAP1;

 		//the original point is piezo2
 		float Angle2Y = angle(Time2, Time3, DPiezo, Volocity);
@@ -175,4 +185,9 @@
 		float Angle0Y = angle(Time1, Time0, DPiezo, Volocity);
 		float Angle0X = angle(Time0, Time3, DPiezo, Volocity);
 	}
+
+
+	if(sigSent == 2){
+		serialSend(Angle0X,Angle0Y);
+	}
 }


Working on motor code

Working on motor code

--- Arduino/test_moteur/test_moteur.ino
+++ Arduino/test_moteur/test_moteur.ino
@@ -24,6 +24,46 @@
  digitalWrite(pinI4,LOW);
  analogWrite(speedpinB,50);
 }
+
+void avance(int vitesse){
+  if (vitesse <0) {
+    digitalWrite(pinI1,HIGH);// DC motor rotates clockwise
+    digitalWrite(pinI2,LOW);
+    digitalWrite(pinI3,HIGH);// DC motor rotates clockwise
+    digitalWrite(pinI4,LOW);
+    analogWrite(speedpinA,abs(vitesse));
+    analogWrite(speedpinB,abs(vitesse));
+  }
+  else{
+    digitalWrite(pinI1,HIGH);// DC motor rotates clockwise
+    digitalWrite(pinI2,LOW);
+    digitalWrite(pinI3,HIGH);// DC motor rotates clockwise
+    digitalWrite(pinI4,LOW);
+    analogWrite(speedpinA,abs(vitesse));
+    analogWrite(speedpinB,abs(vitesse));
+  }
+}
+
+void rotate(int angle){
+  vitesse = 50;
+  if (vitesse <0) {
+    digitalWrite(pinI1,HIGH);// DC motor rotates clockwise
+    digitalWrite(pinI2,LOW);
+    digitalWrite(pinI3,LOW);// DC motor rotates clockwise
+    digitalWrite(pinI4,HIGH);
+    analogWrite(speedpinA,abs(vitesse));
+    analogWrite(speedpinB,abs(vitesse));
+  }
+  else{
+    digitalWrite(pinI1,LOW);// DC motor rotates clockwise
+    digitalWrite(pinI2,HIGH);
+    digitalWrite(pinI3,HIGH);// DC motor rotates clockwise
+    digitalWrite(pinI4,LOW);
+    analogWrite(speedpinA,abs(vitesse));
+    analogWrite(speedpinB,abs(vitesse));
+  }
+}
+
 void loop()
 {
  delay(2000);


added comment about led num

added comment about led num

--- ArduinoRF24-LED/ArduinoRF24-LED.ino
+++ ArduinoRF24-LED/ArduinoRF24-LED.ino
@@ -23,6 +23,9 @@
 #define THIS_ARD_WRITE_PIPE ARD2_TO_ARD1
 #define THIS_ARD_READ_PIPE  ARD1_TO_ARD2

+//tohle by asi uplne nemelo bejt vic nez 4
+//protoze pak se to nevejde do ty zpravy
+//by se muselo pak delat jako bitovej vektor
 #define LED_NUM 4

 RF24 radio(7,8);
@@ -148,10 +151,10 @@
                 write_buffer[0] = 0x00;
                 break;
             case 0x04:
-                write_buffer[9] = led_states[3];
-                write_buffer[8] = led_states[2];
-                write_buffer[7] = led_states[1];
-                write_buffer[6] = led_states[0];
+                for(int i = 0; i < LED_NUM; i++)
+                {
+                    write_buffer[(WRITE_BUFFER_SIZE - LED_NUM) + i] = led_states[i];
+                }
                 break;
             case 0x05:
                 led_num = read_buffer[9];


light stuff

light stuff

--- slave1/slave1.ino
+++ slave1/slave1.ino
@@ -172,37 +172,37 @@
 		// we're facing forwards
 		frontSum = slave1.lightArray.armFrontSum;
 		backSum  = slave1.lightArray.armBackSum;
-		rightSum = slave1.lightArray.armFrontSum;
-		leftSum  = slave1.lightArray.armBackSum;
+		rightSum = slave1.lightArray.armRightSum;
+		leftSum  = slave1.lightArray.armLeftSum;
 	}
 	else if (bearing > 45 && bearing <= 135){
 		// facing right
 		rightSum = slave1.lightArray.armFrontSum;
 		leftSum  = slave1.lightArray.armBackSum;
-		backSum  = slave1.lightArray.armFrontSum;
-		frontSum = slave1.lightArray.armBackSum;
+		backSum  = slave1.lightArray.armRightSum;
+		frontSum = slave1.lightArray.armLeftSum;
 	}
 	else if (bearing < -45  && bearing >= -135){
 		// facing left
 		leftSum = slave1.lightArray.armFrontSum;
 		rightSum  = slave1.lightArray.armBackSum;
-		frontSum = slave1.lightArray.armFrontSum;
-		backSum  = slave1.lightArray.armBackSum;
+		frontSum = slave1.lightArray.armRightSum;
+		backSum  = slave1.lightArray.armLeftSum;
 	}
 	else{
 		// facing back
 		backSum   = slave1.lightArray.armFrontSum;
 		frontSum = slave1.lightArray.armBackSum;
-		leftSum   = slave1.lightArray.armFrontSum;
-		rightSum = slave1.lightArray.armBackSum;
-	}
-
-	if (frontSum) lightByte = lightByte | INDEX1;
-	if (backSum)  lightByte = lightByte | INDEX2;
-	if (rightSum) lightByte = lightByte | INDEX3;
-	if (leftSum)  lightByte = lightByte | INDEX4;
+		leftSum   = slave1.lightArray.armRightSum;
+		rightSum = slave1.lightArray.armLeftSum;
+	}
+
+	if (frontSum > 0){ lightByte = lightByte | INDEX1; Serial.print('f');  }
+	if (backSum > 0){  lightByte = lightByte | INDEX2; Serial.print('b');  }
+	if (rightSum > 0){ lightByte = lightByte | INDEX3; Serial.print('r');  }
+	if (leftSum > 0){  lightByte = lightByte | INDEX4; Serial.print('l');}
+	Serial.println();

-	Serial.println(lightByte, BIN);
 	switch (lightByte){
 		case 0: /*nothing*/
 			break;
@@ -254,6 +254,8 @@
 	}
 }
 extern "C" int main(void){
+	CORE_PIN33_CONFIG = 0;  // completely disables the pin
+
 	Serial.begin(115200);
 	pinMode(LED, OUTPUT);

@@ -311,8 +313,9 @@
 		slave1.lightArray.read();
 		slave1.lightArray.getColours();
 		// Serial.println();
-		PRINTARRAY(slave1.lightArray.lightData);
-		PRINTARRAY(slave1.lightArray.colours);
+
+
+

 		uint8_t command = slave1.checkIfRequested();

@@ -331,6 +334,30 @@
 	    		case SLAVE1_COMMANDS::CALIB_MAG:
 	    			calibMagRequest(); // note that for this command another END_CALIB_MAG command must be sent to finish
 	    			break;
+	    		case SLAVE1_COMMANDS::CALIB_GREEN:
+	    			slave1.lightArray.calibGreen();
+	    			break;
+	    		case SLAVE1_COMMANDS::CALIB_WHITE:
+	    			slave1.lightArray.calibWhite();
+	    			break;
+	    		case SLAVE1_COMMANDS::END_CALIB_LIGHT:
+	    			slave1.lightArray.endCalib();
+	    			break;
+	    		case SLAVE1_COMMANDS::LIGHT_DATA:
+	    			slave1.sendPacket(slave1.lightArray.lightData, 16);
+	    			break;
+	    		case SLAVE1_COMMANDS::LIGHT_DATA_REFS:
+	    			slave1.sendPacket(slave1.lightArray.refData, 16);
+	    			break;
+	    		case SLAVE1_COMMANDS::LIGHT_DATA_COLOURS:
+	    			slave1.sendPacket(slave1.lightArray.colours, 16);
+	    			break;
+	    		case SLAVE1_COMMANDS::LIGHT_DATA_GREEN:
+	    			slave1.sendPacket(slave1.lightArray.green, 16);
+	    			break;
+	    		case SLAVE1_COMMANDS::LIGHT_DATA_WHITE:
+	    			slave1.sendPacket(slave1.lightArray.white, 16);
+	    			break;
 	    		case 255:
 	    			break;
 	    		default:
@@ -349,6 +376,15 @@
 			ledBlinkTime = 500;
 		}
 		if (ledElapsedTime > ledBlinkTime){
+			//lightCalcs();
+			// Serial.print(slave1.lightArray.armFrontSum); Serial.print('\t');
+			// Serial.print(slave1.lightArray.armBackSum); Serial.print('\t');
+			// Serial.print(slave1.lightArray.armRightSum); Serial.print('\t');
+			// Serial.print(slave1.lightArray.armLeftSum); Serial.println();
+			//Serial.println(lightByte, BIN);
+
+			PRINTARRAY(slave1.lightArray.lightData);
+			PRINTARRAY(slave1.lightArray.colours);
 			if (ledState){
 				digitalWriteFast(LED, HIGH);
 			}


Accepting @jcw's changes?

Accepting @jcw's changes?

--- examples/RF12/RF12demo/RF12demo.ino
+++ examples/RF12/RF12demo/RF12demo.ino
@@ -10,17 +10,16 @@
 #include <avr/pgmspace.h>
 #include <util/parity.h>

-#define DEBUG 1
-
+#define debug
 // ATtiny's only support outbound serial @ 38400 baud, and no DataFlash logging

 #if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny44__)
 #define SERIAL_BAUD 38400
+#define JNMicro
 #else
 #define SERIAL_BAUD 57600

-// Enabling dataflash code may cause problems with non-JeeLink configurations
-#define DATAFLASH 0
+#define DATAFLASH 0          // Enabling flash for none flash equipped nodes causes odd problems - particularly non-Jee kit
 // check for presence of DataFlash memory on JeeLink
 #define FLASH_MBIT  16  // support for various dataflash sizes: 4/8/16 Mbit

@@ -67,7 +66,7 @@
 /// Useful url: http://blog.strobotics.com.au/2009/07/27/rfm12-tutorial-part-3a/
 // 4 bit
 #define QUIET   0x1      // quiet mode
-#define V10     0x2      // Indicates a version of RF12Demo after version 10.
+#define V10     0x2      // Indicates a version of RF12Demo up to version 10.
 // ----------------
 // 8 bit
 #define COLLECT 0x20     // collect mode, i.e. pass incoming without sending acks
@@ -87,11 +86,10 @@
 static RF12Config config;
 char revP = 94; // Symbol ^ to indicate direction of frequency offset
 static char cmd;
-static byte value, stack[RF12_MAXDATA+4], top, sendLen, dest, sticky, revF = 0;
+static byte value, stack[RF12_MAXDATA+4], top, sendLen, dest, sticky, revF = 0, low = 0xFF, high = 0;
 static byte testbuf[RF12_MAXDATA], testCounter, useHex;
-static byte band;
-
-void displayVersion(uint8_t newline );
+
+byte band;

 static void showNibble (byte nibble) {
   char c = '0' + (nibble & 0x0F);
@@ -665,7 +663,7 @@
     }
     Serial.print((int) value);
     Serial.println(c);
-
+    word crc = ~0;
     switch (c) {
       default:
         showHelp();
@@ -683,12 +681,16 @@
         if (value) {
          config.nodeId = (value << 6) + (config.nodeId & 0x3F);
          frequency = 1600;
+         high = 0;  // Reset DRSSI max/min
+         low  = 255;
          saveConfig();
         } else {
             showHelp();
         }
         break;
       case 'o': // Increment frequency within band
+          high = 0;  // Reset DRSSI max/min
+          low = 255;
           if (value == 255) {
             revF = !revF;
             revP = revP ^ 40;   // Flip the indicator
@@ -814,39 +816,36 @@
         if (value == 42) Serial.println("Backed Up");

         if (value == 123) {
-          const uint8_t *ee_shadow = RF12_EEPROM_ADDR + RF12_EEPROM_SIZE;
-          // Check CRC to be restored
-          word crc = ~0;
-          for (byte i = 0; i < RF12_EEPROM_SIZE; ++i)
-            crc = _crc16_update(crc, eeprom_read_byte(ee_shadow + i));
-          if (crc)
+          for (byte i = 0; i < RF12_EEPROM_SIZE; ++i) {     // Check CRC to be restored
+	        crc = _crc16_update(crc, eeprom_read_byte(RF12_EEPROM_ADDR + RF12_EEPROM_SIZE + i));
+          }
+          if (crc) {
             Serial.println("Bad CRC");
-          else {
-            for (byte i = 0; i < RF12_EEPROM_SIZE; ++i) {
-              byte b = eeprom_read_byte((ee_shadow) + i);
-              showNibble(b >> 4);
-              showNibble(b);
-              eeprom_write_byte((RF12_EEPROM_ADDR) + i, b);
-            }
+          } else {
+              for (byte i = 0; i < RF12_EEPROM_SIZE; ++i) {
+                byte b = eeprom_read_byte((RF12_EEPROM_ADDR + RF12_EEPROM_SIZE) + i);
+                showNibble(b >> 4);
+                showNibble(b);
+                eeprom_write_byte((RF12_EEPROM_ADDR) + i, b);
+              }
             Serial.println();
             Serial.println("Restored");
             }
-          if (rf12_config())
-            initialize();
-          else
-            Serial.println("Initialize failed");
-        }
-        break;
-#if DEBUG
+          if (rf12_config()) initialize(); else Serial.println("Initialize failed");
+          }
+        break;
+#if defined debug
       case 'n': // Clear eeprom
         if (value == 123) {
-          // Use to clear config eeprom then backup to clear backup eeprom
-          for (byte i = 0; i < (RF12_EEPROM_SIZE); ++i)
-            eeprom_write_byte(RF12_EEPROM_ADDR + i, 0xFF);
+          for (byte i = 0; i < (RF12_EEPROM_SIZE); ++i) {  // Use to clear config eeprom then backup to clear backup eeprom
+            byte b = 255;
+            eeprom_write_byte(RF12_EEPROM_ADDR + i, b);
+          }
           Serial.println("Cleared");
         }
         break;
-    } // End Switch
+/////////////////////
+      } // End Switch
 #endif
     value = top = 0;
     memset(stack, 0, sizeof stack);
@@ -884,15 +883,19 @@
   Serial.begin(SERIAL_BAUD);
   displayVersion(0);
   activityLed(0);
-
-  if (rf12_config())
-    initialize();
-  else {
+#if defined JNMicro2
+////////////////////////////////////////////////////////////////////////
+/// Need some code to power up the RFM12B on the new Jeenode Micro   ///
+////////////////////////////////////////////////////////////////////////
+
+#endif
+    if (rf12_config()) initialize();
+    else {
     config.nodeId = 0x41; // 433 MHz, node 1
     config.group = 0xD4;  // default group 212
     frequency = 1600;
-    config.flags = 0xC;   // Default flags, quiet off and non V10
-//  saveConfig();         // Don't save to eeprom until we have changes.
+    config.flags = 0xC;        // Default flags, quiet off and non V10
+//    saveConfig();            // Don't save to eeprom until we have changes.
   }

 #if DATAFLASH
@@ -903,14 +906,14 @@
 #endif
 }
 void initialize() {
-  config.nodeId = eeprom_read_byte(RF12_EEPROM_ADDR);
-  config.group = eeprom_read_byte(RF12_EEPROM_ADDR + 1);
-  frequency = eeprom_read_byte(RF12_EEPROM_ADDR + 2);
-  config.flags = frequency >> 4;               // Extract the flag nibble
-  if (config.flags & V10)                      // Is this a pre v11 eeprom
-    frequency = 1600;
-  else // Lose flag nibble to get frequency high order
-    frequency = ((frequency & 0x0F)  << 8) + (eeprom_read_byte(RF12_EEPROM_ADDR + 3));
+    config.nodeId = eeprom_read_byte(RF12_EEPROM_ADDR);
+    config.group = eeprom_read_byte(RF12_EEPROM_ADDR + 1);
+    frequency = eeprom_read_byte(RF12_EEPROM_ADDR + 2);
+    config.flags = frequency >> 4;               // Extract the flag nibble
+    if (config.flags & V10)                      // Is this a pre v11 eeprom
+      frequency = 1600;
+    else
+      frequency = ((frequency & 0x0F)  << 8) + (eeprom_read_byte(RF12_EEPROM_ADDR + 3));              // Loose flag nibble to get frequency high order
 }
 void loop() {
   if (Serial.available())
@@ -940,8 +943,21 @@
       if (!useHex)
         Serial.print(' ');
       showByte(rf12_data[i]);
+/// Build a string showing ascii interpretation of rf12_data, if not ascii print a "." just like an IBM core dump JOH
     }
-    Serial.println();
+/// Print string built above
+ //  Code from Thomas Lohmueller known on forum as @tht    //
+        byte drssi = rf12_getRSSI();
+ /////////////////////////////////////////////////////////
+    Serial.print(" (");
+    if (drssi > high) high = drssi;
+    if (drssi < low) low = drssi;
+    Serial.print(low, DEC);
+    Serial.print("-");
+    Serial.print(drssi, DEC);
+    Serial.print("-");
+    Serial.print(high, DEC);
+    Serial.println(")");

     if (rf12_crc == 0) {
       activityLed(1);


scrolling text direction

scrolling text direction

added an option to set the direction in which the text scrolls. set
scrollDirection to 0 for right to left or 1 for left to right

--- CountDownToGrad/CountDownToGrad.ino
+++ CountDownToGrad/CountDownToGrad.ino
@@ -2,12 +2,13 @@
 #include <SimpleTimer.h>

 //--- SETTINGS ---
-const String strTitle = "2016 GRADUATION";    // title - must be a multiple of 16 characters
+const String strTitle = "2016 GRADUATION www.antuple.net/projects/";    // title - must be a multiple of 16 characters
 const String strGrad = "CONGRATS GRADS!";     // timer done message - must be a multiple of 16 characters
 const int lcdPin = 2;                         // pin for LCD
+const int scrollDirection = 0;                // direction to scroll text in, 0 = right to left, 1 = left to right

 // time to count down from
-const int dMax = 74;                          // days
+const int dMax = 70;                          // days
 const int hMax = 0;                           // hours
 const int mMax = 0;                           // minutes
 const int sMax = 0;                           // seconds
@@ -41,20 +42,32 @@
   setupTime();                                            // setup time left
   delay(100);

-  // pad title string with 16 whitespaces in the front
+  // pad title string with 16 whitespaces
   int padding = strTitle.length() % 16;

-  // scroll left to right
+  // scroll title
   for (int i = 0; i < padding; i++) {
-     strTitleDisplay = " " + strTitleDisplay;
-  }
-
-  // pad title string with 16 whitespaces in the front
+     if (scrollDirection == 0) {
+       // scroll text right to left
+       strTitleDisplay = " " + strTitleDisplay;
+     } else if (scrollDirection == 1) {
+       // scroll text left to right
+       strTitleDisplay = strTitleDisplay + " ";
+     }
+  }
+
+  // pad graduation string with 16 whitespaces
   padding = strGrad.length() % 16;

-  // scroll left to right
+  // scroll timer done message
   for (int i = 0; i < padding; i++) {
-     strGradDisplay = " " + strGradDisplay;
+    if (scrollDirection == 0) {
+       // scroll text right to left
+       strGradDisplay = " " + strGradDisplay;
+     } else if (scrollDirection == 1) {
+       // scroll text left to right
+       strGradDisplay = strGradDisplay + " ";
+     }
   }
 }

@@ -108,47 +121,51 @@
 }

 void updateLCD() {
-  // scroll left to right
-  strTitleDisplay = strTitleDisplay.charAt(strTitleDisplay.length() - 1) + strTitleDisplay.substring(0, strTitleDisplay.length() - 1);
-
   if (bTimerDone) {
-    strGradDisplay = strGradDisplay.charAt(strGradDisplay.length() - 1) + strGradDisplay.substring(0, strGradDisplay.length() - 1);
-  }
-
-  // first line, display title
-  if (bTimerDone) {
-     mySerial.print(strGradDisplay);       // first line, display congrats
-     mySerial.write(148);                  // new line
-
-     int spaceCount = 16 - strTime.length() - 2;
-     String strSpace = "";
-     for (int i = 0; i < spaceCount; i++) {
-       strSpace += " ";
-     }
-
-     // format DD:HH:MM:SS
-     String strD = printDigits(0, true);
-     String strH = printDigits(0, true);
-     String strM = printDigits(0, true);
-     String strS = printDigits(0, false);
-     strTime = strD+strH+strM+strS;
-
-     // second line, display time and initials
-     strLine2 = strTime + strSpace + "PK";
-     mySerial.print(strLine2);
-     Serial.println("Time: " + strTime);   // console debug
+    if (scrollDirection == 0) {
+      // scroll text right to left
+      strGradDisplay = strGradDisplay.substring(1, strGradDisplay.length()) + strGradDisplay.charAt(0);
+    } else if (scrollDirection == 1) {
+      // scroll text left to right
+      strGradDisplay = strGradDisplay.charAt(strGradDisplay.length() - 1) + strGradDisplay.substring(0, strGradDisplay.length() - 1);
+    }
+
+    mySerial.print(strGradDisplay);       // first line, display congrats
+    mySerial.write(148);                  // new line
+
+    int spaceCount = 16 - strTime.length() - 2;
+    String strSpace = "";
+    for (int i = 0; i < spaceCount; i++) {
+      strSpace += " ";
+    }
+
+    // format time in DD:HH:MM:SS
+    strTime = formateClockTime(0, 0, 0, 0);
+
+    // second line, display time and initials
+    strLine2 = strTime + strSpace + "PK";
+    mySerial.print(strLine2);
+    Serial.println("Time: " + strTime);   // console debug
   } else {
-     mySerial.println(strTitleDisplay);
-     int spaceCount = 16 - strTime.length() - 2;
-     String strSpace = "";
-     for (int i = 0; i < spaceCount; i++) {
-       strSpace += " ";
-     }
-
-     // second line, display time and initials
-     strLine2 = strTime + strSpace + "PK";
-     mySerial.print(strLine2);
-     Serial.println("Time: " + strTime);   // console debug
+    if (scrollDirection == 0) {
+      // scroll text right to left
+      strTitleDisplay = strTitleDisplay.substring(1, strTitleDisplay.length()) + strTitleDisplay.charAt(0);
+    } else if (scrollDirection == 1) {
+      // scroll text left to right
+      strTitleDisplay = strTitleDisplay.charAt(strTitleDisplay.length() - 1) + strTitleDisplay.substring(0, strTitleDisplay.length() - 1);
+    }
+
+    mySerial.println(strTitleDisplay);
+    int spaceCount = 16 - strTime.length() - 2;
+    String strSpace = "";
+    for (int i = 0; i < spaceCount; i++) {
+      strSpace += " ";
+    }
+
+    // second line, display time and initials
+    strLine2 = strTime + strSpace + "PK";
+    mySerial.print(strLine2);
+    Serial.println("Time: " + strTime);   // console debug
   }
 }

@@ -169,7 +186,7 @@
   return formateClockTime(daysLeft, h, m, s);
 }

-// format DD:HH:MM:SS
+// format time in DD:HH:MM:SS
 String formateClockTime(int days, int hours, int minutes, int seconds) {
   return printDigits(days, true) + printDigits(hours, true) + printDigits(minutes, true) + printDigits(seconds, false);
 }