Fix for <>

Fix for <>

--- NerfKeyboardRemapper.ino
+++ NerfKeyboardRemapper.ino
@@ -2,9 +2,9 @@
 #include <usbhub.h>
 #include <LiquidCrystal.h>

-#define FORCE_SHIFT 0x80
-#define FORCE_ALTGR 0x40
-#define PURIFY 0x3F
+#define FORCE_SHIFT 0x100
+#define FORCE_ALTGR 0x200
+#define PURIFY 0xFF
 #define LETTERS_START 0x04
 #define LETTERS_END 0x1D
 #define LETTERS_CNT 26
@@ -20,18 +20,18 @@
 #define UNGRR 0xBF

-uint8_t invShift(uint8_t v) {
+uint16_t invShift(uint16_t v) {
   return v + FORCE_SHIFT;
 }
-uint8_t grr(uint8_t v){
+uint16_t grr(uint16_t v){
   return v + FORCE_ALTGR;
 }

-boolean isShifted(uint8_t v){
+boolean isShifted(uint16_t v){
   return (v & FORCE_SHIFT);
 }

-boolean isGrr(uint8_t v){
+boolean isGrr(uint16_t v){
   return (v & FORCE_ALTGR);
 }

@@ -40,12 +40,12 @@
 }

 LiquidCrystal lcd(2,3,4,5,6,7);
-uint8_t letters[LETTERS_CNT] = { 0x14, 0x1B, 0x0D, 0x08, invShift(0x36), 0x18, 0x0C, 0x07, 0x06, 0x0B, 0x17, 0x11, 0x33, 0x05, 0x15, 0x0F, 0x21, 0x13, 0x12, 0x1C, 0x0A, 0x0E, 0x10, 0x04, 0x09, 0x36};
-uint8_t shiftLetters[LETTERS_CNT] = { 0x14, 0x1B, 0x0D, 0x08, 0x64, 0x18, 0x0C, 0x07, 0x06, 0x0B, 0x17, 0x11, 0x33, 0x05, 0x15, 0x0F, invShift(0x20), 0x13, 0x12, 0x1C, 0x0A, 0x0E, invShift(0x64), 0x04, 0x09, invShift(0x37)};
-uint8_t numbers[NUMBERS_CNT] = {invShift(0x1E), invShift(0x1F), invShift(0x20), invShift(0x21), invShift(0x22), invShift(0x23), invShift(0x24), invShift(0x25), invShift(0x26), invShift(0x27)};
-uint8_t shiftNumbers[NUMBERS_CNT] = {invShift(0x38), grr(0x27), grr(0x20), invShift(0x30), 0x34, invShift(0x2F), invShift(0x1E), invShift(0x31), invShift(0x22), invShift(0x2D)};
-uint8_t specials[SPE_CNT] = {grr(0x22), grr(0x2D), invShift(0x37), 0x2E, grr(0x25), 0x32, 0x16, 0x23, grr(0x24), 0x1D, 0x19, 0x1A};
-uint8_t shiftSpecials[SPE_CNT] = {grr(0x21), grr(0x2E), 0x10, 0x2E, grr(0x23), 0x32, 0x16, invShift(0x25), grr(0x1F), 0x1D, 0x19, 0x1A};
+uint16_t letters[LETTERS_CNT] = { 0x14, 0x1B, 0x0D, 0x08, invShift(0x36), 0x18, 0x0C, 0x07, 0x06, 0x0B, 0x17, 0x11, 0x33, 0x05, 0x15, 0x0F, 0x21, 0x13, 0x12, 0x1C, 0x0A, 0x0E, 0x10, 0x04, 0x09, 0x36};
+uint16_t shiftLetters[LETTERS_CNT] = { 0x14, 0x1B, 0x0D, 0x08, 0x64, 0x18, 0x0C, 0x07, 0x06, 0x0B, 0x17, 0x11, 0x33, 0x05, 0x15, 0x0F, invShift(0x20), 0x13, 0x12, 0x1C, 0x0A, 0x0E, invShift(0x64), 0x04, 0x09, invShift(0x37)};
+uint16_t numbers[NUMBERS_CNT] = {invShift(0x1E), invShift(0x1F), invShift(0x20), invShift(0x21), invShift(0x22), invShift(0x23), invShift(0x24), invShift(0x25), invShift(0x26), invShift(0x27)};
+uint16_t shiftNumbers[NUMBERS_CNT] = {invShift(0x38), grr(0x27), grr(0x20), invShift(0x30), 0x34, invShift(0x2F), invShift(0x1E), invShift(0x31), invShift(0x22), invShift(0x2D)};
+uint16_t specials[SPE_CNT] = {grr(0x22), grr(0x2D), invShift(0x37), 0x2E, grr(0x25), 0x32, 0x16, 0x23, grr(0x24), 0x1D, 0x19, 0x1A};
+uint16_t shiftSpecials[SPE_CNT] = {grr(0x21), grr(0x2E), 0x10, 0x2E, grr(0x23), 0x32, 0x16, invShift(0x25), grr(0x1F), 0x1D, 0x19, 0x1A};

 void printOnScreen(uint8_t *buf,uint8_t line) {
   for(uint8_t i = 0; i < 8; i++) {
@@ -54,9 +54,9 @@
   }
 }

-void putKey(uint8_t *buf,uint8_t array[],uint8_t shiftArray[], uint8_t i, uint8_t start) {
+void putKey(uint8_t *buf,uint16_t array[],uint16_t shiftArray[], uint8_t i, uint8_t start) {
       if(buf[0] & 0x22) {
-        uint8_t t = shiftArray[buf[i]-start];
+        uint16_t t = shiftArray[buf[i]-start];
         buf[i] = purify(t);
         if(isGrr(t)) {
           buf[0] = buf[0] | GRR;
@@ -65,7 +65,7 @@
           buf[0] = buf[0] & UNSHIFT;
         }
       } else {
-        uint8_t t = array[buf[i]-start];
+        uint16_t t = array[buf[i]-start];
         buf[i] = purify(t);
         if(isGrr(t)) {
           buf[0] = buf[0] | GRR;


Working with MB control PCB

Working with MB control PCB

--- hardware/arduino/plex/plex.ino
+++ hardware/arduino/plex/plex.ino
@@ -1,35 +1,27 @@
-#include <SoftwareSerial.h>
-//Use software serial to receive keys from BT since USB is used to emulate keyboard.
-SoftwareSerial mySerial(14, 16); //RX, TX
+#include <Keyboard.h>
+
 //Status LED
 int ledPin = 9;
+int BT_EN = 14;
+int BT_STATE = 15;

 void setup() {
   //define LED as Output
   pinMode(ledPin, OUTPUT);
+  pinMode(BT_EN, OUTPUT);
+  pinMode(BT_STATE, INPUT);
+
+  digitalWrite(BT_EN, HIGH);

   //Init software serial with 9600baud rate
   //HC-05 works at 9600baud in data mode
   //HC-05 works at 38400 in AT mode
-  mySerial.begin(9600);
+  Serial1.begin(9600);
 //  mySerial.write("AT+NAMEPLX");
 }

 void loop() {
-//  sendText("itrollolol.com");
-//  delay(25);
-//  digitalWrite(ledPin, HIGH);
-//  delay(25);
-//  digitalWrite(ledPin, LOW);
-//https://support.plex.tv/hc/en-us/articles/201670487-Keyboard-Shortcuts
-//KEY_UP_ARROW	  0xDA	218
-//KEY_DOWN_ARROW	0xD9	217
-//KEY_LEFT_ARROW	0xD8	216
-//KEY_RIGHT_ARROW	0xD7	215
-//KEY_RETURN    	0xB0	176
-//KEY_ESC	        0xB1	177
-
-  if (mySerial.available()) {
-    Keyboard.write( mySerial.read() );
+  if (Serial1.available()) {
+    Keyboard.write( Serial1.read() );
   }
 }


Bug fixes after the test week in Croatia

--- DiveIno.ino
+++ DiveIno.ino
@@ -69,11 +69,13 @@

 byte safetyStopState = SAFETY_STOP_NOT_STARTED;

+unsigned long diveStartTimestamp;
 unsigned long diveDurationInSeconds;
 unsigned long safetyStopDurationInSeconds;
 unsigned long testPreviousDiveDurationInSeconds;

 SimpleTimer diveDurationTimer;
+float previousDepthInMeter;

 MAX17043 batteryMonitor;
 float batterySoc = 255;
@@ -157,8 +159,8 @@

 	tft.InitLCD();

-    // Set the function, which will be called in every second, if the timer is enabled
-	diveDurationTimer.setTimer(1000, diveUnderWater, diveDurationTimer.RUN_FOREVER);
+    // Set the function, which will be called in every 5th second, if the timer is enabled
+	diveDurationTimer.setTimer(5000, diveUnderWater, diveDurationTimer.RUN_FOREVER);
 	diveDurationTimer.disable(diveDurationTimer.RUN_FOREVER);

 	displayScreen(MENU_SCREEN);
@@ -336,6 +338,14 @@
 		depthInMeter = buhlmann.calculateDepthFromPressure(pressureInMillibar);
 	}

+	//Check for sensor error
+	if (abs(depthInMeter-previousDepthInMeter) > 20) {
+		//This is a sensor error - skip it!!!
+		return;
+	} else {
+		previousDepthInMeter = depthInMeter;
+	}
+
 	//Draw the data to the screen
 	view.drawCurrentTemperature(temperatureInCelsius);
 	view.drawCurrentPressure(pressureInMillibar);
@@ -345,24 +355,28 @@

 	switch (currentScreen) {
 		case GAUGE_SCREEN: {
+
+			view.drawDiveDuration(now()-diveStartTimestamp);
+
 			//Instead of dive information we will display the current time
 			view.drawCurrentTime(settings.getCurrentTimeText());
-
-			diveDurationInSeconds++;
-			view.drawDiveDuration(diveDurationInSeconds);
 		}
 		break;
 		case DIVE_SCREEN: {
-			//Progress with the dive, if we are deeper than 1.2 meter
 			if (pressureInMillibar > (seaLevelPressureSetting + 120) || diveDurationInSeconds > 60) {
-				diveDurationInSeconds++;
+
+				//Progress with the dive, if we are deeper than 1.2 meter
+				unsigned int intervalDuration = now()-diveStartTimestamp-diveDurationInSeconds;
+				calculateSafetyStop(maxDepthInMeter, depthInMeter, intervalDuration);
+
+				diveDurationInSeconds = diveDurationInSeconds + intervalDuration;
 				view.drawDiveDuration(diveDurationInSeconds);

-				//The timer fires in every second
-				calculateSafetyStop(maxDepthInMeter, depthInMeter, 1);
-
-				//Progress with the algorithm in every second
+				//Progress with the algorithm
 				diveProgress(temperatureInCelsius, pressureInMillibar, depthInMeter, diveDurationInSeconds);
+			} else {
+				//No dive progress - reset the dive timestamp
+				diveStartTimestamp = now();
 			}
 		}
 		break;
@@ -371,6 +385,10 @@

 void startDive()
 {
+	//Store the the current time as seconds since Jan 1 1970 at the start of the dive
+	diveStartTimestamp = now();
+	previousDepthInMeter = 0;
+
 	diveDurationTimer.enable(diveDurationTimer.RUN_FOREVER);

 	//Set default values before the dive


renamed the public functions

renamed the public functions


Revert "Extreme PID values chilled"

Revert "Extreme PID values chilled"

This reverts commit a2ac3c59975fdf41813c3cb0f8170cf9cc2396f9.

--- Firmware/R2-Quadcopter/PID.ino
+++ Firmware/R2-Quadcopter/PID.ino
@@ -3,34 +3,18 @@
   // Executer le PID et en tirer le resultat
   if (!auto_stabilisation_mode) {
     pid_roll_out = ROLL_PID_KP * roll_error + ROLL_PID_KI * Integral_roll_error * dt + ROLL_PID_KD * Derivative_roll_error / dt;
-    if(pid_roll_out > ROLL_PID_MAX)pid_roll_out = ROLL_PID_MAX;
-    else if(pid_roll_out < ROLL_PID_MIN)pid_roll_out = ROLL_PID_MIN;
-
     pid_pitch_out = PITCH_PID_KP * pitch_error + PITCH_PID_KI * Integral_pitch_error * dt + PITCH_PID_KD * Derivative_pitch_error / dt;
-    if(pid_pitch_out > PITCH_PID_MAX)pid_pitch_out = PITCH_PID_MAX;
-    else if(pid_pitch_out < PITCH_PID_MIN)pid_pitch_out = PITCH_PID_MIN;
-
     pid_yaw_out = YAW_PID_KP * yaw_error + YAW_PID_KI * Integral_yaw_error * dt + YAW_PID_KD * Derivative_yaw_error / dt;
-    if(pid_yaw_out > YAW_PID_MAX)pid_yaw_out = YAW_PID_MAX;
-    else if(pid_yaw_out < YAW_PID_MIN)pid_yaw_out = YAW_PID_MIN;
-
+
     pid_setpoint_update();
     pid_errors_update();
     pid_calculate_Int_and_Der();
   }
   else if (auto_stabilisation_mode) {
     pid_roll_out = ROLL_PID_KP * AS_roll_error + ROLL_PID_KI * AS_Integral_roll_error * dt + ROLL_PID_KD * AS_Derivative_roll_error / dt;
-    if(pid_roll_out > ROLL_PID_MAX)pid_roll_out = ROLL_PID_MAX;
-    else if(pid_roll_out < ROLL_PID_MIN)pid_roll_out = ROLL_PID_MIN;
-
     pid_pitch_out = PITCH_PID_KP * AS_pitch_error + PITCH_PID_KI * AS_Integral_pitch_error * dt + PITCH_PID_KD * AS_Derivative_pitch_error / dt;
-    if(pid_pitch_out > PITCH_PID_MAX)pid_pitch_out = PITCH_PID_MAX;
-    else if(pid_pitch_out < PITCH_PID_MIN)pid_pitch_out = PITCH_PID_MIN;
+    pid_yaw_out = YAW_PID_KP * yaw_error + YAW_PID_KI * Integral_yaw_error * dt + YAW_PID_KD * Derivative_yaw_error / dt;//On laisse le yaw comme avant car il ne doit pas etre affecté pas l'auto_dajust

-    pid_yaw_out = YAW_PID_KP * yaw_error + YAW_PID_KI * Integral_yaw_error * dt + YAW_PID_KD * Derivative_yaw_error / dt;//On laisse le yaw comme avant car il ne doit pas etre affecté pas l'auto_dajust
-    if(pid_yaw_out > YAW_PID_MAX)pid_yaw_out = YAW_PID_MAX;
-    else if(pid_yaw_out < YAW_PID_MIN)pid_yaw_out = YAW_PID_MIN;
-
     pid_setpoint_update();
     AS_errors_update();
     pid_calculate_AS_Int_and_Der();


Traffic jam at enqueByte

Traffic jam at enqueByte

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

--- zimodem/serout.ino
+++ zimodem/serout.ino
@@ -132,7 +132,7 @@
       if(rtsActive == HIGH)
         invertMask = invertMask | UART_INVERSE_RTS;
     }
-    debugPrintf("invert = %d magic values = %d %d, RTS_HIGH=%d, RTS_LOW=%d HIGHHIGH=%d LOWLOW=%d\n",invertMask,ctsActive,rtsActive, DEFAULT_RTS_HIGH, DEFAULT_RTS_LOW, HIGH, LOW);
+    //debugPrintf("invert = %d magic values = %d %d, RTS_HIGH=%d, RTS_LOW=%d HIGHHIGH=%d LOWLOW=%d\n",invertMask,ctsActive,rtsActive, DEFAULT_RTS_HIGH, DEFAULT_RTS_LOW, HIGH, LOW);
     if(invertMask != 0)
       uart_set_line_inverse(UART_NUM_2, invertMask);
     const int CUTOFF = 5;
@@ -172,13 +172,11 @@
   switch(flowControlType)
   {
   case FCT_RTSCTS:
-#ifndef ZIMODEM_ESP32
     if(pinSupport[pinCTS])
     {
       //debugPrintf("CTS: pin %d (%d == %d)\n",pinCTS,digitalRead(pinCTS),ctsActive);
       return (digitalRead(pinCTS) == ctsActive);
     }
-#endif
     return true;
   case FCT_NORMAL:
   case FCT_AUTOOFF:
@@ -194,13 +192,14 @@

 bool ZSerial::isSerialCancelled()
 {
-#ifndef ZIMODEM_ESP32
   if(flowControlType == FCT_RTSCTS)
   {
     if(pinSupport[pinCTS])
+    {
+      //debugPrintf("CTS: pin %d (%d == %d)\n",pinCTS,digitalRead(pinCTS),ctsActive);
       return (digitalRead(pinCTS) == ctsInactive);
-  }
-#endif
+    }
+  }
   return false;
 }

@@ -244,6 +243,16 @@
       break;
     }
   }
+  // the car jam of blocked bytes stops HERE
+  //debugPrintf("%d\n",serialOutBufferBytesRemaining());
+  while(serialOutBufferBytesRemaining()<1)
+  {
+    if(!isSerialOut())
+      delay(1);
+    else
+      serialOutDeque();
+    yield();
+  }
   enqueSerialOut(c);
 }


added comments 	modified:   mcu_main/mcu_main.ino

--- mcu_main/mcu_main.ino
+++ mcu_main/mcu_main.ino
@@ -216,6 +216,7 @@
     delayMicroseconds(period - duty);
 }

+//!  @brief  :  operate the built-in led i.e. pin 13
 void indicate(boolean running)
 {
     digitalWrite(indicator, running);


Successfully using a DHT22 with an Adafruit example using the following libraries: Adafruit_DHT_Unified Adafruit_Unified_Sensor DHT_sensor_library

--- moisture/moisture.ino
+++ moisture/moisture.ino
@@ -1,9 +1,79 @@
+// Depends on the following Arduino libraries:
+// - Adafruit Unified Sensor Library: https://github.com/adafruit/Adafruit_Sensor
+// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
+
+#include <Adafruit_Sensor.h>
+#include <DHT.h>
+#include <DHT_U.h>
+
+#define DHTPIN            2         // Pin which is connected to the DHT sensor.
+
+// Uncomment the type of sensor in use:
+//#define DHTTYPE           DHT11     // DHT 11
+#define DHTTYPE           DHT22     // DHT 22 (AM2302)
+//#define DHTTYPE           DHT21     // DHT 21 (AM2301)
+
+// See guide for details on sensor wiring and usage:
+//   https://learn.adafruit.com/dht/overview
+
+DHT_Unified dht(DHTPIN, DHTTYPE);
+
+uint32_t delayMS;
+
 void setup() {
-  // put your setup code here, to run once:
-
+  Serial.begin(9600);
+  // Initialize device.
+  dht.begin();
+  Serial.println("DHTxx Unified Sensor Example");
+  // Print temperature sensor details.
+  sensor_t sensor;
+  dht.temperature().getSensor(&sensor);
+  Serial.println("------------------------------------");
+  Serial.println("Temperature");
+  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
+  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
+  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
+  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" *C");
+  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" *C");
+  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" *C");
+  Serial.println("------------------------------------");
+  // Print humidity sensor details.
+  dht.humidity().getSensor(&sensor);
+  Serial.println("------------------------------------");
+  Serial.println("Humidity");
+  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
+  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
+  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
+  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println("%");
+  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println("%");
+  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println("%");
+  Serial.println("------------------------------------");
+  // Set delay between sensor readings based on sensor details.
+  delayMS = sensor.min_delay / 1000;
 }

 void loop() {
-  // put your main code here, to run repeatedly:
-
+  // Delay between measurements.
+  delay(delayMS);
+  // Get temperature event and print its value.
+  sensors_event_t event;
+  dht.temperature().getEvent(&event);
+  if (isnan(event.temperature)) {
+    Serial.println("Error reading temperature!");
+  }
+  else {
+    Serial.print("Temperature: ");
+    Serial.print(event.temperature);
+    Serial.println(" *C");
+  }
+  // Get humidity event and print its value.
+  dht.humidity().getEvent(&event);
+  if (isnan(event.relative_humidity)) {
+    Serial.println("Error reading humidity!");
+  }
+  else {
+    Serial.print("Humidity: ");
+    Serial.print(event.relative_humidity);
+    Serial.println("%");
+  }
 }


lots of little edits

lots of little edits

--- plantstation.ino
+++ plantstation.ino
@@ -59,6 +59,7 @@
 //===== For water level sensor ===================
 byte waterLevelPercent;
 const byte waterSensorPin = A3;
+const byte waterSensorPower = A14;
 int waterLevelVal;
 String waterLevelStatus = "OK";

@@ -92,6 +93,7 @@
   pinMode(lightSwitchPin, OUTPUT);
   pinMode(waterPumpPin, OUTPUT);
   pinMode(hygroPower, OUTPUT);
+  pinMode(waterSensorPower, OUTPUT);

   digitalWrite(waterPumpPin, LOW);

@@ -102,28 +104,34 @@
   while (!Console);
   Console.print("\nPlantStation is warming up.\nYun Console is warming up.\nKeen is warming up.\n\n");

-  // Because we need initial moisture readings
+  // Because we need initial moisture and water level readings
   digitalWrite(hygroPower, HIGH);
+  digitalWrite(waterSensorPower, HIGH);
   delay(5000);
   readMoistureSensor();
+  readWaterLevelSensor();
   digitalWrite(hygroPower, LOW);
+  digitalWrite(waterSensorPower, LOW);
   // Because end
+
+  readAirMeasurements();
+  readSoilMeasurements();
+  readLightResistor();
+
 }

 void loop() {
   unsigned long currentMillis = millis();
-
-  readAirMeasurements();
-  readSoilMeasurements();
-  readLightResistor();
-  readWaterLevelSensor();
-
-  outputEvent();

   // these happen every minute (or so)
   if (currentMillis - prevMinOneMillis > minOneInterval) {
     prevMinOneMillis = currentMillis;

+    readAirMeasurements();
+    readSoilMeasurements();
+    readLightResistor();
+
+    outputEvent();
     sendToKeen();
   }

@@ -132,6 +140,7 @@
     prevMinFiveMillis = currentMillis;

     readMoistureSensor();
+    readWaterLevelSensor();
     waterPlantStarts();
     switchLights();
   }
@@ -151,7 +160,7 @@
     prevWatering = millis();
     waterPumpIsOn = true;
     digitalWrite(waterPumpPin, HIGH);
-    Console.println("Watering started");
+    Console.println("\nWatering started\n");
   }
 }

@@ -159,51 +168,56 @@
     if (waterPumpIsOn && currentMillis >= prevWatering + wateringSeconds) {
     waterPumpIsOn = false;
     digitalWrite(waterPumpPin, LOW);
-    Console.println("Watering stopped");
+    Console.println("\nWatering stopped\n");
   } else if (waterPumpIsOn && moistureThreshold < moisturePercent) {
     waterPumpIsOn = false;
     digitalWrite(waterPumpPin, LOW);
-    Console.println("Watering stopped");
+    Console.println("\nWatering stopped\n");
   } else if (waterPumpIsOn && waterLevelStatus == "LOW") {
     waterPumpIsOn = false;
     digitalWrite(waterPumpPin, LOW);
-    Console.println("Watering stopped");
+    Console.println("\nWatering stopped\n");
   }
 }

 void switchLights() {
   if (lightOnThreshold > lightPercent && !lightIsOn) {
+    Console.println("\nArtificial lights on.\n");
     digitalWrite(lightSwitchPin, HIGH);
     lightIsOn = true;
   }
   if (lightOnThreshold < lightPercent && lightIsOn) {
+    Console.println("\nArtificial lights off.\n");
     digitalWrite(lightSwitchPin, LOW);
     lightIsOn = false;
   }
 }

 void readLightResistor() {
+  Console.println("\nReading light sensor.");
   lightResistorVal = analogRead(lightPin);
   lightPercent = map(lightResistorVal, lightMinVal, lightMaxVal, 0, 100);
+  Console.print("Light Percent: ");
+  Console.println(lightPercent);
 }

 void readMoistureSensor() {
+  Console.println("\nReading moisture sensor.");
   digitalWrite(hygroPower, HIGH);
   delay(1000); // nasty hack to wait for moisture drivers
   moistureSensorVal = analogRead(hygroPin);
   digitalWrite(hygroPower, LOW);
-  moisturePercent = map(moistureSensorVal, moistureMinVal, moistureMaxVal, 0, 100);
-
-  // Dry  0 - 300
-// Humid 300 - 700
-// Wet 700 - 950
-// moistureStatus
+  moisturePercent = reversemap(moistureSensorVal, moistureMinVal, moistureMaxVal, 0, 100);
+  Console.print("Moisture Percent: ");
+  Console.println(moisturePercent);
+
+  // moistureStatus
   if (moistureSensorVal > 0 && moistureSensorVal < 300) {
-    moistureStatus = "Dry";
+    moistureStatus = "Wet";
   } else if (moistureSensorVal >= 300 && moistureSensorVal < 700) {
     moistureStatus = "Humid";
   } else if (moistureSensorVal >= 700) {
-    moistureStatus = "Wet";
+    moistureStatus = "Dry";
   } else {
     moistureStatus = "ERR";
   }
@@ -211,17 +225,26 @@
 }

 void readWaterLevelSensor() {
+  Console.println("\nReading Water Level.");
+  digitalWrite(waterSensorPower, HIGH);
+  delay(1000); // nasty hack to wait for moisture drivers
   waterLevelVal = analogRead(waterSensorPin);
+  digitalWrite(waterSensorPower, LOW);
   waterLevelPercent = map(waterLevelVal, waterMinVal, waterMaxVal, 0, 100);
+  Console.print("Water Level Percent: ");
+  Console.println(waterLevelPercent);

   if (waterLevelPercent < waterLevelThreshold) {
    waterLevelStatus = "LOW";
   } else {
    waterLevelStatus = "OK";
   }
+  Console.print("Water level is: ");
+  Console.println(waterLevelStatus);
 }

 void readAirMeasurements() {
+  Console.println("\nReading air measurements.");
   am.humidityAir = myDHT.readHumidity();
   am.tempAirC = myDHT.readTemperature();
   am.tempAirF = myDHT.readTemperature(true);
@@ -230,9 +253,16 @@
   if (am.humidityAir == 0  && am.tempAirC == 0) {
     Console.println("Failed to read from DHT sensor.");
   }
+  Console.print("Air temp F is: ");
+  Console.println(am.tempAirF);
+  Console.print("Humidity is: ");
+  Console.println(am.humidityAir);
+  Console.print("Heat Index is: ");
+  Console.println(am.heatIndex);
 }

 void readSoilMeasurements() {
+  Console.println("\nReading soil measurements.");
   byte data[12];
   byte addr[8];

@@ -270,9 +300,13 @@
   float tempRead = ((MSB << 8) | LSB); //using two's compliment
   sm.tempSoilC = tempRead / 16;
   sm.tempSoilF = sm.tempSoilC*9/5+32;
+
+  Console.print("Soil temp F is: ");
+  Console.println(sm.tempSoilF);
 }

 void sendToKeen() {
+  Console.print("\nSending data to Keen.io.");
   String my_output = "{";
   // strings
   my_output += "\"AppId\":\"";                      my_output += appId;             my_output += "\"";
@@ -315,7 +349,7 @@
 }

 void outputEvent() {
-  String my_output = "";
+  String my_output = "\n";
   // strings
   //my_output += "AppId:";                        my_output += appId;
   //my_output += ";Location:";                    my_output += location;


no message

no message


Capture: also capture start is now interrupt-driven

--- Capture/Capture.ino
+++ Capture/Capture.ino
@@ -1,4 +1,5 @@
 int in = 3;
+int inInterrupt = 1;
 int debug = 4;

 static const int prescaler = 1;
@@ -19,6 +20,8 @@
 volatile int intrZeroes;
 unsigned char intrSamples[maxSampleBytes];

+volatile bool intrHasCapture = false;
+
 // the loop routine runs over and over again forever:
 void setup() {
   pinMode(debug, OUTPUT);
@@ -27,6 +30,12 @@
   setupTimer();
   Serial.begin(115200);
   Serial.println("Start");
+  enableCaptureInterrupt();
+}
+
+void enableCaptureInterrupt()
+{
+  attachInterrupt(inInterrupt, startCapture, FALLING);
 }

 void setupTimer()
@@ -45,7 +54,6 @@

 void enableTimer()
 {
-  noInterrupts();
   TIMSK1 |= (1 << TOIE1);
   intrReading = true;
   intrFirst = true;
@@ -54,7 +62,6 @@
   intrOnes = 0;
   intrZeroes = 0;
   intrSamples[0] = 0;
-  interrupts();
 }

 void disableTimer()
@@ -93,43 +100,42 @@
 #endif
 }

+void startCapture() {
+  enableTimer();
+  intrHasCapture = true;
+  detachInterrupt(inInterrupt);
+}
+
 void dump() {
-  enableTimer();
   while (intrReading) {
     // wait
   }
+  intrHasCapture = false;
   for (int c = 0; c < intrOnes; ++c) {
     if (intrAtBit-- == 0) {
       intrAtBit = 7;
       --intrAtByte;
     }
   }
-  for (int atByte = 0, atBit = 0;
-       atByte != intrAtByte || atBit != intrAtBit;
-       (++atBit == 8) ? (atBit = 0, ++atByte) : 0) {
-    if (atByte && atBit == 0) {
-      Serial.print(" ");
+  if (intrAtByte || intrAtBit) {
+    for (int atByte = 0, atBit = 0;
+         atByte != intrAtByte || atBit != intrAtBit;
+         (++atBit == 8) ? (atBit = 0, ++atByte) : 0) {
+      if (atByte && atBit == 0) {
+        Serial.print(" ");
+      }
+      Serial.print((intrSamples[atByte] & (1 << atBit)) ? '1' : '0');
     }
-    Serial.print((intrSamples[atByte] & (1 << atBit)) ? '1' : '0');
+    if (intrZeroes == 20) {
+      Serial.print("/*..*/");
+    }
+    Serial.println();
   }
-  if (intrZeroes == 20) {
-    Serial.print("/*..*/");
-  }
-  Serial.println();
+  enableCaptureInterrupt();
 }

 void loop() {
-  static bool started = false;
-  if (!started) {
-    int value = digitalRead(in);
-    if (value == HIGH) {
-      started = true;
-    }
-  } else {
-    int value = digitalRead(in);
-    if (value == LOW) {
-      dump();
-      started = false;
-    }
+  if (intrHasCapture) {
+    dump();
   }
 }


Added octal buttonVal's

Added octal buttonVal's

--- IR_Test/IR_Test.ino
+++ IR_Test/IR_Test.ino
@@ -81,66 +81,82 @@
     case 16769055:
       button="-";
       buttonId = 69005;
+      buttonVal = 206615;
       break;
     case 16754775:
       button="+";
       buttonId = 54775;
+      buttonVal = 152767;
       break;
     case 16748655:
       button="EQ";
       buttonId = 48655;
+      buttonVal = 137031;
       break;
     case 16738455:
       button="0";
       buttonId = 38455;
+      buttonVal = 113067;
       break;
     case 16750695:
       button="100+";
       buttonId = 50695;
+      buttonVal = 143007
       break;
     case 16756815:
       button="200+";
       buttonId = 56815;
+      buttonVal = 156757;
       break;
     case 16724175:
       button="1";
       buttonId = 24175;
+      buttonVal = 57157;
       break;
     case 16718055:
       button="2";
       buttonId = 18055;
+      buttonVal = 43207;
       break;
     case 16743045:
       button="3";
       buttonId = 43045;
+      buttonVal = 124045;
       break;
     case 16716015:
       button="4";
       buttonId = 16015;
+      buttonVal = 37217;
       break;
     case 16726215:
       button="5";
       buttonId = 26215;
+      buttonVal = 63147;
       break;
     case 16734885:
       button="6";
       buttonId = 34885;
+      buttonVal = 104105
       break;
     case 16728765:
       button="7";
       buttonId = 28765;
+      buttonVal = 70135;
       break;
     case 16730805:
       button="8";
       buttonId = 30805;
+      buttonVal = 74125;
       break;
     case 16732845:
       button="9";
       buttonId = 32845;
+      buttonVal = 100115;
       break;
     default:
       button="";
       buttonId = 0;
+      buttonVal = 0;
       break;
   }
 }
@@ -483,7 +499,7 @@

 void patternPicker(int x) {
   separate(x)
-  for (int i = 1; i < 6; i++) {
+  for (int i = 0; i < 6; i++) {
     if (nums[i] = 0) {
       p0();
     } else if (nums[i] = 1) {
@@ -518,7 +534,7 @@
   }
   delay(100); */
   if ((someNum % 1000) == 0){
-    if (buttonId != 0){
+    if (buttonVal != 0){
       Serial.println(button);
       Serial.println(buttonId);
       Serial.println(convertToOct(buttonId));


blackOnOpPollTimeOut dosen’t work with Madrix

--- BlackLED.ino
+++ BlackLED.ino
@@ -10,7 +10,7 @@
 //#define _use_FastLED  //for all types of chips but only 3 channel !!only LPD8806 implemented in code
 #define _use_octoWS2811 //for all WS2811 type chips

-#define blackOnOpPollTimeOut //recoment more than 20000 ms
+//#define blackOnOpPollTimeOut //recoment more than 20000 ms
 const static uint32_t OpPollTimeOut = 30000;

 //#define _MadMapper_sync_


enableReadTerminalCommands parameter added

--- si5351-beacon.ino
+++ si5351-beacon.ino
@@ -151,10 +151,12 @@
 #if defined(TIME_SLICE_GPS)
 HardwareSerial& gpsSerial = Serial1; // <--- Specify serial port for GPS NMEA module here
 TimeSliceGPS timeSlice(gpsSerial);
+const bool enableReadTerminalCommands = true; // Accept commands from terminal in GPS mode. Set to "false" if  GPS' UART is equal to Terminal's UART
 #endif

 #if defined(TIME_SLICE_DS3231)
 TimeSliceDS3231 timeSlice(pin1PPS);
+const bool enableReadTerminalCommands = true; // Accept commands from terminal in DS3231 mode. Should be always "true".
 #endif

@@ -232,6 +234,12 @@
   bandParams.setXTALFrequencyInKHz( xtalFrequencyInKHz );
   printBandInfo();

+  if( !enableReadTerminalCommands )
+  {
+    // Show notification to user.
+    Serial.println(F("Terminal commands disabled"));
+  }
+
 }

@@ -241,7 +249,7 @@
   //
   // command line interface
   //
-  if( Serial.available() )
+  if( enableReadTerminalCommands && Serial.available() )
   {
     int inByte = Serial.read();
     commandBuffer.handleInputChar( inByte );


Final Firmware?! Version 2.5

Final Firmware?! Version 2.5

Looks like a working build! Did minor tweaks to height mode

--- 00_Firmware/Firmware/Firmware.ino
+++ 00_Firmware/Firmware/Firmware.ino
@@ -8,7 +8,8 @@

 	TODO: BF - Height mode does not like LDR1 and LDR2 sensing different things -- should average them.
 	           Currently used as an "on screen" check.
-
+
+	v2.5 - JV - Minor tweaks to height mode
 	v2.4 - JV - Moved serial buffer updates to a seperate call, serial now updated regardless of mode.
 	v2.3 - JH - Fixes to serial RGB colour display.
 	v2.2 - JH - Motor driver accumulator. Known bug which does not let it drive to the extents.
@@ -89,7 +90,7 @@
 #define PULSE_STATE__ACTIVE_PULSE  1	// The sync-pulse check returned a pulse! It's probably on a screen.

 /** Sensor settings. */
-#define ON_SCREEN_TIMEIN 1000			// The amount of time before height mode accepts an on screen value. One second in ms.
+#define ON_SCREEN_TIMEIN 500			// The amount of time before height mode accepts an on screen value. One second in ms.
 const int LDR_MIN_LIMIT = 120;				// The smallest acceptable delta between the min and max values of the LDR.
 const int LDR_MAX_LIMIT = 1000;				// The largest acceptable delta between the min and max values of the LDR.
 #define LDR_OFFSCREEN_DELTA_GAP 100 	// The largest gap between the LDR values at which it is considered off-screen.
@@ -111,6 +112,7 @@
 //#define SERIAL_INFO			// Should device values be streamed via serial? csv: ms, ldr1, ldr2, rgb, height, frc, haspulse, swbot
 //#define SERIAL_SYNC_DEBUG		// Should sync pulse debug data be streamed via serial? csv: ms, r, g, b
 //#define SERIAL_SYNC_DEBUG2	// Should the verbose sync pulse debug data be streamed via serial? csv: ms, slope, max, r, g, b, min, raw
+//#define EMIT_MODES

 /** Colour modes - how the RGB LED is controlled. */
 #define RGBMODE_NONE     0		// The RGB LED displays nothing.
@@ -458,7 +460,7 @@
 	Serial.begin(115200);

 	// Wait two seconds.
-	Serial.println("Boot v2.3");
+	Serial.println("Boot v2.5");

 	// Select a default clip mode from the set of possible modes, if one is not set.
 	eClipMode = EEPROM.read(EEMODEADDR);
@@ -558,15 +560,21 @@
 		switch( eClipMode )
 		{
 			case EEMODE_HEIGHTONLY:
+				#ifdef EMIT_MODES
 				Serial.println( "HEIGHT" );
+				#endif
 				pRGB.setPixelColor(0,  255, 0, 0);
 				break;
 			case EEMODE_SYNCPULSE:
+				#ifdef EMIT_MODES
 				Serial.println( "SYNC" );
+				#endif
 				pRGB.setPixelColor(0,  0, 255, 0);
 				break;
 			case EEMODE_SERIAL:
+				#ifdef EMIT_MODES
 				Serial.println( "SERIAL" );
+				#endif
 				pRGB.setPixelColor(0,  0, 0, 255);
 				break;
 		}
@@ -826,6 +834,7 @@
  *   become more accurate.
  */
 void loopHeightMode() {
+	static WindowVariance * valueVariance = new WindowVariance(5);

 	// Determine historic variables for height sampling.
 	static uint16_t min = 99999;
@@ -845,12 +854,17 @@

 		// Compute the mean.
 		uint16_t iMean  = (iSample1 + iSample2) * 0.5;
+		valueVariance->push( iMean );

 		// Start this frame by assuming we are not on the screen.
 		bOnScreen = false;

 		// If the LDRs are sensing the same thing, we are probably on the screen.
-		boolean bDelta_Suggest = iDelta <= LDR_OFFSCREEN_DELTA_GAP;
+		#ifdef HEIGHT_DELTA_CHECK
+			boolean bDelta_Suggest = iDelta <= LDR_OFFSCREEN_DELTA_GAP;
+		#else
+			boolean bDelta_Suggest = true;
+		#endif
 		if (bDelta_Suggest)
 		{
 			// Update the ranges.
@@ -872,7 +886,7 @@
 				{
 					// Set the flag and update the motor height.
 					bOnScreen = true;
-					iTargetPos = constrain(map(iMean, min, max, 0, MOTOR_TRAVEL), 0, MOTOR_TRAVEL);
+					iTargetPos = constrain(map(valueVariance->mean(), min, max, 0, MOTOR_TRAVEL), 0, MOTOR_TRAVEL);
 				}
 				else
 				{
@@ -909,13 +923,13 @@
 		}

 		#ifdef HEIGHT_DEBUG // csv: on screen, ldr1, ldr2, min, max, value
-		Serial.print(bOnScreen ? 100 : 0); Serial.print(",");
+		/*Serial.print(bOnScreen ? 100 : 0); Serial.print(",");
 		Serial.print(iSample1); Serial.print(",");
 		Serial.print(iSample2); Serial.print(",");

 		Serial.print(min); Serial.print(",");
 		Serial.print(max); Serial.print(",");
-		Serial.print(iMean); Serial.print("\n");
+		Serial.print(iMean); Serial.print("\n");*/
 		#endif
 	}


Replace hardcoded values with #defines

Replace hardcoded values with #defines

--- Guzheng/Guzheng.ino
+++ Guzheng/Guzheng.ino
@@ -6,6 +6,14 @@

 // Some defines
 #define THRESHOLD 700
+#define VOLUME 0x7F
+#define LASTPORT 4
+#define DELAY 10
+
+// MIDI command defines
+#define NOTEON 0x90
+#define NOTEOFF 0x80
+#define CHANGEINSTRUMENT 0xC0

 // Values for different notes
 int note8 = 0x68;
@@ -26,7 +34,7 @@
   // Set instrument to trumpet
   // 0xC0 is the change instrument command
   // 0x39 is the instrument ID in hex
-  Serial.write(0xC0);
+  Serial.write(CHANGEINSTRUMENT);
   Serial.write(0x39);
 }

@@ -34,31 +42,31 @@
 void musicOn(int ID) {
   switch (ID) {
   case 1:
-    noteOn(0x90, note1, 0x7F);
+    noteOn(NOTEON, note1, VOLUME);
     break;
   case 2:
-    noteOn(0x90, note2, 0x7F);
+    noteOn(NOTEON, note2, VOLUME);
     break;
   case 3:
-    noteOn(0x90, note3, 0x7F);
+    noteOn(NOTEON, note3, VOLUME);
     break;
   case 4:
-    noteOn(0x90, note4, 0x7F);
+    noteOn(NOTEON, note4, VOLUME);
     break;
   case 5:
-    noteOn(0x90, note5, 0x7F);
+    noteOn(NOTEON, note5, VOLUME);
     break;
   case 6:
-    noteOn(0x90, note6, 0x7F);
+    noteOn(NOTEON, note6, VOLUME);
     break;
   case 7:
-    noteOn(0x90, note7, 0x7F);
+    noteOn(NOTEON, note7, VOLUME);
     break;
   case 8:
-    noteOn(0x90, note8, 0x7F);
+    noteOn(NOTEON, note8, VOLUME);
     break;
   default:
-    noteOn(0x80, note1, 0x00);
+    noteOn(NOTEOFF, note1, 0x00);
     break;
   }
 }
@@ -68,31 +76,31 @@
 void musicOff(int ID) {
   switch (ID) {
   case 1:
-    noteOn(0x80, note1, 0x7F);
+    noteOn(NOTEOFF, note1, 0x7F);
     break;
   case 2:
-    noteOn(0x80, note2, 0x7F);
+    noteOn(NOTEOFF, note2, 0x7F);
     break;
   case 3:
-    noteOn(0x80, note3, 0x7F);
+    noteOn(NOTEOFF, note3, 0x7F);
     break;
   case 4:
-    noteOn(0x80, note4, 0x7F);
+    noteOn(NOTEOFF, note4, 0x7F);
     break;
   case 5:
-    noteOn(0x80, note5, 0x7F);
+    noteOn(NOTEOFF, note5, 0x7F);
     break;
   case 6:
-    noteOn(0x80, note6, 0x7F);
+    noteOn(NOTEOFF, note6, 0x7F);
     break;
   case 7:
-    noteOn(0x80, note7, 0x7F);
+    noteOn(NOTEOFF, note7, 0x7F);
     break;
   case 8:
-    noteOn(0x80, note8, 0x7F);
+    noteOn(NOTEOFF, note8, 0x7F);
     break;
   default:
-    noteOn(0x80, note1, 0x00);
+    noteOn(NOTEOFF, note1, 0x00);
     break;
   }
 }
@@ -101,7 +109,7 @@
 {
   // Main loop
   // 5 ports, from 0 to 4
-  for (int i = 0; i < 5; i++) {
+  for (int i = 0; i <= LASTPORT; i++) {
     if(analogRead(i) > THRESHOLD) {
       // Beam has been cut
       // i+1 is because i is 0 indexed, but the ID starts with 1
@@ -111,7 +119,7 @@
       musicOff(i + 1);
     }
     // Delay 10 to prevent weird analog readings
-    delay(10);
+    delay(DELAY);
   }
 }


test long press button

test long press button

--- scripts-arduino/bp_led_lp.ino
+++ scripts-arduino/bp_led_lp.ino
@@ -38,8 +38,7 @@
     switch(eventResult){
         case EV_NONE:               // if nothing append
             //TODO : Ne rien faire de particulier, ou attendre la fin d'une synchronisation
-            event = EV_LONGPRESS;
-            Serial.println("waiting for signal...");
+
             break;
         case EV_SHORTPRESS:         // if short press
             //TODO : Allumer ou éteindre la LED (a check)
@@ -52,6 +51,7 @@
             break;
         case EV_LONGPRESS:          // if long press
             //TODO : Faire clignoter la LED et attendre la fin d'une synchronisation.
+
             break;
     }

@@ -70,6 +70,7 @@
         else{
             event = EV_LONGPRESS;
             Serial.println(CONST_ID+":"+CONST_TYPE+":4");
+
         }
     }
     else{
@@ -78,10 +79,9 @@

     if (button_now_pressed)
         ++button_pressed_counter;
-    else{
+    else
         button_pressed_counter = 0;
-    }
-
+
     button_was_pressed = button_now_pressed;
     return event;
 }


Fix bad function declaration

Fix bad function declaration

--- _2048no/_2048no.ino
+++ _2048no/_2048no.ino
@@ -250,7 +250,7 @@
 /**
  * Play a melody given in parameters
  */
-void playMelody(int* melody, int* duration, int melodySize) {
+void playMelody(const int* melody, const int* duration, const int melodySize) {
   int note, noteDuration, pauseBetweenNotes;

   for (note = 0; note < melodySize; note++) {


msgStorageLib: add MsgServer_GetSenderNameOf1stMessage()

--- esp8266_160221_msgStorageLib.ino
+++ esp8266_160221_msgStorageLib.ino
@@ -5,6 +5,8 @@
 #include "msgStorage.h"

 /*
+ * v0.12 2016 Mar. 4
+ *  - add MsgServer_GetSenderNameOf1stMessage()
  * v0.11 2016 Feb. 23
  *	- fix MsgServer_Save() > for s_messageCount==0, FileSys_commit() was necessary
  *  - fix MsgServer_Load() > assign to s_messageCount
@@ -119,6 +121,19 @@
 	return ""; // nothing to remove
 }

+String MsgServer_GetSenderNameOf1stMessage(String rcver)
+{
+  // Return [senderSerial] of the 1st message for the receiver
+  //
+
+  for(int idx = 0; idx < s_messageCount; idx++) {
+    if (s_messageList[idx].receiverName == rcver) {
+      return s_messageList[idx].senderName;
+    }
+  }
+  return ""; // nothing to remove
+}
+
 void MsgServer_Remove1stMessage(String rcver)
 {
 	// remove 1st message for the receiver
@@ -346,4 +361,4 @@

 	MsgServer_Load();
 	debug_outputDebugString("Test_MsgServer_SaveLoad", "Line331 > " + s_messageList[0].message);
-}+}


Update examples

Update examples

--- examples/RFID_UART/RFID_UART.ino
+++ examples/RFID_UART/RFID_UART.ino
@@ -6,19 +6,29 @@
 #define RFID_RX_PIN 10
 #define RFID_TX_PIN 11

-#ifdef 1
-	int DEBUG = 1;
-#endif
+// #define DEBUG
+#define TEST
+
 SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);
+RFIDdata tag;

 void setup() {
-	Serial.begin(9600);
-	Serial.println("Hello, 2bk!");
+	Serial.begin(57600);
+	Serial.println("Hello, double bk!");
 }

-void loop() {
+void loop() {
 	if(RFID.isAvailable()){
-	    RFID.cardNumber();
+		tag = RFID.data();
+		Serial.print("RFID card number: ");
+		Serial.println(RFID.cardNumber());
+#ifdef TEST
+	Serial.print("RFID raw data: ");
+	for(int i=0; i<tag.dataLen; i++){
+	    Serial.print(tag.raw[i], HEX);
+	    Serial.print('\t');
+		}
+#endif
 	}
 }


publish data via event; fine-tuning of sleep-wake interval

--- firmware/src/PoolBuddy.ino
+++ firmware/src/PoolBuddy.ino
@@ -11,7 +11,8 @@
 unsigned int MetricnextPublishTime;
 int nextSampleTime, nextSleepTime;
 int SAMPLE_INTERVAL = 2500;
-int SLEEP_INTERVAL = 60000;
+int SLEEP_INTERVAL = 60000 * 5;
+int WAKE_INTERVAL = 60000;

 double pH = 0;
 double ORP = 0;
@@ -34,7 +35,7 @@
   Particle.function("check",check_calibrated);
   Particle.function("slope",check_slope);

-  nextSleepTime = millis() + 30000 + SLEEP_INTERVAL;
+  nextSleepTime = millis() + WAKE_INTERVAL;
 }

 void loop() {
@@ -46,11 +47,16 @@
     soc = lipo.getSOC();
     }
   if(millis() > nextSleepTime) {
-    nextSleepTime = millis() + 30000 + SLEEP_INTERVAL;
+    Particle.publish("waterdata", water_data(), PRIVATE);
+    nextSleepTime = millis() + SLEEP_INTERVAL + WAKE_INTERVAL;
     executeRequest(PH_ADDRESS,"Sleep");
     executeRequest(ORP_ADDRESS,"Sleep");
-    System.sleep(SLEEP_MODE_DEEP,30);
+    System.sleep(SLEEP_MODE_DEEP,60*5);
   }
+}
+
+String water_data() {
+  return String::format("{temp:%f,ph:%f,orp:%f,soc:%f}",celsius,pH,ORP,soc);
 }

 void getPh() {


Add a bunch of logging, configuration, etc.

Something is wrong though. Sending data seems to hang pretty often but
I'm not sure why.

--- src/TempGauge/TempGauge.ino
+++ src/TempGauge/TempGauge.ino
@@ -4,7 +4,7 @@
 #include <Wire.h>
 #include <RTClib.h>
 #include <OneWire.h>
-#include <WiFiSettings.h>
+#include "WiFiSettings.h"

 // CC3000 configuration
 #define     ADAFRUIT_CC3000_IRQ    3    // MUST be an interrupt pin!
@@ -17,12 +17,10 @@
                                          ADAFRUIT_CC3000_VBAT,
                                          SPI_CLOCK_DIV2);

-// Wireless network configuration
-// Put WiFi Config Here
-
 // Other sketch configuration
-#define     READING_DELAY_SECS     10      // Number of minutes to wait between readings.
-#define     TIMEOUT_MS             15000  // How long to wait (in milliseconds) for a server connection to respond (for both AWS and NTP calls).
+#define     READING_DELAY_SECS     1      // Number of seconds to wait between readings.
+#define     TIMEOUT_MS             15000  // How long to wait (in milliseconds) for a server connection to respond
+#define     WEBSITE                "fremont"

 #define MAX_DS1820_SENSORS 1
 byte addr[8];
@@ -96,15 +94,17 @@
   // Note: If the sketch will run for more than ~24 hours, you probably want to query the time
   // server again to keep the current time from getting too skewed.
   unsigned long currentTime = lastPolledTime + (millis() - sketchTime);
-
-  if ((currentTime - lastReading) >= (READING_DELAY_SECS * 1000)) {
-    lastReading = currentTime;
-
-    float currentTemp = readTempF();
-    Serial.println(currentTemp);
-
-    dbWrite(currentTime, currentTemp);
-  }
+
+  Serial.print(F("Starting read. Current time: ")); Serial.println(currentTime);
+  lastReading = currentTime;
+
+  float currentTemp = readTempF();
+  Serial.print(F("Current temp: ")); Serial.println(currentTemp);
+
+  dbWrite(currentTime, currentTemp);
+
+  Serial.println(F("\n\rDone writing. Delay till next read.\n\r\n\r"));
+  delay(READING_DELAY_SECS * 1000);
 }

 float readTempF() {
@@ -128,7 +128,6 @@
   return ((data[1] << 8) + data[0]) * 0.0625;
 }

-// Write a temperature reading to the DynamoDB table.
 void dbWrite(unsigned long currentTime, float currentTemp) {
   // Generate time and date strings
   DateTime dt(currentTime);
@@ -136,10 +135,12 @@
   char dateTime[17];
   memset(dateTime, 0, 17);
   dateTime8601(dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute(), dt.second(), dateTime);
+
   // Set date to just the year month and day of the ISO8601 simple date string.
   char date[9];
   memset(date, 0, 9);
   memcpy(date, dateTime, 8);
+
   // Set currentTimeStr to the string value of the current unix time (seconds since epoch).
   char currentTimeStr[8*sizeof(unsigned long)+1];
   memset(currentTimeStr, 0, 8*sizeof(unsigned long)+1);
@@ -148,6 +149,7 @@
   // Generate string for the temperature reading.
   char temp[8*sizeof(unsigned long)+5];
   memset(temp, 0, 8*sizeof(unsigned long)+5);
+
   // Convert to fixed point string.  Using a proper float to string function
   // like dtostrf takes too much program memory (~1.5kb) to use in this sketch.
   ultoa((unsigned long) currentTemp, temp, 10);
@@ -157,23 +159,32 @@
   temp[n+2] = '0' + ((unsigned long) (currentTemp*100)) % 10;
   temp[n+3] = '0' + ((unsigned long) (currentTemp*1000)) % 10;

-  // Make request to DynamoDB API.
+  // Resolve server IP address
   uint32_t ip = 0;
+  Serial.print(WEBSITE); Serial.print(F(" I.P. address: "));
   while (ip == 0) {
-    if (!cc3000.getHostByName("fremont", &ip)) {
+    if (!cc3000.getHostByName(WEBSITE, &ip)) {
       Serial.println(F("Couldn't resolve!"));
     }
     delay(500);
   }
+  cc3000.printIPdotsRev(ip);
+
+  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
+  int replies = cc3000.ping(ip, 5);
+  Serial.print(replies); Serial.println(F(" replies"));
+
+  // Send request to Elasticsearch API
   Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 9200);
   if (www.connected()) {
-
+    Serial.println(F("Connected. Sending reading to Elasticsearch"));
     // Generate string with payload length for use in the signing and request sending.
     char payloadlen[8*sizeof(unsigned long)+1];
     memset(payloadlen, 0, 8*sizeof(unsigned long)+1);
     ultoa(20+strlen(currentTimeStr)+strlen(temp), payloadlen, 10);

     // HTTP Headers
+    Serial.print(F("Sending headers... "));
     www.fastrprint(F("POST /temp_gauge/reading HTTP/1.1\n"));
     www.fastrprint(F("Host: fremont:9200\n"));
     www.fastrprint(F("Content-Length: "));
@@ -181,13 +192,16 @@
     www.fastrprint(F("\n"));
     www.fastrprint(F("Content-Type: application/json\n"));
     www.fastrprint(F("\n"));
+    Serial.println("done.");

     // Payload
+    Serial.print(F("Sending body... "));
     www.fastrprint(F("{\"time\":")); // Length: 8
     www.fastrprint(currentTimeStr);
     www.fastrprint(F("000,\"temp\":")); // Length: 11
     www.fastrprint(temp);
     www.fastrprint(F("}")); // Length: 1
+    Serial.println(F("done."));
   } else {
     Serial.println(F("Connection failed"));
     www.close();
@@ -195,8 +209,8 @@
   }

   // Read data until either the connection is closed, or the idle timeout is reached.
-  Serial.println(F("Elasticsearch response:"));
   unsigned long lastRead = millis();
+  Serial.println(F("Elasticsearch response: "));
   while (www.connected() && (millis() - lastRead < TIMEOUT_MS)) {
     while (www.available()) {
       char c = www.read();


Add "raw raw raw" mode and fix some 8-bit-clean paths

--- firmware/teensytty/teensytty.ino
+++ firmware/teensytty/teensytty.ino
@@ -112,7 +112,8 @@

 // Uncomment this to ignore the hardware switches and use basic defaults
 #define IGNORE_THE_SWITCHES
-
+// And uncomment this to just be 'raw mode'
+//#define RAW_RAW_RAW

 #ifdef TESTING
 #define HWSERIAL Serial
@@ -143,7 +144,7 @@

 // You can tweak the baud rate very slightly here, but it's better to use 110 and
 // fix whatever timing/alignment issues in hardware
-#define BAUDRATE 111
+#define BAUDRATE 110

 // Macro to force a Teensy reset
 #define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C
@@ -252,7 +253,7 @@
   } else if (millisSinceActivity > SNOOZETIME) {
     // Stop the open-line chattering
     HWSERIAL.setBreak();
-  } else {
+  } else if(!isRx8BitClean) {
     // Keep the line open so timing errors are minimized
     sendToTTY(0);
   }
@@ -295,6 +296,18 @@
   isRx8BitClean  = !digitalRead(PIN_RX_8BITCLEAN);

 #ifdef IGNORE_THE_SWITCHES
+
+#ifdef RAW_RAW_RAW
+  isTestMode     = 0;
+  isTxUCLC       = 0;
+  isTxFoldSlash  = 0;
+  isTxUtf8Arrows = 0;
+  isTx8BitClean  = 1;
+  isRxNLCR       = 0;
+  isRxSpare1     = 0;
+  isRxDelays     = 0;
+  isRx8BitClean  = 1;
+#else
   isTestMode     = 0;
   isTxUCLC       = 1;
   isTxFoldSlash  = 0;
@@ -306,6 +319,8 @@
   isRx8BitClean  = 0;
 #endif

+#endif
+
 #ifdef DEBUG_ALL
   Serial.print("Tx 8-bit clean? ");  Serial.println(yesno(isTx8BitClean));
   if (!isTx8BitClean) {
@@ -339,7 +354,9 @@
   Serial.println(b, HEX);
 #endif

-  if (!isRx8BitClean) {
+  if (isRx8BitClean) {
+    sendToTTY(b);
+  } else {
     if (isRxNLCR) {
       // TODO linefeed conversion, LF => CR+LF
       if ((b == LF) && (prevUSBByte != CR)) {
@@ -425,7 +442,7 @@
   if (!isTx8BitClean) {
     // Processing

-    // Ryemove the parity bit
+    // Remove the parity bit
     b = b & 0x7F;
     c = b;

@@ -479,9 +496,13 @@

   prevTTYByte = b;

-  // Don't send nulls to the USB terminal
-  if (c != 0) {
+  if (isTx8BitClean) {
     sendToUSB(c);
+  } else {
+    // Don't send nulls to the USB terminal
+    if (c != 0) {
+      sendToUSB(c);
+    }
   }
   return c;
 }


Save brightness setting in EEPROM

Save brightness setting in EEPROM

--- Lee_Retirement/Lee_Retirement.ino
+++ Lee_Retirement/Lee_Retirement.ino
@@ -55,7 +55,6 @@

 #define BrightMax 255
 #define BrightMin 0
-int brightness_increment = -2;

 // read the buttons
 int read_LCD_buttons()
@@ -128,6 +127,7 @@
       if( brightness >= BrightMax ){
         brightness = BrightMax;
       }
+      EEPROM.update(ADDR_BRIGHTNESS, brightness);
       break;
     }
     case btnLEFT: {
@@ -136,6 +136,7 @@
       if( brightness <= BrightMin ){
         brightness = BrightMin;
       }
+      EEPROM.update(ADDR_BRIGHTNESS, brightness);
       break;
     }
     case btnUP: {
@@ -157,7 +158,7 @@
   }
   analogWrite(PinBacklight, brightness);

-  // assemble LCD line
+  // assemble first LCD line
   line1 = "";
   line1 = "ADC:" + String(adc_key_in);
   while( line1.length() < 16 - key.length() ){
@@ -168,7 +169,7 @@
   lcd.print(line1);

   // assemble second LCD line
-  line2 = "inc:" + String(brightness_increment);
+  line2 = "bright:" + String(brightness);
   secs = String(millis()/1000);
   if(RTC.read(tm)){
     secs = "ok!" + String(tm.Second);


WIP. cleanup

WIP. cleanup


Added temperature value to Blynk push notification.

- Prefixed cloud variables with corresponding cloud prefixes.

--- thermometer.ino
+++ thermometer.ino
@@ -37,7 +37,10 @@
 #include "blynk/blynk.h"
 #endif

-// Boot
+
+//-------------------------------------------------------------------------
+// Boot setup
+//-------------------------------------------------------------------------
 // STARTUP(WiFi.selectAntenna(ANT_EXTERNAL));
 STARTUP(WiFi.selectAntenna(ANT_INTERNAL));
 STARTUP(System.enableFeature(FEATURE_RETAINED_MEMORY));
@@ -45,10 +48,11 @@
 // SYSTEM_THREAD(DISABLED);
 // SYSTEM_MODE(AUTOMATIC);

+
 //-------------------------------------------------------------------------
 // Temperature sensing and publishing to Particle, ThinkSpeak, and Blynk
 //-------------------------------------------------------------------------
-#define SKETCH "THERMOMETER 1.1.0"
+#define SKETCH "THERMOMETER 1.2.0"
 #include "credentials.h"

@@ -65,6 +69,7 @@
 //-------------------------------------------------------------------------
 const unsigned int TIMEOUT_WATCHDOG = 10000;    // Watchdog timeout in milliseconds
 const unsigned int TIMEOUT_RECONNECT = 10000;   // Reconnection timeout in milliseconds
+

 //-------------------------------------------------------------------------
 // Measuring configuration
@@ -82,10 +87,10 @@
 const char* TEMP_STATUS[] = {"unknown", "Freeze", "Cold", "Lukewarm", "Normal", "Warm", "Hot"};

 // Statistical smoothing and exponential filtering
-const float FACTOR_RSSI = 0.1;    // Filtering factor for RSSI
-const float FACTOR_TEMP = 0.2;    // Filtering factor for temperature
-ExponentialFilter efRssi = ExponentialFilter(FACTOR_RSSI);
-ExponentialFilter efTemp = ExponentialFilter(FACTOR_TEMP);
+const float EXPFILTER_FACTOR_RSSI = 0.1;    // Filtering factor for RSSI
+const float EXPFILTER_FACTOR_TEMP = 0.2;    // Filtering factor for temperature
+ExponentialFilter efRssi = ExponentialFilter(EXPFILTER_FACTOR_RSSI);
+ExponentialFilter efTemp = ExponentialFilter(EXPFILTER_FACTOR_TEMP);
 SmoothSensorData smooth;

 // Measured values
@@ -96,7 +101,7 @@

 // Backup variables (long term statistics)
 retained int bootCount, bootTimeLast, bootRunPeriod, reconnects;
-retained float tempValueMin = 100.0, tempValueMax = -25.0;
+retained float tempValueMin = 150.0, tempValueMax = -50.0;

 //-------------------------------------------------------------------------
@@ -117,10 +122,10 @@
 #ifdef THINGSPEAK_CLOUD
 const unsigned int PERIOD_PUBLISH_THINGSPEAK = 60000;
 const char* THINGSPEAK_TOKEN = CREDENTIALS_THINGSPEAK_TOKEN;
-const unsigned long CHANNEL_NUMBER = CREDENTIALS_THINGSPEAK_CHANNEL;
-#define FIELD_RSSI_VALUE 1
-#define FIELD_TEMP_VALUE 2
-#define FIELD_TEMP_TREND 3
+const unsigned long THINGSPEAK_CHANNEL_NUMBER = CREDENTIALS_THINGSPEAK_CHANNEL;
+#define THINGSPEAK_FIELD_RSSI_VALUE 1
+#define THINGSPEAK_FIELD_TEMP_VALUE 2
+#define THINGSPEAK_FIELD_TEMP_TREND 3
 TCPClient ThingSpeakClient;
 int thingspeakResult;
 #endif
@@ -132,20 +137,19 @@
 #ifdef BLYNK_CLOUD
 const unsigned int PERIOD_PUBLISH_BLYNK = 30000;
 char BLYNK_TOKEN[] = CREDENTIALS_BLYNK_TOKEN;
-#define VPIN_BOOT_VALUE  V1
-#define VPIN_RSSI_VALUE  V2
-#define VPIN_LM35_VALUE  V3
-#define VPIN_LM35_TREND  V4
-#define VPIN_LM35_MIN    V5
-#define VPIN_LM35_MAX    V6
-#define VPIN_LM35_RESET  V7
-#define VPIN_LM35_LED1   V8
-#define VPIN_LM35_LED2   V9
-#define VPIN_DISCONNECT  V10
-#define VPIN_RECONNECTS  V11
+#define BLYNK_VPIN_BOOT_VALUE  V1
+#define BLYNK_VPIN_RSSI_VALUE  V2
+#define BLYNK_VPIN_LM35_VALUE  V3
+#define BLYNK_VPIN_LM35_TREND  V4
+#define BLYNK_VPIN_LM35_MIN    V5
+#define BLYNK_VPIN_LM35_MAX    V6
+#define BLYNK_VPIN_LM35_RESET  V7
+#define BLYNK_VPIN_LM35_LED1   V8
+#define BLYNK_VPIN_LM35_LED2   V9
+#define BLYNK_VPIN_RECONNECTS  V10
 #if defined(BLYNK_SIGNAL_TEMP)
-WidgetLED ledTempInc(VPIN_LM35_LED1);
-WidgetLED ledTempDec(VPIN_LM35_LED2);
+WidgetLED ledTempInc(BLYNK_VPIN_LM35_LED1);
+WidgetLED ledTempDec(BLYNK_VPIN_LM35_LED2);
 #endif
 #if defined(BLYNK_NOTIFY_TEMP)
 String BLYNK_LABEL_GLUE = String(" -- ");
@@ -416,25 +420,25 @@
         tsPublish = millis();
         bool isField = false;

-#ifdef FIELD_RSSI_VALUE
+#ifdef THINGSPEAK_FIELD_RSSI_VALUE
         isField = true;
-        ThingSpeak.setField(FIELD_RSSI_VALUE, (int)rssiValue);
-#endif
-
-#ifdef FIELD_TEMP_VALUE
+        ThingSpeak.setField(THINGSPEAK_FIELD_RSSI_VALUE, (int)rssiValue);
+#endif
+
+#ifdef THINGSPEAK_FIELD_TEMP_VALUE
         isField = true;
-        ThingSpeak.setField(FIELD_TEMP_VALUE, (float)tempValue);
-#endif
-
-#ifdef FIELD_TEMP_TREND
+        ThingSpeak.setField(THINGSPEAK_FIELD_TEMP_VALUE, (float)tempValue);
+#endif
+
+#ifdef THINGSPEAK_FIELD_TEMP_TREND
         isField = true;
-        ThingSpeak.setField(FIELD_TEMP_TREND, (float)tempTrend);
+        ThingSpeak.setField(THINGSPEAK_FIELD_TEMP_TREND, (float)tempTrend);
 #endif

         // Publish if there is something to
         if (isField)
         {
-            thingspeakResult = ThingSpeak.writeFields(CHANNEL_NUMBER, THINGSPEAK_TOKEN);
+            thingspeakResult = ThingSpeak.writeFields(THINGSPEAK_CHANNEL_NUMBER, THINGSPEAK_TOKEN);
         }
     }
 }
@@ -464,7 +468,7 @@
 #ifdef BLYNK_NOTIFY_TEMP
             if (tempStatus != tempStatusOld)
             {
-                Blynk.notify(BLYNK_LABEL_PREFIX + BLYNK_LABEL_GLUE + BLYNK_LABEL_TEMP + BLYNK_LABEL_GLUE + TEMP_STATUS[tempStatus]);
+                Blynk.notify(BLYNK_LABEL_PREFIX + BLYNK_LABEL_GLUE + BLYNK_LABEL_TEMP + BLYNK_LABEL_GLUE + TEMP_STATUS[tempStatus] + BLYNK_LABEL_GLUE + String::format("%4.1f C", tempValue));
                 tempStatusOld = tempStatus;
             }
 #endif
@@ -493,57 +497,57 @@
 #endif
 }

-#ifdef VPIN_BOOT_VALUE
-BLYNK_READ(VPIN_BOOT_VALUE)
-{
-    Blynk.virtualWrite(VPIN_BOOT_VALUE, bootCount);
-}
-#endif
-
-#ifdef VPIN_RSSI_VALUE
-BLYNK_READ(VPIN_RSSI_VALUE)
-{
-    Blynk.virtualWrite(VPIN_RSSI_VALUE, rssiValue);
-}
-#endif
-
-#ifdef VPIN_LM35_VALUE
-BLYNK_READ(VPIN_LM35_VALUE)
-{
-    Blynk.virtualWrite(VPIN_LM35_VALUE, String::format("%4.1f", tempValue));
-}
-#endif
-
-#ifdef VPIN_LM35_TREND
-BLYNK_READ(VPIN_LM35_TREND)
-{
-    Blynk.virtualWrite(VPIN_LM35_TREND, String::format("%5.3f", tempTrend));
-}
-#endif
-
-#ifdef VPIN_LM35_MIN
-BLYNK_READ(VPIN_LM35_MIN)
-{
-    Blynk.virtualWrite(VPIN_LM35_MIN, String::format("%4.1f", tempValueMin));
-}
-#endif
-
-#ifdef VPIN_LM35_MAX
-BLYNK_READ(VPIN_LM35_MAX)
-{
-    Blynk.virtualWrite(VPIN_LM35_MAX, String::format("%4.1f", tempValueMax));
-}
-#endif
-
-#ifdef VPIN_RECONNECTS
-BLYNK_READ(VPIN_RECONNECTS)
-{
-    Blynk.virtualWrite(VPIN_RECONNECTS, reconnects);
-}
-#endif
-
-#ifdef VPIN_LM35_RESET
-BLYNK_WRITE(VPIN_LM35_RESET)
+#ifdef BLYNK_VPIN_BOOT_VALUE
+BLYNK_READ(BLYNK_VPIN_BOOT_VALUE)
+{
+    Blynk.virtualWrite(BLYNK_VPIN_BOOT_VALUE, bootCount);
+}
+#endif
+
+#ifdef BLYNK_VPIN_RSSI_VALUE
+BLYNK_READ(BLYNK_VPIN_RSSI_VALUE)
+{
+    Blynk.virtualWrite(BLYNK_VPIN_RSSI_VALUE, rssiValue);
+}
+#endif
+
+#ifdef BLYNK_VPIN_LM35_VALUE
+BLYNK_READ(BLYNK_VPIN_LM35_VALUE)
+{
+    Blynk.virtualWrite(BLYNK_VPIN_LM35_VALUE, String::format("%4.1f", tempValue));
+}
+#endif
+
+#ifdef BLYNK_VPIN_LM35_TREND
+BLYNK_READ(BLYNK_VPIN_LM35_TREND)
+{
+    Blynk.virtualWrite(BLYNK_VPIN_LM35_TREND, String::format("%5.3f", tempTrend));
+}
+#endif
+
+#ifdef BLYNK_VPIN_LM35_MIN
+BLYNK_READ(BLYNK_VPIN_LM35_MIN)
+{
+    Blynk.virtualWrite(BLYNK_VPIN_LM35_MIN, String::format("%4.1f", tempValueMin));
+}
+#endif
+
+#ifdef BLYNK_VPIN_LM35_MAX
+BLYNK_READ(BLYNK_VPIN_LM35_MAX)
+{
+    Blynk.virtualWrite(BLYNK_VPIN_LM35_MAX, String::format("%4.1f", tempValueMax));
+}
+#endif
+
+#ifdef BLYNK_VPIN_RECONNECTS
+BLYNK_READ(BLYNK_VPIN_RECONNECTS)
+{
+    Blynk.virtualWrite(BLYNK_VPIN_RECONNECTS, reconnects);
+}
+#endif
+
+#ifdef BLYNK_VPIN_LM35_RESET
+BLYNK_WRITE(BLYNK_VPIN_LM35_RESET)
 {
     if (param.asInt() == HIGH)
     {
@@ -552,14 +556,4 @@
 }
 #endif

-#ifdef VPIN_DISCONNECT
-BLYNK_WRITE(VPIN_DISCONNECT)
-{
-    if (param.asInt() == HIGH)
-    {
-        Particle.disconnect();
-    }
-}
-#endif
-
-#endif
+#endif


Add wifi_station_set_hostname(HOSTNAME); to make

https://github.com/toblum/McLighting/issues/79

--- Arduino/McLighting/McLighting.ino
+++ Arduino/McLighting/McLighting.ino
@@ -177,6 +177,8 @@
   pinMode(BUILTIN_LED, OUTPUT);
   // start ticker with 0.5 because we start in AP mode and try to connect
   ticker.attach(0.5, tick);
+
+  wifi_station_set_hostname(const_cast<char*>(HOSTNAME));

   // ***************************************************************************
   // Setup: Neopixel


Refactored the main loop of the firmware.

--- firmware/2016/robot_firmware/robot_firmware.ino
+++ firmware/2016/robot_firmware/robot_firmware.ino
@@ -10,25 +10,23 @@
   IMUSetup();
 }

-void verifyPipe() {
-  if (isStartingPipe()) {
-    if (has_received_message)
-      setChannel();
-  }
+void sendMessageBackToCentral() {
+    int send_message[2];
+    getMessages(send_message);
+    send(send_message);
 }

 void loop() {
   has_received_message = receive();
-  verifyPipe();

-  int send_message[2];
-  getMessages(send_message);
-  send(send_message);
+  if (has_received_message){
+    if (isStartingPipe())
+      setChannel();
+    else {
+      sendMessageBackToCentral();
+    }
+  }

   delay(20);
-
-  move (100, "motorA");
-  move (-100,"motorB");
-
   has_received_message = false;
 }


Don't bother wrapping the script and version debug print in an IF.

--- Arduino/BlueCube/BlueCube.ino
+++ Arduino/BlueCube/BlueCube.ino
@@ -90,13 +90,10 @@
     waitCounter++;
   }

-  // Print Debug Info if a serial interface is present
-  if (Serial)
-  {
-    Serial.print("BlueCube v");
-    Serial.println(SCRIPT_VERSION);
-  }
-
+  // Print script name and version
+  Serial.print("BlueCube v");
+  Serial.println(SCRIPT_VERSION);
+
   // Tell the cube library that the function 'userFunctionHandler' should be
   // called if the user uses the 'user ### colour;' serial command line
   // instruction


Adjusted mid speed

Adjusted mid speed

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -144,7 +144,7 @@
 int getMarkovSpeed(int oldSpeed){
   int probability = random(101);
   int lowVal = 2;
-  int midVal = 7;
+  int midVal = 5;
   int hiVal = 10;

   if(oldSpeed == lowVal){


Fixed binary charsets in exemples

Fixed binary charsets in exemples


Changed for Murano ADC Update.

Changed for Murano ADC Update.

--- examples/Murano-SmartLightBulb-ThingDevBoard/Murano-SmartLightBulb-ThingDevBoard.ino
+++ examples/Murano-SmartLightBulb-ThingDevBoard/Murano-SmartLightBulb-ThingDevBoard.ino
@@ -38,14 +38,14 @@
 #define TEMPUNIT "F" //Change to "C" for Celsius

 /*==============================================================================
-* WIFI Configuration Variables - Change these variables to your own settings.
-*=============================================================================*/
+ * WIFI Configuration Variables - Change these variables to your own settings.
+ *=============================================================================*/
 const char ssid[]     = "<YOUR_SSID_HERE>";
 const char password[] = "<YOUR_WIFI_PASSWORD_HERE>";

 /*==============================================================================
-* EXOSITE MURANO Configuration Variables - Change these variables to your own settings.
-*=============================================================================*/
+ * EXOSITE MURANO Configuration Variables - Change these variables to your own settings.
+ *=============================================================================*/
 #define productId "<MURANO_PRODUCT_ID_HERE>"

 const int REPORT_INTERVAL = 1000; //milliseconds period for reporting to Exosite.com
@@ -56,11 +56,12 @@
 String writeString = "temperature=";
 String writeString2 = "&uptime=";
 String writeString3 = "&humidity=";
+String writeString4 = "state=";
 String returnString;

 /*==============================================================================
-* End of Configuration Variables
-*=============================================================================*/
+ * End of Configuration Variables
+ *=============================================================================*/

 char macString[18];  // Used to store a formatted version of the MAC Address
 byte macData[WL_MAC_ADDR_LENGTH];
@@ -68,21 +69,23 @@
 long unsigned int prevSensorTime = 0;
 int exosite_comm_errors = 0;
 int comm_errors = 0;
+int s = 0;
+bool initial = true;

 WiFiClient client;
 Exosite exosite(&client);
 DHT dht(DHTPIN, DHTTYPE);

 /*==============================================================================
-* setup
-*
-* Arduino setup function.
-*=============================================================================*/
+ * setup
+ *
+ * Arduino setup function.
+ *=============================================================================*/
 void setup() {
   Serial.begin(112500);
   EEPROM.begin(40);
   exosite.begin();
-  exosite.setDomain(productId".m2.exosite.com");
+  exosite.setDomain(productId".devmode-m2.exosite.io");

   //SET UP IO PINS
   pinMode(LED_PIN, OUTPUT);
@@ -103,16 +106,16 @@
   Serial.println(macString);

   for (int c=0; c<8; c++) {
-     digitalWrite(LED_PIN, LOW);
-     delay(100);
-     digitalWrite(LED_PIN, HIGH);
-     delay(100);
+    digitalWrite(LED_PIN, LOW);
+    delay(100);
+    digitalWrite(LED_PIN, HIGH);
+    delay(100);
   }
   if (exosite.provision(productId, productId, macString)) {
-        Serial.println("setup: Provision Succeeded");
-        EEPROM.commit();
+    Serial.println("setup: Provision Succeeded");
+    EEPROM.commit();
   } else {
-        Serial.println("setup: Provision Check Done");
+    Serial.println("setup: Provision Check Done");
   }

   // Setup Sensor Interface
@@ -120,16 +123,23 @@

 }
 /*==============================================================================
-* loop
-*
-* Arduino loop function.
-*=============================================================================*/
+ * loop
+ *
+ * Arduino loop function.
+ *=============================================================================*/
 void loop()
 {
   int8_t index = 0;
   int8_t lastIndex = -1;
   float h,t;
-
+
+  // Set initial value for "state", lightbulb off (0)
+  if (initial)
+  {
+    exosite.writeRead(writeString4 + String(s), readString, returnString);
+    initial = false;
+  }
+
   if (prevSensorTime + SENSOR_INTERVAL < millis() || millis() < prevSensorTime)
   {
     h = dht.readHumidity();
@@ -162,53 +172,57 @@
   if (prevSendTime + REPORT_INTERVAL < millis() || millis() < prevSendTime || isnan(h) || isnan(t) ) {
     int uptime = millis()/1000;
     digitalWrite(LED_PIN, LOW);
-    if (exosite.writeRead(writeString +String(t) + writeString2 + String(uptime) + writeString3 + String(h), readString, returnString)) {
+    if (exosite.writeRead(writeString + String(t) + writeString2 + String(uptime) + writeString3 + String(h), readString, returnString)) {
       //Serial.println("Succeeded");
       exosite_comm_errors = 0;
       comm_errors = 0;
       prevSendTime = millis();
       //Handle Response Message
-      for(;;) {
-        index = returnString.indexOf("=", lastIndex+1);
-        if(index != 0) {
+      for (;;) {
+        index = returnString.indexOf("=", lastIndex + 1);
+        if (index != 0) {
           String alias = "";
-          String tempString = returnString.substring(lastIndex+1, index);
+          String tempString = returnString.substring(lastIndex + 1, index);
           Serial.print(F("exo: Dataport - "));
           Serial.print(tempString);
-          lastIndex = returnString.indexOf("&", index+1);
+          lastIndex = returnString.indexOf("&", index + 1);
           alias = tempString;
-          if(lastIndex != -1){
-            tempString = returnString.substring(index+1, lastIndex);
-          }else{
-            tempString = returnString.substring(index+1);
+          if (lastIndex != -1) {
+            tempString = returnString.substring(index + 1, lastIndex);
+          } else {
+            tempString = returnString.substring(index + 1);
           }
           Serial.print("=");
           Serial.print(tempString);
           Serial.print(" ->");

           //Handle response for pin D13 to control LED
-          if (alias == "state"){
-            if(tempString == "1"){
+          if (alias == "state") {
+            if (tempString == "1") {
+              s = 1;
               digitalWrite(LIGHTBULB_PIN, LOW);
               Serial.println("turn on Light");
-            }else if(tempString == "0"){
+              exosite.writeRead(writeString4 + String(s), readString, returnString);
+            } else if (tempString == "0") {
+              s = 0;
               digitalWrite(LIGHTBULB_PIN, HIGH);
               Serial.println("turn off Light");
-            }else{
+              exosite.writeRead(writeString4 + String(s), readString, returnString);
+            } else {
               Serial.print(F("Unknown Setting: "));
               Serial.println(tempString);
             }
-          } else if (alias == "msg"){
+          } else if (alias == "msg") {
             Serial.print("Message: ");
             Serial.println(tempString);
           } else {
             Serial.println("Unknown Alias Dataport");
           }

-          if(lastIndex == -1)
+          if (lastIndex == -1)
             break;

-        } else{
+        } else {
           Serial.println(F("No Index"));
           break;
         }
@@ -218,21 +232,21 @@
       //Serial.println("HANDLER: network or platform api request issue");
       exosite_comm_errors++;
       comm_errors++;
-      for (int c=0; c<4; c++) {
-         digitalWrite(LED_PIN, LOW);
-         delay(200);
-         digitalWrite(LED_PIN, HIGH);
-         delay(200);
+      for (int c = 0; c < 4; c++) {
+        digitalWrite(LED_PIN, LOW);
+        delay(200);
+        digitalWrite(LED_PIN, HIGH);
+        delay(200);
       }
     }
     digitalWrite(LED_PIN, HIGH);

     if (exosite_comm_errors == 5) {
-       for (int c=0; c<3; c++) {
-         digitalWrite(LED_PIN, LOW);
-         delay(500);
-         digitalWrite(LED_PIN, HIGH);
-         delay(500);
+      for (int c = 0; c < 3; c++) {
+        digitalWrite(LED_PIN, LOW);
+        delay(500);
+        digitalWrite(LED_PIN, HIGH);
+        delay(500);
       }
       Serial.print("exo: Check Provisioning - ");
       Serial.print("Murano Product ID: ");
@@ -246,11 +260,11 @@

       } else {
         Serial.println("exo: Provision: No New Activation");
-        for (int c=0; c<4; c++) {
-           digitalWrite(LED_PIN, LOW);
-           delay(500);
-           digitalWrite(LED_PIN, HIGH);
-           delay(500);
+        for (int c = 0; c < 4; c++) {
+          digitalWrite(LED_PIN, LOW);
+          delay(500);
+          digitalWrite(LED_PIN, HIGH);
+          delay(500);
         }
       }
       exosite_comm_errors = 0;
@@ -266,10 +280,10 @@
 }

 /*==============================================================================
-* connectWifi
-*
-* Use in setup to connect to local Wifi network
-*=============================================================================*/
+ * connectWifi
+ *
+ * Use in setup to connect to local Wifi network
+ *=============================================================================*/
 void connectWifi() {
   WiFi.mode(WIFI_STA); // Need for deepSleep
   // Connect to WiFi network
@@ -303,4 +317,4 @@
   // Print Some Useful Info
   Serial.print(F("wifi: MAC Address: "));
   Serial.println(macString);
-}
+}


turning on led

turning on led

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -9,6 +9,7 @@
 const int LOOP_LENGTH = 50;

 int distance;
+int led = 13;
 boolean is_hand = false;
 unsigned long time;
 unsigned long loop_delay;
@@ -18,6 +19,7 @@
   // initialize serial communication at 9600 bits per second:
   Serial.begin(115200);
   Dist.begin(A0);
+  pinMode(led, OUTPUT);
 }

 // the loop routine runs over and over again forever:
@@ -28,6 +30,7 @@
     if (!is_hand) {
       is_hand = true;
       Serial.println("ON");
+      digitalWrite(led, HIGH);
     }
     Serial.print("->");
     Serial.println(distance);
@@ -35,6 +38,7 @@
      if (is_hand) {
       is_hand = false;
       Serial.println("OFF");
+      digitalWrite(led, LOW);
     }
   }
   int loop_delay = LOOP_LENGTH - (time - millis());


Changed arduino string construction

Changed arduino string construction

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -13,15 +13,20 @@

 void send_log(String message) {
-  //char command = char(0);
   char end_stop = char(255);
-  String send_message = String(message + end_stop);
-  String send_message_with_command = String(0x00 + send_message);
+
+  String send_message = "";
+  send_message.concat(char(0));
+  send_message.concat(message);
+  send_message.concat(end_stop);
+
+//  String send_message = String(message + end_stop);
+//  String send_message_with_command = String(0x00 + send_message);

-  int send_length = send_message_with_command.length()+1;
+  int send_length = send_message.length()+1;

   char charBuf[send_length];
-  send_message_with_command.toCharArray(charBuf, send_length);
+  send_message.toCharArray(charBuf, send_length);
   Serial.write(charBuf);
 }


Reduce memory footprint by using PROGMEM variables. Add support for management dashboard on sdcard. Bugfixes.

--- sketches/Energino/Energino.ino
+++ sketches/Energino/Energino.ino
@@ -55,12 +55,12 @@
 #include <avr/eeprom.h>

 // comment/uncomment to disable/enable debug
-#define DEBUG
+//#define DEBUG

 // comment/uncomment to disable/enable ethernet support
-//#define NOETH
-
-#define RELAY_PIN 3
+#define NOETH
+
+#define RELAY_PIN 2

 #ifdef DEBUG
 #define DBG if(1)
@@ -69,13 +69,9 @@
 #endif

 // Feed id
-const long FEED = 0;
+long FEED = 0;
 // Cosm key
-const char KEY[] = "-";
-
-// Cosm configuration
-IPAddress HOST(216,52,233,121);
-const long PORT = 80;
+char KEY[] = "-";

 // Energino parameters
 int R1 = 100;
@@ -94,24 +90,23 @@

 #ifndef NOETH

-  // Server configuration parameters, energino will listen for
-  // incoming requests on this port
-  const long SERVER_PORT = 8180;
-
-  // This configuration is used when DHCP fails
-  IPAddress IP(192,168,1,10);
-  IPAddress MASK(255,255,255,0);
-  IPAddress GW(192,168,1,1);
-
-  // JSON response header and footer
-  const char JSON_RESPONSE_BEGIN[] = "HTTP/1.1 200 OK\nContent-Type: application/json\n\n[";
-  const char JSON_RESPONSE_END[] = "]\n";
-
-  // working vars
-  EthernetServer server(SERVER_PORT);
-
-  // Minimum period for Ethernet updates
-  const long MIN_ETHERNET_PERIOD = 2000;
+// Cosm configuration
+IPAddress HOST(216,52,233,121);
+long PORT = 80;
+
+// Server configuration parameters, energino will listen for
+// incoming requests on this port
+const long SERVER_PORT = 8180;
+
+// HTML response
+const char HTML_RESPONSE[43] PROGMEM = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n";
+const char HTML_RESPONSE_404[25] PROGMEM = "HTTP/1.1 404 Not Found\n\n";
+
+// JSON response header and footer
+const char JSON_RESPONSE[49] PROGMEM = "HTTP/1.1 200 OK\nContent-Type: application/json\n\n";
+
+// working vars
+EthernetServer server(SERVER_PORT);

 #endif

@@ -134,7 +129,8 @@
   IPAddress host;
   long port;
 #endif
-} settings;
+}
+settings;

 void reset() {
   strcpy (settings.magic,MAGIC);
@@ -160,7 +156,7 @@

 void setup() {
   // Set serial port
-  Serial.begin(115200);
+  Serial.begin(115200);
   // Default on
   pinMode(RELAY_PIN,OUTPUT);
   digitalWrite(RELAY_PIN, LOW);
@@ -168,47 +164,40 @@
   eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));
   if (strcmp(settings.magic, MAGIC) != 0) {
     reset();
-    DBG Serial.println("write defaults");
     eeprom_write_block((const void*)&settings, (void*)0, sizeof(settings));
   }
   // set sleep counter
   resetSleep(settings.period);
-  #ifndef NOETH
-    // Try to configure the ethernet using DHCP
-    delay(2000);
-    DBG Serial.println("dhcp");
-    if (Ethernet.begin(settings.mac) == 0) {
-      DBG Serial.println("dhcp fail");
-      // Use static IP
-      Ethernet.begin(settings.mac, IP, MASK, GW);
-    }
-    // Print IP
-    DBG Serial.print("ip: ");
-    DBG Serial.println(Ethernet.localIP());
-    // Give the Ethernet shield a second to initialize:
-    delay(1000);
-    // Start server
-    server.begin();
-    // Init SD
-    pinMode(10, OUTPUT);
-    // see if the card is present and can be initialized:
-    if (!SD.begin(4)) {
-      Serial.println("sd fail");
-      return;
-    }
-  #endif
+#ifndef NOETH
+  // Try to configure the ethernet using DHCP
+  if (Ethernet.begin(settings.mac) == 0) {
+    DBG Serial.println("dhcp fail");
+    return;
+  }
+  // Print IP
+  DBG Serial.print("ip: ");
+  DBG Serial.println(Ethernet.localIP());
+  // Start server
+  server.begin();
+  // Init SD
+  pinMode(10, OUTPUT);
+  // see if the card is present and can be initialized:
+  if (!SD.begin(4)) {
+    Serial.println("sd fail");
+    return;
+  }
+#endif
 }

 void loop() {
-
+
   // Make sure that update period is not too high
-  #ifndef NOETH
-    if ((settings.feed != 0) && (settings.period < MIN_ETHERNET_PERIOD)) {
-      DBG Serial.println("period too high");
-      resetSleep(MIN_ETHERNET_PERIOD);
-    }
-  #endif
-
+#ifndef NOETH
+  if ((settings.feed != 0) && (settings.period < 2000)) {
+    resetSleep(2000);
+  }
+#endif
+
   // Start profiling
   long started = millis();

@@ -216,10 +205,10 @@
   serParseCommand();

   // Listen for incoming requests
-  #ifndef NOETH
-    handleRequests();
-  #endif
-
+#ifndef NOETH
+  handleRequests();
+#endif
+
   // Instant values are too floating,
   // let's smooth them up
   long VRaw = 0;
@@ -235,16 +224,16 @@
   IFinal = scaleCurrent((float)IRaw/sleep);

   // send data to remote host
-  #ifndef NOETH
-    //sendData();
-  #endif
-
+#ifndef NOETH
+  sendData();
+#endif
+
   // dump to serial
   dumpToSerial();

   // profiling
   delta = abs(millis() - started);
-
+
   // Control loop
   sleep -= 5 * (delta - settings.period);
   if (sleep < 5) {
@@ -262,7 +251,8 @@
   // working vars
   char cmd = '\0';
   int i, serAva;
-  char inputBytes[60] = { '\0' };
+  char inputBytes[60] = {
+    '\0'           };
   char * inputBytesPtr = &inputBytes[0];
   // read command from serial
   serAva = Serial.available();
@@ -289,6 +279,7 @@
   if (cmd == 'R') {
     reset();
   }
+#ifndef NOETH
   else if (cmd == 'F') {
     long value = atol(inputBytesPtr);
     if (value >= 0) {
@@ -314,9 +305,10 @@
       settings.port = value;
     }
   }
+#endif
   else {
     int value = atoi(inputBytesPtr);
-    if (value > 0) {
+    if (value < 0) {
       return;
     }
     if (cmd == 'P') {
@@ -326,16 +318,16 @@
       settings.r1 = value;
     }
     else if (cmd == 'B') {
-        settings.r2 = value;
+      settings.r2 = value;
     }
     else if (cmd == 'C') {
-        settings.offset = value;
+      settings.offset = value;
     }
     else if (cmd == 'D') {
-        settings.sensitivity = value;
-    }
+      settings.sensitivity = value;
+    }
     else if (cmd == 'S') {
-      if (value >= 0) {
+      if (value > 0) {
         digitalWrite(RELAY_PIN, HIGH);
       }
       else {
@@ -366,7 +358,6 @@
       // If you've gotten to the end of the line (received a newline
       // character) the http request has ended, so you can send a reply
       if (c == '\n' || idx >= 50) {
-        //char method [5];
         char * method;
         method = strtok (buffer, " ");
         if (strcmp(method, "GET") == 0) {
@@ -376,11 +367,15 @@
           if (strcmp(toks, "read") == 0) {
             toks = strtok (NULL, "/");
             if (strcmp(toks, "datastreams") == 0) {
-              sendContent(request);
+              writeHeader(request, JSON_RESPONSE);
+              writeDataStream(request);
               break;
             }
             else if (strcmp(toks, "switch") == 0) {
-              sendContent(request, digitalRead(RELAY_PIN));
+              writeHeader(request, JSON_RESPONSE);
+              request.print("[");
+              request.print(digitalRead(RELAY_PIN));
+              request.print("]\n");
               break;
             }
           }
@@ -389,35 +384,33 @@
             if (strcmp(toks, "switch") == 0) {
               toks = strtok (NULL, "/");
               if (atoi(toks) > 0) {
-                DBG Serial.println("switch up");
                 digitalWrite(RELAY_PIN, HIGH);
               }
               else {
-                DBG Serial.println("switch down");
                 digitalWrite(RELAY_PIN, LOW);
               }
-              sendContent(request, digitalRead(RELAY_PIN));
+              writeHeader(request, JSON_RESPONSE);
+              request.print("[");
+              request.print(digitalRead(RELAY_PIN));
+              request.print("]\n");
               break;
             }
           }
           else {
-            File dataFile = SD.open("a.htm");
+            File dataFile = SD.open(toks, FILE_READ);
             if (dataFile) {
+              writeHeader(request, HTML_RESPONSE);
               while (dataFile.available()) {
-                  request.write(dataFile.read());
+                request.write(dataFile.read());
               }
               dataFile.close();
-            } else {
-              Serial.println(dataFile);
-            }
+              request.write("\n");
+              break;
+            }
           }
-          // send a not found response header
-          request.println("HTTP/1.1 404 Not Found\n\n");
-          request.println();
-          break;
         }
-        request.println("HTTP/1.1 501 Not Implemented\n\n");
-        request.println();
+        writeHeader(request, HTML_RESPONSE_404);
+        request.write("\n");
         break;
       }
     }
@@ -465,20 +458,14 @@
   }
   else {
     // if you couldn't make a connection:
-    DBG Serial.println("fail");
-  }
-}
-
-void sendContent(EthernetClient &request, long value) {
-  request.println(JSON_RESPONSE_BEGIN);
-  request.print(value);
-  request.print(JSON_RESPONSE_END);
-}
-
-void sendContent(EthernetClient &request) {
-  request.println(JSON_RESPONSE_BEGIN);
-  writeDataStream(request);
-  request.print(JSON_RESPONSE_END);
+    DBG Serial.println("connect fail");
+  }
+}
+
+void writeHeader(EthernetClient &request, const char * data) {
+  while (pgm_read_byte(data) != 0x00) {
+    request.write(pgm_read_byte(data++));
+  }
 }

 void writeDataStream(EthernetClient &request) {
@@ -497,8 +484,10 @@
   request.print("{\"id\":\"switch\", \"current_value\":");
   request.print(itoa(digitalRead(RELAY_PIN),r,10));
   request.print("}");
-  request.print("]}");;
-}
+  request.print("]}");
+  ;
+}
+
 #endif

 void dumpToSerial() {
@@ -519,39 +508,39 @@
   Serial.print(delta);
   Serial.print(",");
   Serial.print(sleep);
-  #ifdef NOETH
-    Serial.print(",");
-    Serial.print("-");
-    Serial.print(",");
-    Serial.print("-");
-    Serial.print(",");
-    Serial.print("-");
-    Serial.print(",");
-    Serial.print("-");
-    Serial.print(",");
-    Serial.print("-");
-    Serial.print(",");
-    Serial.print("-");
-  #else
-    Serial.print(",");
-    Serial.print(Ethernet.localIP());
-    Serial.print(",");
-    Serial.print(SERVER_PORT);
-    Serial.print(",");
-    for (byte thisByte = 0; thisByte < 4; thisByte++) {
-      // print the value of each byte of the IP address:
-      Serial.print(settings.host[thisByte], DEC);
-      if (thisByte < 3) {
-        Serial.print(".");
-      }
-    }
-    Serial.print(",");
-    Serial.print(settings.port);
-    Serial.print(",");
-    Serial.print(settings.feed);
-    Serial.print(",");
-    Serial.print(settings.apikey);
-  #endif
+#ifdef NOETH
+  Serial.print(",");
+  Serial.print("-");
+  Serial.print(",");
+  Serial.print("-");
+  Serial.print(",");
+  Serial.print("-");
+  Serial.print(",");
+  Serial.print("-");
+  Serial.print(",");
+  Serial.print("-");
+  Serial.print(",");
+  Serial.print("-");
+#else
+  Serial.print(",");
+  Serial.print(Ethernet.localIP());
+  Serial.print(",");
+  Serial.print(SERVER_PORT);
+  Serial.print(",");
+  for (byte thisByte = 0; thisByte < 4; thisByte++) {
+    // print the value of each byte of the IP address:
+    Serial.print(settings.host[thisByte], DEC);
+    if (thisByte < 3) {
+      Serial.print(".");
+    }
+  }
+  Serial.print(",");
+  Serial.print(settings.port);
+  Serial.print(",");
+  Serial.print(settings.feed);
+  Serial.print(",");
+  Serial.print(settings.apikey);
+#endif
   Serial.print("\n");

 }
@@ -568,4 +557,3 @@
   sleep = value / 1000 * 5000;
   settings.period = value;
 }
-


Added comments and refactored a bit.

Added comments and refactored a bit.

--- src/sketch.ino
+++ src/sketch.ino
@@ -10,7 +10,19 @@

 #define SENSOR_DETECT_PIN 7
 #define LED_PIN 13
+
+// How long to wait for no change to identify a stopped status (ms)
 #define STOP_THRESHOLD 1000L
+
+// How long to wait between reading the sensor. You may want to
+// tweak this value or the STOP THRESHOLD depending on how fast
+// the item is being moved. If the thing is moving fast, you may
+// want to shorten this time so you don't miss too many measurements.
+// If the thing is moving slow, you can probably leave this alone
+// or increase it, but you might need to increase the STOP_THRESHOLD.
+//
+// Think about it.
+#define DELAY_TIME 200

 enum MotionState {
   Stopped,
@@ -46,21 +58,29 @@

   // Now deal with the real world
   if (value != previousValue) {
-    previousValue = value;
-    lastChangeTime = millis();
-    currentState = Moving;
-    digitalWrite(LED_PIN, HIGH);
-    Serial.println("Now moving...");
+    handleValueChange(value);
   } else {
-    long duration = sampleTime - lastChangeTime;
-    if (duration > STOP_THRESHOLD) {
-      currentState = Stopped;
-      digitalWrite(LED_PIN, LOW);
-      Serial.print("No change for too long (");
-      Serial.print(duration);
-      Serial.println(") ms. Stopped");
-    }
+    handleValueNoChange(sampleTime);
   }

-  delay(300);
+  delay(DELAY_TIME);
 }
+
+void handleValueChange(int value) {
+  previousValue = value;
+  lastChangeTime = millis();
+  currentState = Moving;
+  digitalWrite(LED_PIN, HIGH);
+  Serial.println("Now moving...");
+}
+
+void handleValueNoChange(int sampleTime) {
+  long duration = sampleTime - lastChangeTime;
+  if (duration > STOP_THRESHOLD) {
+    currentState = Stopped;
+    digitalWrite(LED_PIN, LOW);
+    Serial.print("No change for too long (");
+    Serial.print(duration);
+    Serial.println(") ms. Stopped");
+  }
+}


add autostart to cyclictimer

add autostart to cyclictimer

--- arduino/due/due.ino
+++ arduino/due/due.ino
@@ -53,15 +53,15 @@
     CyclicTimer::onDone();
     lamp.toggle();
   }
-} flashLamp(451);
+} flashLamp(451,true);

 RegisterTimer(flashLamp);

-CyclicTimer noncritical(1250);
+CyclicTimer noncritical(1250,true);
 RegisterTimer(noncritical);

-CyclicTimer shorttimer(250);
+CyclicTimer shorttimer(250,true);
 RegisterTimer(shorttimer);

@@ -71,7 +71,6 @@
   //Pin structs take care of themselves, unless you need special modes outside arduino's libraries.
   greenirq.attach(true);//we don't build in attach() to the constructor as in many cases the isr needs stuff that isn't initialized until setup() is run.
   redirq.attach(true);
-  flashLamp.retrigger();//have to manually fire it off once, after that it toggles in its own.
 }

 char indicator='-';
@@ -79,6 +78,7 @@
   __WFE();//this made the beat between the two timers go away, which is a good thing.
   if(shorttimer.hasFired()){
     SerialUSB.print(indicator);
+    Serial.print('v');
   }
   if(noncritical.hasFired()){
     SerialUSB.println();


updated Basic example

updated Basic example

--- BME680_Library/examples/Basic/Basic.ino
+++ BME680_Library/examples/Basic/Basic.ino
@@ -5,11 +5,14 @@
 void setup(void){
   Serial.begin(9600);

-  if(!bme680.begin()){
-    Serial.print("BME680 Initialization Failed!");
+  Serial.print("BME Initialization...");
+  if(bme680.begin()){
+     Serial.print("Succeeded!");
+  }
+  else {
+    Serial.print("Failed!");
     for(;;); // spin forever
   }
-
 }

 void loop(void){


v1.0.1 - More comprehsensive object creation

Removing hard-coded object values

--- examples/voltage_divider/voltage_divider.ino
+++ examples/voltage_divider/voltage_divider.ino
@@ -9,12 +9,13 @@
 	B pin linked to ground
 	Wiper linked to analog0 pin to read back the wiper position

-	WARNING : in this example, the read wiper position is extrapolated from 2 non precise functions : AnalogRead and Map. This drive the read output to error up to 5 steps, espacially near the extreme positions. Please keep in mind also there is a not null R value at the step 0.
+	WARNING : in this example, the read wiper position is extrapolated from 2 non precise functions : AnalogRead and Map. This drive the read output to mismatch up to 4 steps, espacially near the extreme positions. Please keep in mind also there is a not null R value at the step 0.
 	This example only checks the library as working properly

     @section  HISTORY

     v1.0 - First release
+	v1.0.1 - More comprehsensive object creation - using #define stuff
 */
 /**************************************************************************/

@@ -22,14 +23,17 @@
 #include <AnalogDevice_AD5161.h>
 #include <Wire.h>
 #include <SPI.h>
-#include <math.h>
+//#include <math.h>

+#define I2CMODE true
 #define CSPIN 13
 #define AD0 0
+#define NB_STEPS 255
+#define RVALUE 5000
 #define ANALOG_PIN 0

 //AD5161 object creation
-ANALOGDEVICE_AD5161 myPot(true, 0, 0, 255, 5000);
+ANALOGDEVICE_AD5161 myPot(I2CMODE, CSPIN, AD0, NB_STEPS, RVALUE);

 uint8_t lastposition;


LED blink causing issues with serial monitor

--- module/module.ino
+++ module/module.ino
@@ -250,10 +250,6 @@
 	    	digitalWrite(interlock, HIGH);
 			lastPollTime = millis();
 		}
-
-		if ( (pollCounter > 0) && (timeSince(lastBlink) > 500) ) {
-			digitalWrite(ledPin, (digitalRead(ledPin) == HIGH ? LOW : HIGH));
-		}
 	}
 }
 /*void soundFeedback(bool isReject) {


rotary encoder

rotary encoder

Now a rotary encoder can be connected to vary the speed of the motor directly

--- CHMachine_Arduino/CHMachine_Arduino.ino
+++ CHMachine_Arduino/CHMachine_Arduino.ino
@@ -1,38 +1,114 @@
 /*
-  COCK HERO MACHINE serial connection V.0.9
+  COCK HERO MACHINE serial connection V.0.9.1
   http://cockheromachine.blogspot.it/
   cockheromachine@gmail.com
-
-  This program is expected to receive over serial an 8bit integer value between the string 'V' and any other string(e.g. V100S) to vary the pulse width accordingly on the analog pin.
+
+  This program is expected to receive over serial an 8bit integer value between the string 'V' and any other string(e.g. V100S) to vary the pulse width accordingly on the analog pin.
   The pin PWM goes to 0 after 200ms if no signal is received.
-
+  Optionally, a rotary encoder can be connected to vary the PWM duty cycle without the need of a serial connection.
+
 */

-int Value = 0;
-int pin = 5;
-int timelimit = 200;
-long unsigned timer = 0;
+
+const int encoderPin1 = 2; //encoder pin A
+const int encoderPin2 = 3;//encoder pin B
+const int pwmpin = 5; //PWM
+const int BUTTONpin = 12; // Pin for Button
+int Value = 0; //PWM speed from serial
+const int timelimit = 200; // turn off time after no data is received
+
+long unsigned timer = 0; // time since last data is received
+
+volatile int lastEncoded = 0;
+volatile long encoderValue = 0;//PWM value from encoder
+long lastencoderValue = 0;// last PWM value from encoder
+volatile bool knobstate = 1;//turn to 1 when encoder has been turned
+
+const int buttonWaitInterval = 5000; //microseconds between bounces
+
+unsigned long previousMicros = 0;// Used to track how long between "bounces"
+bool previousButtonState = 0;// Used to track state of button (high or low)
+bool debouncedButtonState = 0;// Variable reporting de-bounced state.
+bool bounceState = 0;// Tracks if we are waiting for a "bounce" event
+

 void setup() {
-  // initialize the digital pin as an output.
-  pinMode(pin, OUTPUT);
-  Serial.begin(9600);
-  //Serial.print("connOK");
-
+  Serial.begin (9600);
+
+  pinMode(encoderPin1, INPUT_PULLUP);
+  pinMode(encoderPin2, INPUT_PULLUP);
+  pinMode(pwmpin, OUTPUT);
+  pinMode(BUTTONpin, INPUT_PULLUP);
+
+  analogWrite (pwmpin, 0);
+
+  attachInterrupt(0, updateEncoder, CHANGE);
+  attachInterrupt(1, updateEncoder, CHANGE);
+
 }

-// the loop routine runs over and over again forever:
-void loop() {
-
-  if (Serial.available() > 0) {

+void updateEncoder() {
+  knobstate = 1;
+
+  int MSB = digitalRead(encoderPin1); //MSB = most significant bit
+  int LSB = digitalRead(encoderPin2); //LSB = least significant bit
+
+  int encoded = (MSB << 1) | LSB; //converting the 2 pin value to single number
+  int sum  = (lastEncoded << 2) | encoded; //adding it to the previous encoded value
+
+  if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
+  if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;
+
+  lastEncoded = encoded; //store this value for next time
+}
+
+
+void updateButton() {
+
+  if (bounceState == 1) {// Waiting for any activity on the button
+    boolean currentButtonState = digitalRead(BUTTONpin); // Get and store current button state
+
+    if (previousButtonState != currentButtonState) {// Check to see if a transition has occured (and only one)
+
+      bounceState = 0;// A transition was detected, ignore the others for a while
+
+      previousMicros = micros(); // Store current time (start the clock)
+    }
+
+    previousButtonState = currentButtonState;// Keep storing existing button state
+  }
+
+  if (bounceState == 0) {// We are waiting for the buttonWaitInterval to elapse
+
+    unsigned long currentMicros = micros();// Compare current value of micros to previously stored, enough time yet?
+    if ((unsigned long)(currentMicros - previousMicros) >= buttonWaitInterval) {
+      // Store the state of the button to debouncedButtonState, which "reports"
+      // the correct value. This allows for the code to handle active high or low inputs
+      debouncedButtonState = digitalRead(BUTTONpin);
+
+      bounceState = 1;// Go back to watching the button again.
+    }
+  }
+}
+
+
+
+
+
+void loop() {
+
+
+  if (Serial.available() > 0 ) {
+    knobstate = 0;
+    encoderValue = 0;

     if (Serial.peek() == 'V') {      //check for the character that signifies that this will be on
       Serial.read();                 //remove the first character(V)
       Value = Serial.parseInt();     //read the value
       Serial.read();                 //remove the last character(S)
-      analogWrite(pin, Value);       // set the state of the PIN
+      analogWrite(pwmpin, Value);       // set the state of the PIN
       timer = millis();              //reset the timer
     }

@@ -45,8 +121,8 @@
     else if (Serial.peek() == 'T') {      //check for the character T that estabilish the connection
       Serial.read();   //clean the serial buffer
       Serial.println("connOK");         //send a string
-
-
+
+
     }
     else
       Serial.read();                 //clear the serial buffer
@@ -54,8 +130,39 @@

   }

-  if (millis() - timer >= timelimit) { //turn off the pin after some time if no data is received
-    analogWrite(pin, 0);
+  if (millis() - timer >= timelimit and knobstate == 0) { //turn off the pin after some time if no data is received
+    analogWrite(pwmpin, 0);
   }

+
+  if (knobstate == 1) {
+    updateButton();
+
+    if (debouncedButtonState == 0) {
+      encoderValue = 0;
+    }
+
+    if (encoderValue != lastencoderValue) {
+
+      if ( encoderValue > 255 ) {
+        encoderValue = 255;
+      }
+      if ( encoderValue < 0 )   {
+        encoderValue = 0;
+      }
+
+      analogWrite(pwmpin, encoderValue);
+      lastencoderValue = encoderValue;
+    }
+  }
+
+
+
+
+
 }
+
+
+
+
+


added resetconfig command to reset all ssid/usernames/etc. and all passwords, all other config items stay intact

--- FirmwareManager/src/FirmwareManager.ino
+++ FirmwareManager/src/FirmwareManager.ino
@@ -957,6 +957,7 @@
         }
     }
     DEBUG2(">> Ready.\n");
+    DEBUG2(">> httpAuthUser: %s\n", httpAuthUser);
     DEBUG2(">> httpAuthPass: %s\n", httpAuthPass);
 }


fixed upload uri to production version

fixed upload uri to production version

--- controller_flash/controller.ino
+++ controller_flash/controller.ino
@@ -47,7 +47,7 @@
     ORP_final = dtostrf(orp, 2, 3, "ssssssss");
     Serial.println("casted values are pH_final = "+pH_final+" and ORP_final = "+ORP_final);
     // Make a HTTP request:
-    client.println("GET /poolcontrollerlog/chems/"+ORP_final+"/"+pH_final+"/"+sID+" HTTP/1.1");
+    client.println("GET /api/chems/"+ORP_final+"/"+pH_final+"/"+sID+" HTTP/1.1");
     client.println("Host: piemontese.robmengel.com");
     client.println("Connection: close");
     client.println();