refactor: use snake case

refactor: use snake case

--- src/src.ino
+++ src/src.ino
@@ -10,19 +10,19 @@
   Location loc;
 } Destination;

-// Updated by onNewGps
+// Updated by on_new_gps
 // Location
-Location currentLoc = {0};
+Location current_loc = {0};
 // Time in milliseconds
-unsigned long currentTime = 0;
-unsigned long lastTime = 0;
-double deltaTime = 0;
+unsigned long current_time = 0;
+unsigned long last_time = 0;
+double delta_time = 0;
 // Distance in degrees
-double currentDist = 0;
-double lastDist = 0;
-double deltaDist = 0;
-// ETA in milliseconds. If negative, we're traveling away from currentDest
-double etaTime = 0;
+double current_dist = 0;
+double last_dist = 0;
+double delta_dist = 0;
+// ETA in milliseconds. If negative, we're traveling away from current_dest
+double eta_time = 0;

 Destination dests[] = {
   {"Test", {0.0, 10.0}},
@@ -30,48 +30,49 @@
   {"Work", {44.989136, -93.250454}},
 };

-// Change currentDest to change the
-Location currentDest = dests[0].loc;
+// Change current_dest to change the distance and eta
+Location current_dest = dests[0].loc;

+// Assumes flat world - error: ~1km @ 1000km
 double distance(Location from, Location to) {
   return sqrt(pow(from.lat - to.lat, 2) + pow(from.lng - to.lng, 2));
 }

-void onNewGps(double lat, double lng) {
-  currentLoc.lat = lat;
-  currentLoc.lng = lng;
+void on_new_gps(double lat, double lng) {
+  current_loc.lat = lat;
+  current_loc.lng = lng;

-  lastTime = currentTime;
-  currentTime = millis();
-  deltaTime = currentTime - lastTime;
+  last_time = current_time;
+  current_time = millis();
+  delta_time = current_time - last_time;

-  lastDist = currentDist;
-  currentDist = distance(currentLoc, currentDest);
-  deltaDist = currentDist - lastDist;
+  last_dist = current_dist;
+  current_dist = distance(current_loc, current_dest);
+  delta_dist = current_dist - last_dist;

-  etaTime = -deltaTime * currentDist / deltaDist;
+  eta_time = -delta_time * current_dist / delta_dist;
 }

 void setup() {
   Serial.begin(9600);
 }

-unsigned long updateAt = 0;
+unsigned long update_at = 0;

 void loop() {
-  if (millis() >= updateAt) {
-    updateAt = millis() + 250;
+  if (millis() >= update_at) {
+    update_at = millis() + 250;
     int ticks = millis() / 250 % 96;
-    onNewGps(
+    on_new_gps(
       (double) cos(ticks * (2 * 3.14159 / 96)),
       (double) sin(ticks * (2 * 3.14159 / 96))
     );
-    Serial.print(currentLoc.lat, 6);
+    Serial.print(current_loc.lat, 6);
     Serial.print(", ");
-    Serial.println(currentLoc.lng, 6);
-    Serial.println(currentDist);
-    Serial.println(deltaDist);
-    Serial.println(etaTime / 1000);
+    Serial.println(current_loc.lng, 6);
+    Serial.println(current_dist);
+    Serial.println(delta_dist);
+    Serial.println(eta_time / 1000);
     Serial.println();
   }
 }


Encoders: Updated comments

Encoders: Updated comments

--- arduino/libraries/BuildingBlocks/examples/Encoders/Encoders.ino
+++ arduino/libraries/BuildingBlocks/examples/Encoders/Encoders.ino
@@ -3,7 +3,7 @@
 #include <SPI.h>
 #include <BuildingBlocks.h>

-// Define an instance of MiniKeyboard module.
+// Define an instance of Encoders module.
 Encoders encoders;

 // Define an instance of the Mainboard module.
@@ -16,7 +16,7 @@
 	// Initialize the Mainboard module
 	mainboard.init();

-	// Set the function which will get called when keyboard events are detected.
+	// Set the function which will get called when encoder events are detected.
 	encoders.setCallback(&onEncEvent);
 }

@@ -26,9 +26,9 @@
 }

 int16_t clamp(int16_t value, int16_t min, int16_t max) {
-  if (value < min) value = min;
-  else if (value > max) value = max;
-  return value;
+	if (value < min) value = min;
+	else if (value > max) value = max;
+	return value;
 }

 // This will get called while executing mainboard.update(), if events were detected.


Update WebServerSD.ino

Update WebServerSD.ino

Cleanup Error handling; Add additional check for missing file system

--- examples/WebServerSD/WebServerSD.ino
+++ examples/WebServerSD/WebServerSD.ino
@@ -34,35 +34,45 @@
 };

 boolean file_handler(TinyWebServer& web_server) {
+
+  if(!has_filesystem) {
+    web_server.send_error_code(500);
+    web_server << P("Internal Server Error");
+    return true;
+  }
+
   char* filename = TinyWebServer::get_file_from_path(web_server.get_path());
+
+  if(!filename) {
+  	web_server.send_error_code(400);
+  	web_server << F("Bad Request");
+  	return true;
+  }
+
   send_file_name(web_server, filename);
   free(filename);
   return true;
 }

 void send_file_name(TinyWebServer& web_server, const char* filename) {
-  if (!filename) {
+
+  TinyWebServer::MimeType mime_type
+    = TinyWebServer::get_mime_type_from_filename(filename);
+  if (file.open(&root, filename, O_READ)) {
+    web_server.send_error_code(200);
+    web_server.send_content_type(mime_type);
+    web_server.end_headers();
+
+    Serial << F("Read file "); Serial.println(filename);
+    web_server.send_file(file);
+    file.close();
+  } else {
     web_server.send_error_code(404);
-    web_server << F("Could not parse URL");
-  } else {
-    TinyWebServer::MimeType mime_type
-      = TinyWebServer::get_mime_type_from_filename(filename);
-    if (file.open(&root, filename, O_READ)) {
-      web_server.send_error_code(200);
-      web_server.send_content_type(mime_type);
-      web_server.end_headers();
-
-      Serial << F("Read file "); Serial.println(filename);
-      web_server.send_file(file);
-      file.close();
-    } else {
-      web_server.send_error_code(404);
-      web_server.send_content_type("text/plain");
-      web_server.end_headers();
-
-	  Serial << F("Could not find file: "); Serial.println(filename);
-      web_server << F("Could not find file: ") << filename << "\n";
-    }
+    web_server.send_content_type("text/plain");
+    web_server.end_headers();
+
+    Serial << F("Could not find file: "); Serial.println(filename);
+    web_server << F("404 - File not found") << filename << "\n";
   }
 }


[WifiDude] Refactoring request and response handling.

Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>

--- laundry-dude-xbee-bridge/laundry-dude-xbee-bridge.ino
+++ laundry-dude-xbee-bridge/laundry-dude-xbee-bridge.ino
@@ -12,6 +12,11 @@

 SoftwareSerial xbeeSerial(8, 9); // RX, TX
 Process curl;
+
+int requested[] = {0, 0, 0, 0, 0};
+String requests = "htlar";
+
+int ndx = 0;

 void setup() {
 	Bridge.begin();
@@ -29,18 +34,13 @@
 }

 void loop() {
-	request('l');
-	delay(1000);
-	request('h');
-	delay(1000);
-	request('t');
-	delay(1000);
-	request('a');
-	request('r');
-	delay(1000);
-	getData();
-	set('b', block);
-	setLockState(block == '1');
+	for (int i = 0; i < requests.length(); i++) {
+		request(requests.charAt(i));
+		while(processResponse());
+	}
+
+	for (int i = 0; i < 10000; i++)
+		processResponse();
 }

 void set(char type, char value) {
@@ -48,50 +48,60 @@
 	xbeeSerial.println(value);
 }

+bool processResponse() {
+	char type;
+	int indexOfType;
+
+	while (recvWithEndMarker()) {
+		type = receivedChars[0];
+		indexOfType = requests.indexOf(type);
+		if (indexOfType < 0)
+			return false;
+		sendData();
+		requested[indexOfType] = 0;
+		return true;
+	}
+}
+
 void request(char type) {
+	requested[requests.indexOf(type)] %= 50;
+	requested[requests.indexOf(type)]++;
+
+	if (requested[requests.indexOf(type)] != 1) {
+		return;
+	}
+
 	Console.print("Request: ");Console.println(type);
-	while (xbeeSerial.available()) xbeeSerial.read();
-
-	xbeeSerial.print(type);
-	int x = 0;
-	while (!xbeeSerial.available() && x < 10) {
-		x++;
-		delay(100);
-	}
-	recvWithEndMarker();
-	sendData();
+	xbeeSerial.println(type);
 }

 void sendData() {
-	if (newData == true) {
-		Console.print("This just in ... ");
-		Console.println(receivedChars);
-		postData(receivedChars);
-		newData = false;
-	}
+	Console.print("Sending: ");
+	Console.println(receivedChars);
+	postData(receivedChars);
 }

-void recvWithEndMarker() {
-	static byte ndx = 0;
+bool recvWithEndMarker() {
 	char endMarker = '\n';
 	char rc;

-	while (xbeeSerial.available() > 0 && newData == false) {
+	while (xbeeSerial.available()) {
 		rc = xbeeSerial.read();
+		Console.print(rc);

 		if (rc != endMarker) {
 			receivedChars[ndx] = rc;
 			ndx++;
-			if (ndx >= numChars) {
+			if (ndx >= numChars)
 				ndx = numChars - 1;
-			}
-		}
-		else {
+		} else {
 			receivedChars[ndx] = '\0'; // terminate the string
 			ndx = 0;
-			newData = true;
+			return true;
 		}
 	}
+
+	return false;
 }

 void postData(const char* data) {


Cleanup

Cleanup

--- fan.ino
+++ fan.ino
@@ -1,7 +1,6 @@
 #include <LiquidCrystal595.h>
 #include "Cabinet.h"
 #include "TextFormatter.h"
-#include "LEDHandler.h"
 #include <avr/pgmspace.h>
 #include <math.h>
 #include "Enums.h"


Update MarqueeTextClean.ino

Update MarqueeTextClean.ino

--- examples/MarqueeTextClean/MarqueeTextClean.ino
+++ examples/MarqueeTextClean/MarqueeTextClean.ino
@@ -210,6 +210,9 @@
 const uint8_t LEDMATRIX_CS_PIN = 9;
 const int LEDMATRIX_SEGMENTS = 4;
 const int LEDMATRIX_WIDTH    = LEDMATRIX_SEGMENTS * 8;
+
+//module reverse is set to true, remove the boolean parameter if
+//scrolling is appearing from the wrong side in each module.
 LEDMatrixDriver lmd(LEDMATRIX_SEGMENTS, LEDMATRIX_CS_PIN, true);

 // set x to LEDMATRIX_WIDTH to bring text "into" the display.


Working on implementing state transition functions and delineating the states explicitely.

--- SunriseAlarm.ino
+++ SunriseAlarm.ino
@@ -16,7 +16,7 @@

 // 2013-04-06 TODO:  Add a temperature sensor to the lamp and if it exceeds a particular temperature, then turn it off or down
 // 2013-04-06 TODO:  Add three LEDs inside the enclosure to indicate which mode you are in.  E.g. green for alarm, blue for time, and red for sundown.
-// 2013-04-06 DONE 2013-04-06:  Store SunSet alarm setting in EEPROM
+// 2013-04-06 DONE 2013-04-06:  Store Sunset alarm setting in EEPROM
 // 2013-04-06 DONE 2013-04-06:  Store brigness level in EEPROM
 // 2013-04-06 DONE 2013-04-06:  Change Alarm, Time, and Sundown modes so they will automatically exit the mode after 60 seconds of inactivity.
 // 2013-04-01 TODO:  Box enclosure:  Consider a OLED display behind a thin veneer of wood or paper so that the display can print
@@ -27,7 +27,7 @@
 // 2013-04-01 TODO:  Change "OffButton" to allow you to see how much time is left and reset it
 // 2013-04-01 TODO:  Rework SunRISE alarm to match the way the SunSET alarm works.  Basically, use millis() instead of clock
 // DONE 2013-03-29:  Add alarm & time mode so you don't have to hold down the buttons.
-// DONE 2013-03-30:  Add SunSet mode
+// DONE 2013-03-30:  Add Sunset mode
 // WONTFIX 2013-03-29:  Add AM/PM indicator
 // DONE 2013-03-29:  Add method to toggle alarm on/off
 // DONE 2013-03-28:  Add hardware buttons for setting time and alarm
@@ -217,8 +217,8 @@
 const int rewind_delay = 150;
 const uint32_t millisecondsIn30Minutes = 1800000;

-int defaultSunSetDelta = 10; // minutes
-int sunSetDimLevel = 100; // 100 = max bright, 0 = off
+int defaultSunsetDelta = 10; // minutes
+int sunsetDimLevel = 100; // 100 = max bright, 0 = off

 const uint32_t modeInactivePeriod = 30000; // 30 seconds

@@ -274,92 +274,6 @@
   encoder->service();
 }

-
-bool readAlarmTimeFromEEPROM() {
-  if (eeprom.isPresent()) {
-    char buf[2];
-    eeprom.ReadMem(alarm_address, buf, 2);
-    alarmTime.hour = static_cast<int>(buf[0]);
-    alarmTime.minute = static_cast<int>(buf[1]);
-    return true;
-  }
-  return false;
-}
-
-bool writeAlarmTimeToEEPROM() {
-  if (eeprom.isPresent()) {
-    char myBuf[2];
-    myBuf[0] = static_cast<char>(alarmTime.hour);
-    myBuf[1] = static_cast<char>(alarmTime.minute);
-    eeprom.WriteMem(alarm_address, myBuf, 2);
-    return true;
-  }
-  return false;
-}
-
-bool readBrightnessFromEEPROM() {
-  if (eeprom.isPresent()) {
-    char buf[1];
-    eeprom.ReadMem(brightness_address, buf, 1);
-    matrixBrightness = static_cast<int>(buf[0]);
-    return true;
-  }
-  return false;
-}
-
-bool writeBrightnessToEEPROM() {
-  if (eeprom.isPresent()) {
-    char myBuf[1];
-    myBuf[0] = static_cast<char>(matrixBrightness);
-    eeprom.WriteMem(brightness_address, myBuf, 1);
-    return true;
-  }
-  return false;
-}
-
-
-bool readSunSetDeltaFromEEPROM() {
-  if (eeprom.isPresent()) {
-    char buf[1];
-    eeprom.ReadMem(sunset_address, buf, 1);
-    defaultSunSetDelta = static_cast<int>(buf[0]);
-    return true;
-  }
-  return false;
-}
-
-bool writeSunSetDeltaToEEPROM() {
-  if (eeprom.isPresent()) {
-    char myBuf[1];
-    myBuf[0] = static_cast<char>(defaultSunSetDelta);
-    eeprom.WriteMem(sunset_address, myBuf, 1);
-    return true;
-  }
-  return false;
-}
-
-bool readSunSetDimFromEEPROM() {
-  if (eeprom.isPresent()) {
-    char buf[1];
-    eeprom.ReadMem(sunset_dim_address, buf, 1);
-    sunSetDimLevel = static_cast<int>(buf[0]);
-    return true;
-  }
-  return false;
-}
-
-bool writeSunSetDimToEEPROM() {
-  if (eeprom.isPresent()) {
-    char myBuf[1];
-    myBuf[0] = static_cast<char>(sunSetDimLevel);
-    eeprom.WriteMem(sunset_dim_address, myBuf, 1);
-    return true;
-  }
-  return false;
-}
-
-
-
 int debounceInterval = 30;
 int debounceDigitalRead(int pin) {
   int lastResult = digitalRead(pin);
@@ -374,6 +288,111 @@
   return lastResult;
 }

+bool alarmButtonPushed()
+{
+  return (digitalRead(AlarmButton) == LOW && debounceDigitalRead(AlarmButton) == LOW);
+}
+
+bool timeButtonPushed()
+{
+  return (digitalRead(TimeButton) == LOW && debounceDigitalRead(TimeButton) == LOW);
+}
+bool offButtonPushed()
+{
+  return (digitalRead(OffButton) == HIGH && debounceDigitalRead(OffButton) == HIGH);
+}
+
+bool rotaryButtonPushed()
+{
+  return (digitalRead(RotaryButton) == LOW && debounceDigitalRead(RotaryButton) == LOW);
+}
+
+bool readAlarmTimeFromEEPROM() {
+  if (eeprom.isPresent()) {
+    char buf[2];
+    eeprom.ReadMem(alarm_address, buf, 2);
+    alarmTime.hour = static_cast<int>(buf[0]);
+    alarmTime.minute = static_cast<int>(buf[1]);
+    return true;
+  }
+  return false;
+}
+
+bool writeAlarmTimeToEEPROM() {
+  if (eeprom.isPresent()) {
+    char myBuf[2];
+    myBuf[0] = static_cast<char>(alarmTime.hour);
+    myBuf[1] = static_cast<char>(alarmTime.minute);
+    eeprom.WriteMem(alarm_address, myBuf, 2);
+    return true;
+  }
+  return false;
+}
+
+bool readBrightnessFromEEPROM() {
+  if (eeprom.isPresent()) {
+    char buf[1];
+    eeprom.ReadMem(brightness_address, buf, 1);
+    matrixBrightness = static_cast<int>(buf[0]);
+    return true;
+  }
+  return false;
+}
+
+bool writeBrightnessToEEPROM() {
+  if (eeprom.isPresent()) {
+    char myBuf[1];
+    myBuf[0] = static_cast<char>(matrixBrightness);
+    eeprom.WriteMem(brightness_address, myBuf, 1);
+    return true;
+  }
+  return false;
+}
+
+
+bool readSunsetDeltaFromEEPROM() {
+  if (eeprom.isPresent()) {
+    char buf[1];
+    eeprom.ReadMem(sunset_address, buf, 1);
+    defaultSunsetDelta = static_cast<int>(buf[0]);
+    return true;
+  }
+  return false;
+}
+
+bool writeSunsetDeltaToEEPROM() {
+  if (eeprom.isPresent()) {
+    char myBuf[1];
+    myBuf[0] = static_cast<char>(defaultSunsetDelta);
+    eeprom.WriteMem(sunset_address, myBuf, 1);
+    return true;
+  }
+  return false;
+}
+
+bool readSunsetDimFromEEPROM() {
+  if (eeprom.isPresent()) {
+    char buf[1];
+    eeprom.ReadMem(sunset_dim_address, buf, 1);
+    sunsetDimLevel = static_cast<int>(buf[0]);
+    return true;
+  }
+  return false;
+}
+
+bool writeSunsetDimToEEPROM() {
+  if (eeprom.isPresent()) {
+    char myBuf[1];
+    myBuf[0] = static_cast<char>(sunsetDimLevel);
+    eeprom.WriteMem(sunset_dim_address, myBuf, 1);
+    return true;
+  }
+  return false;
+}
+
+
+
+
 uint8_t computeMinRGBLevel(uint8_t* RGB)
 {
   uint8_t myRGB[3] = {255, 255, 255};
@@ -396,11 +415,11 @@
 uint8_t minRGBLevel = computeMinRGBLevel(targetColor);
 uint16_t totalDimmerSteps = minRGBLevel * NUM_LED;

-void setColorForSunSet()
+void setColorForSunset()
 {
   for (uint8_t i = 0 ; i < 3 ; ++i)
   {
-    targetColor[i] = (sunSetDimLevel*1.0/100.0)*(1.0*candleLight[i]);
+    targetColor[i] = (sunsetDimLevel*1.0/100.0)*(1.0*candleLight[i]);
   }
   minRGBLevel = computeMinRGBLevel(targetColor);
   totalDimmerSteps = minRGBLevel * NUM_LED;
@@ -633,8 +652,8 @@
   display_todd();
   readBrightnessFromEEPROM();
   matrix.setBrightness(matrixBrightness); // 0-15
-  readSunSetDeltaFromEEPROM();
-  readSunSetDimFromEEPROM();
+  readSunsetDeltaFromEEPROM();
+  readSunsetDimFromEEPROM();
   updateClockTime(true);
   updateCurrentTime(true);
   readAlarmTimeFromEEPROM();
@@ -712,20 +731,21 @@
   analogWrite(TimeLED, matrixBrightness * 255 / 16 + 15);
   display_Cloc();
   delay(1000);
+  waitForButtonDepress(TimeButton, LOW);
+}
+
+void changeState_setTime_to_Clock()
+{
+  updateCurrentTime(true);
+  digitalWrite(TimeLED, LOW);
+}
+
+void setTimeState() {
+  changeState_Clock_to_setTime();
+
   DateTime currentTime = RTC.now();
   ClockTime t(currentTime);
   updateTimeDisplay(t, true, alarmMasterSwitchEnabled);
-  waitForButtonDepress(TimeButton, LOW);
-}
-
-void changeState_setTime_to_Clock()
-{
-  updateCurrentTime(true);
-  digitalWrite(TimeLED, LOW);
-}
-
-void setTimeState() {
-  chnageState_Clock_to_setTime();

   uint32_t modeActive = millis();
   bool normalExit = true;
@@ -804,31 +824,31 @@
   changeState_setAlarm_to_Clock();
 }

+bool sunsetActive = false;
 void changeState_Clock_to_setSunset()
 {
-  setColorForSunSet();
-  matrix.print(sunSetDimLevel);
-  if (sunSetDimLevel == 0) {
+  setColorForSunset();
+  matrix.print(sunsetDimLevel);
+  if (sunsetDimLevel == 0) {
     matrix.writeDigitNum(4, 0);
   }
   matrix.writeDisplay();
-  sunSetActive = true;
+  sunsetActive = true;
   turnLightOn();
   waitForButtonDepress(RotaryButton, LOW);
 }

 void changeState_setSunset_to_Clock()
 {
-  if (sunSetDimLevel == 0) {
-    sunSetActive = false;
+  if (sunsetDimLevel == 0) {
+    sunsetActive = false;
     turnLightOff();
   }
-  writeSunSetDimToEEPROM();
-}
-
-uint32_t millisAtStartOfSunSet = 0;
-bool sunSetActive = false;
-void setSunSetState() {
+  writeSunsetDimToEEPROM();
+}
+
+uint32_t millisAtStartOfSunset = 0;
+void setSunsetState() {
   changeState_Clock_to_setSunset();

   uint32_t modeActive = millis();
@@ -837,12 +857,12 @@
     int16_t encoderDelta = encoder->getValue();
     if (encoderDelta != 0)
     {
-      sunSetDimLevel += encoderDelta;
-      sunSetDimLevel = min(100,max(0, sunSetDimLevel));
-      matrix.print(sunSetDimLevel);
-      if (sunSetDimLevel == 0) matrix.writeDigitNum(4, 0);
+      sunsetDimLevel += encoderDelta;
+      sunsetDimLevel = min(100,max(0, sunsetDimLevel));
+      matrix.print(sunsetDimLevel);
+      if (sunsetDimLevel == 0) matrix.writeDigitNum(4, 0);
       matrix.writeDisplay();
-      setColorForSunSet();
+      setColorForSunset();
       turnLightOn();
       modeActive = millis();
     }
@@ -854,29 +874,29 @@
   if (normalExit) {
     waitForButtonDepress(RotaryButton, LOW);
   }
-  millisAtStartOfSunSet = millis();
+  millisAtStartOfSunset = millis();

   changeState_setSunset_to_Clock();
 }

-uint32_t lastSunSetUpdate = millis();
-unsigned sunSetUpdateInterval = 5;
-int lastSunSetLightLevel = 0;
+uint32_t lastSunsetUpdate = millis();
+unsigned sunsetUpdateInterval = 5;
+int lastSunsetLightLevel = 0;
 void updateSunsetLight() {
-  if (!sunSetActive) {
+  if (!sunsetActive) {
     return;
   }
-  if (!isTimeNow(lastSunSetUpdate, sunSetUpdateInterval)) {
+  if (!isTimeNow(lastSunsetUpdate, sunsetUpdateInterval)) {
     return;
   }
   uint32_t currentMillis = millis();
-  uint32_t delta = static_cast<uint32_t>(currentMillis - millisAtStartOfSunSet);
-  uint32_t finalMillis = defaultSunSetDelta;
+  uint32_t delta = static_cast<uint32_t>(currentMillis - millisAtStartOfSunset);
+  uint32_t finalMillis = defaultSunsetDelta;
   finalMillis *= 60;
   finalMillis *= 1000;
   if (delta > finalMillis) {
-    sunSetActive = false;
+    sunsetActive = false;
     linearBrightOfStep(0);
   }
   else {
@@ -886,24 +906,6 @@
 }

-bool alarmButtonPushed()
-{
-  return (digitalRead(AlarmButton) == LOW && debounceDigitalRead(AlarmButton) == LOW);
-}
-
-bool timeButtonPushed()
-{
-  return (digitalRead(TimeButton) == LOW && debounceDigitalRead(TimeButton) == LOW);
-}
-bool offButtonPushed()
-{
-  return (digitalRead(OffButton) == HIGH && debounceDigitalRead(OffButton) == HIGH);
-}
-
-bool rotaryButtonPushed()
-{
-  return (digitalRead(RotaryButton) == LOW && debounceDigitalRead(RotaryButton) == LOW);
-}

 void turnOffLightsDueToOffButton()
 {
@@ -918,8 +920,8 @@
       snoozeActive = false;
       turnLightOff();
     }
-    else if (sunSetActive) {
-      sunSetActive = false;
+    else if (sunsetActive) {
+      sunsetActive = false;
       turnLightOff();
     }
     else {
@@ -949,7 +951,7 @@
   if (alarmButtonPushed()) setAlarmState();
   else if (timeButtonPushed()) setTimeState();
   else if (offButtonPushed()) turnOffLightsDueToOffButton();
-  else if (rotaryButtonPushed()) setSunSetState();
+  else if (rotaryButtonPushed()) setSunsetState();

   processAlarmMasterSwitch();
   updateAlarmLight();
@@ -970,4 +972,4 @@
   SunriseAlarm::loop();
 }

-void
+


Latest changes.

Latest changes.

--- hal100/hal100.ino
+++ hal100/hal100.ino
@@ -53,12 +53,6 @@
 float valueL = 0;           // calculated value L float
 float Cmult;                // constant multiplier to calculate C value
 float Lmult;                // constant multiplier to calculate L value
-float totalStepsC;          // amount of steps in single 260 degree rotation
-float pFmin;                // value of minimum pF in given variable capacitor
-float pFmax;                // value of maximum pF in given variable capacitor
-float pFtotalValue;         // = maximum pF - minimum pF
-float pFperStep;            // value of pF in one motor step
-float valueRotateC;         // steps neede to rotate to calculated C value

 boolean presentValue = false;

@@ -284,6 +278,7 @@
   PlanckTime = 299792458;
   Cmult = 1.5;
   valueC = PlanckTime / ( tuningFreqCalc * KHz ) * Cmult;
+  Serial.print("Value C pF=");
   Serial.println(valueC);
 }

@@ -291,20 +286,21 @@
   pi = 3.14159;
   Lmult = 1000000000000;
   valueL = ((1 / (2 * pi * tuningFreqCalc * valueC)) / (2 * pi * tuningFreqCalc)) * Lmult;
+  Serial.print("Value L uH=");
   Serial.println(valueL);
 }

 void calculateStepsC() {                        // calculate needed steps for C
-  // Process for linear capacitor with 22-360 pH - need to ajust or change for different capacitor
-
-  totalStepsC = 2964;
-  pFmin = 22;
-  pFmax = 360;
-  pFtotalValue = pFmax - pFmin;
-//  Serial.println(pFtotalValue);
-  pFperStep = pFtotalValue / ( totalStepsC / 2 );
-//  Serial.println(pFperStep);
-  valueRotateC = ( valueC - pFmin ) / pFperStep;
+  // Process for linear capacitor with 44-408 pF - need to ajust or change for different capacitor
+  float totalStepsC = 2964;
+  float pFmin = 20;
+  float pFmax = 200;
+  float pFtotalValue = pFmax - pFmin;
+  Serial.println(pFtotalValue);
+  float pFperStep = pFtotalValue / ( totalStepsC / 2 );
+  Serial.println(pFperStep);
+  float valueRotateC = ( valueC - pFmin ) / pFperStep;
+  Serial.print("steps C to rotate=");
   Serial.println(valueRotateC);
 }

@@ -313,7 +309,15 @@
 }

 void calculateStepsL() {                        // calculate needed steps for L
- // Process for non-linear variable inductor - need to ajust or change for different capacitor
+ // Process for non-linear variable inductor - need to ajust or change for different inductor
+ // y = -0.0299x2 + 1.3867x + 0.5894
+ float totalStepsL = 2964;                                                              // total motor steps for 1 rotation
+ float LturnsRequred = ( -0.0299 * valueL * valueL ) + ( 1.3867 * valueL ) + 0.5894;    // poly math
+ float valueRotateL = LturnsRequred * totalStepsL;
+ Serial.print("L turns requred=");
+ Serial.println(LturnsRequred);
+ Serial.print("steps L to rotate=");
+ Serial.println(valueRotateL);

 }

@@ -386,4 +390,4 @@
   //    TFTscreen.text(dataPrintout, 50, 70);
   //  }

-}
+}


Display "fade" value when setting

Display "fade" value when setting

--- sketches/utils/blinkm_control/blinkm_control.ino
+++ sketches/utils/blinkm_control/blinkm_control.ino
@@ -392,6 +392,8 @@
           Serial.println("Fade speed out of range; setting to 128");
           fadeSpeed = 128;
         }
+        Serial.print("Set fade speed to ");
+        Serial.println(fadeSpeed);
         dev.send();
         dev.write('f');
         dev.write(fadeSpeed);


FIX: Type definition of debounce variables.

--- sketches/midi_organ_debounce/midi_organ_debounce.ino
+++ sketches/midi_organ_debounce/midi_organ_debounce.ino
@@ -100,7 +100,7 @@
 }

 // same function as above, but take into effect debounce.
-void keyChangeDebounce(bool value, bool &state, char &debounce, int key, int channel) {
+void keyChangeDebounce(bool value, bool &state, unsigned char &debounce, int key, int channel) {
   // Compare them - `state` records inverse of switch read
   if (value == state) { // Equal means a change

@@ -129,7 +129,7 @@
 }

 // function to loop over pedals
-void pedalPoll(bool (&states)[numPedals], char (&debounce)[numPedals], int arraySize, int pedalMidiChannel) {
+void pedalPoll(bool (&states)[numPedals], unsigned char (&debounce)[numPedals], int arraySize, int pedalMidiChannel) {
   for(int key=0; key<arraySize; key++){
       // run through all switches, reading their values
       // pass results to keyChange which will dispatch a MIDI event if needed


Changing the cycle time and displaying the button state

--- ReaperRemote.ino
+++ ReaperRemote.ino
@@ -1,9 +1,9 @@
 /**
- * Author: Leonid Lezner
- * License: MIT
- *
- * Required libraries: Adafruit_BluefruitLE_nRF51, Button
- */
+   Author: Leonid Lezner
+   License: MIT
+
+   Required libraries: Adafruit_BluefruitLE_nRF51, Button
+*/

 #include <Arduino.h>
 #include "Feather.h"
@@ -15,8 +15,8 @@
 #include "Adafruit_BLEBattery.h"
 #include <Button.h>

-#define MINIMUM_FIRMWARE_VERSION "0.6.6"
-#define MODE_LED_BEHAVIOUR      "MODE"
+#define MINIMUM_FIRMWARE_VERSION    "0.6.6"
+#define MODE_LED_BEHAVIOUR          "MODE"

 const unsigned int batt_mv_curve[] = {4200, 4030, 3860, 3830, 3790, 3700, 3600};
 const unsigned char batt_charge_curve[] = {100, 76, 52, 42, 30, 11, 0};
@@ -32,14 +32,15 @@
 Adafruit_BLEMIDI midi(ble);
 Adafruit_BLEBattery battery(ble);

-Button button1(5);
-Button button2(6);
-
-#define MIDI_COMMAND_ON     0x90
-#define MIDI_COMMAND_OFF    0x80
-
-#define CYCLE_TIME          500 /* ms */
-#define CYCLE_TIME_BATTERY  1000
+// Button 1 is mute
+Button button1(6);
+
+// Button 2 is chapter marker
+Button button2(5);
+
+#define CYCLE_TIME_BLE      200 /* ms */
+#define CYCLE_TIME_BATTERY  1000 /* ms */
+#define CYCLE_TIME          50

 void error(const __FlashStringHelper *err)
 {
@@ -63,7 +64,7 @@

 void BleMidiRX(uint16_t timestamp, uint8_t status, uint8_t byte1, uint8_t byte2)
 {
-
+  /* no action, ignoring the incomming data */
 }

 void setup()
@@ -73,6 +74,9 @@
   button1.begin();
   button2.begin();

+  pinMode(ledPin, OUTPUT);
+  digitalWrite(ledPin, LOW);
+
   Serial.println(F("Reaper Remote by Allesnetz.com"));

   if (!ble.begin(VERBOSE_MODE))
@@ -125,18 +129,21 @@
   }
 }

-
-void sendCC(unsigned char mute) {
+void sendMuteCommand(bool mute) {
   // Send CC message on channel 0, controller 1
   midi.send(0xB0, 1, mute ? 127 : 0);
 }

+void sendMidiNote(bool onState, unsigned char channel, unsigned char note, unsigned char velocity) {
+  midi.send((onState ? 0x90 : 0x80) | (channel & 0x0F), note, velocity);
+}
+
 void loop() {
-  if (cycle_ble >= CYCLE_TIME) {
+  if (cycle_ble >= CYCLE_TIME_BLE) {
     cycle_ble = 0;
-    ble.update(CYCLE_TIME);
+    ble.update(CYCLE_TIME_BLE);
   } else {
-    cycle_ble += 100;
+    cycle_ble += CYCLE_TIME;
   }

   if (isConnected) {
@@ -145,11 +152,6 @@

       unsigned int voltage = getBatteryVoltage();
       unsigned char charge = chargeLookup(batt_mv_curve, batt_charge_curve, voltage);
-
-      Serial.print("VBat: ");
-      Serial.print(voltage);
-      Serial.print(" c: ");
-      Serial.println(charge);

       ble.print("VBat: ");
       ble.print(voltage);
@@ -158,7 +160,7 @@

       battery.update(charge);
     } else {
-      cycle_battery += 100;
+      cycle_battery += CYCLE_TIME;
     }
   }

@@ -166,13 +168,15 @@
   if (button1.toggled()) {
     if (button1.read() == Button::PRESSED) {
       Serial.println("Button 1 has been pressed");
-      if (isConnected) {
-        sendCC(1);
+      digitalWrite(ledPin, HIGH);
+      if (isConnected) {
+        sendMuteCommand(true);
       }
     } else {
       Serial.println("Button 1 has been released");
-      if (isConnected) {
-        sendCC(0);
+      digitalWrite(ledPin, LOW);
+      if (isConnected) {
+        sendMuteCommand(false);
       }
     }
   }
@@ -181,17 +185,19 @@
   if (button2.toggled()) {
     if (button2.read() == Button::PRESSED) {
       Serial.println("Button 2 has been pressed");
+      digitalWrite(ledPin, HIGH);
       if (isConnected) {
         // Send the note to reaper to set the marker
-        midi.send(MIDI_COMMAND_ON, 0, 64);
+        sendMidiNote(true, 0, 0, 64);
       }
     } else {
       Serial.println("Button 2 has been released");
-      if (isConnected) {
-        midi.send(MIDI_COMMAND_OFF, 0, 64);
+      digitalWrite(ledPin, LOW);
+      if (isConnected) {
+        sendMidiNote(false, 0, 0, 64);
       }
     }
   }

-  delay(100);
-}
+  delay(CYCLE_TIME);
+}


REV8 h/w test WIP

REV8 h/w test WIP

--- Arduino/hardware/V0p2_Main_PCB_REV7_DORM1_and_REV8/testsuite/201611/REV8Minimal-201701/REV8Minimal-201701.ino
+++ Arduino/hardware/V0p2_Main_PCB_REV7_DORM1_and_REV8/testsuite/201611/REV8Minimal-201701/REV8Minimal-201701.ino
@@ -23,6 +23,9 @@
  *     - todo init GPIO pins to safe mode.
  *     - todo init peripherals to safe low power mode.
  *     - loop endlessly.
+ *
+ * See also, for previous version of this code:
+ *     Arduino/snapshots/20150110-r4107-V0p2-Arduino-REV8-boiler-relay-test/
  */

 // INCLUDES & DEFINES


- whitespace and indentation

- whitespace and indentation

--- examples/HID/HID_volume/HID_volume.ino
+++ examples/HID/HID_volume/HID_volume.ino
@@ -33,17 +33,17 @@

   if (buttonState == LOW) {
     Serial.println(F("BLE HID Peripheral - clearing bond data"));
-
+
     // clear bond store data
     bleHIDPeripheral.clearBondStoreData();
   }
-
+
   encoder.write(0);
-
+
 #ifdef ANDROID_CENTRAL
   bleHIDPeripheral.setReportIdOffset(1);
 #endif
-
+
   bleHIDPeripheral.setLocalName("HID Volume");
   bleHIDPeripheral.addHID(bleMultimedia);

@@ -62,7 +62,7 @@

     while (bleHIDPeripheral.connected()) {
       pollButton();
-
+
       pollEncoder();
     }

@@ -75,10 +75,10 @@
 void pollButton() {
   // check the button
   int tempButtonState = digitalRead(BUTTON_PIN);
-
+
   if (tempButtonState != buttonState) {
     buttonState = tempButtonState;
-
+
     if (buttonState == LOW) {
       Serial.println(F("Mute"));
       bleMultimedia.write(MMKEY_MUTE);
@@ -89,18 +89,17 @@
 void pollEncoder() {
   // check the encoder
   int encoderState = encoder.read();
-
+
   if (encoderState != 0) {
-      if (encoderState > 0) {
-        Serial.println(F("Volume up"));
-        bleMultimedia.write(MMKEY_VOL_UP);
-      } else {
-        Serial.println(F("Volume down"));
-        bleMultimedia.write(MMKEY_VOL_DOWN);
-      }
-
+    if (encoderState > 0) {
+      Serial.println(F("Volume up"));
+      bleMultimedia.write(MMKEY_VOL_UP);
+    } else {
+      Serial.println(F("Volume down"));
+      bleMultimedia.write(MMKEY_VOL_DOWN);
+    }
+
     encoder.write(0);
   }
 }

-


COH-78: WIP

COH-78: WIP

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1,6 +1,6 @@
 // Uncomment exactly one of the following CONFIG_... lines to select which board is being built for.
-#define CONFIG_Trial2013Winter_Round2_CC1HUB // REV2 cut4 as CC1 hub.
-//#define CONFIG_REV9 // REV9 as CC1 relay, cut 2 of the board.
+//#define CONFIG_Trial2013Winter_Round2_CC1HUB // REV2 cut4 as CC1 hub.
+#define CONFIG_REV9 // REV9 as CC1 relay, cut 2 of the board.

 // IF DEFINED: entire comms model switches to secure.
 #define ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
@@ -335,19 +335,20 @@
 // Send a CC1 Alert message with this unit's house code via the RFM23B.
 bool sendCC1AlertByRFM23B()
   {
+#if !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
   OTProtocolCC::CC1Alert a = OTProtocolCC::CC1Alert::make(FHT8V.nvGetHC1(), FHT8V.nvGetHC2());
   if(a.isValid()) // Might be invalid if house codes are, eg if house codes not set.
     {
     uint8_t txbuf[OTProtocolCC::CC1Alert::primary_frame_bytes+1]; // More than large enough for preamble + sync + alert message.
     const uint8_t bodylen = a.encodeSimple(txbuf, sizeof(txbuf), true);
-#if 0 && defined(DEBUG)
-OTRadioLink::printRXMsg(p, txbuf, bodylen);
-#endif
     // Send loud since the hub may be relatively far away,
     // there is no 'ACK', and these messages should not be sent very often.
     // Should be consistent with automatically-generated alerts to help with diagnosis.
     return(PrimaryRadio.sendRaw(txbuf, bodylen, 0, OTRadioLink::OTRadioLink::TXmax));
     }
+#else
+#error --- send beacon frame
+#endif // ENABLE_OTSECUREFRAME_ENCODING_SUPPORT
   return(false); // Failed.
   }
 #endif


COH-71: WIP

COH-71: WIP

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -445,9 +445,9 @@
   // Set up async edge interrupts.
   ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
     {
-    //PCMSK0 = PB; PCINT  0--7    (LEARN1 and Radio)
+    //PCMSK0 = PB; PCINT  0--7    (Radio)
     //PCMSK1 = PC; PCINT  8--15
-    //PCMSK2 = PD; PCINT 16--24   (Serial RX and LEARN2 and MODE and Voice)
+    //PCMSK2 = PD; PCINT 16--24   (Serial RX)

     PCICR =
 #if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
@@ -486,6 +486,7 @@
   TIME_LSD = OTV0P2BASE::getSecondsLT();
   }

+
 void loop() {
   // put your main code here, to run repeatedly:


Re-generate GSM examples, #294

Re-generate GSM examples, #294

--- examples/Boards_GSM/SIM800_SIM900/SIM800_SIM900.ino
+++ examples/Boards_GSM/SIM800_SIM900/SIM800_SIM900.ino
@@ -1,4 +1,7 @@
 /*************************************************************
+  Download latest Blynk library here:
+    https://github.com/blynkkk/blynk-library/releases/latest
+
   Blynk is a platform with iOS and Android apps to control
   Arduino, Raspberry Pi and the likes over the Internet.
   You can easily build graphic interfaces for all your
@@ -14,43 +17,41 @@
   This example code is in public domain.

  *************************************************************
-
-  This example shows how to use SIM800 or SIM900 modem series
-  to connect your project to Blynk.
-
   Attention! Please check out TinyGSM guide:
     http://tiny.cc/tiny-gsm-readme

-  WARNING: SIM module support is for BETA testing.
+  WARNING: GSM modem support is for BETA testing.

   Change GPRS apm, user, pass, and Blynk auth token to run :)
   Feel free to apply it to any other example. It's simple!

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

-#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
-
-// Default heartbeat interval for GSM is 60
-// If you want override this value, uncomment and set this option:
-//#define BLYNK_HEARTBEAT 30
+/* Comment this out to disable prints and save space */
+#define BLYNK_PRINT Serial

 // Select your modem:
 #define TINY_GSM_MODEM_SIM800
 //#define TINY_GSM_MODEM_SIM900
 //#define TINY_GSM_MODEM_M590
+//#define TINY_GSM_MODEM_A6
+
+// Default heartbeat interval for GSM is 60
+// If you want override this value, uncomment and set this option:
+//#define BLYNK_HEARTBEAT 30

 #include <TinyGsmClient.h>
 #include <BlynkSimpleSIM800.h>

 // You should get Auth Token in the Blynk App.
 // Go to the Project Settings (nut icon).
-const char auth[] = "YourAuthToken";
+char auth[] = "YourAuthToken";

 // Your GPRS credentials
 // Leave empty, if missing user or pass
-const char apn[]  = "YourAPN";
-const char user[] = "";
-const char pass[] = "";
+char apn[]  = "YourAPN";
+char user[] = "";
+char pass[] = "";

 // Hardware Serial on Mega, Leonardo, Micro
 #define SerialAT Serial1
@@ -63,8 +64,9 @@

 void setup()
 {
-  // Set console baud rate
-  Serial.begin(115200);
+  // Debug console
+  Serial.begin(9600);
+
   delay(10);

   // Set GSM module baud rate


Fixed QoS error caused by MQTTCLIENT_QOS2 being defined after including MQTTClient.h Moved Send LED activity into publishToBroker so as to include this on initial set up Added Last Will and Testament so that broker reports an error in case of connection failure

--- sensor/ZoneControlSensor.ino
+++ sensor/ZoneControlSensor.ino
@@ -3,6 +3,8 @@
 Copyright (c) Nicholas Tyrrell, Bournemouth University
 Code inspired by http://www.eclipse.org/paho/clients/c/embedded/
 */
+
+#define MQTTCLIENT_QOS2 1

 #include <SPI.h>
 #include <Ethernet2.h>
@@ -22,9 +24,8 @@
 char room[21] = "roman"; //name of room within building

 //MQTT constants
-#define MQTTCLIENT_QOS2 1
 const char* mainTopic = "londonbridge";
-MQTT::QoS qos = MQTT::QOS1;
+MQTT::QoS qos = MQTT::QOS2;
 bool retained = true;

 //Room State
@@ -65,11 +66,22 @@
 	returnCode = ipstack.connect(host, port);
 	//if IP connection successful
 	if (returnCode == 1) {
+		//dynamically set the room's state for will message topic
+		char willTopicBuffer[100];
+		strcpy(willTopicBuffer, mainTopic);
+		strcat(willTopicBuffer, "/");
+		strcat(willTopicBuffer, room);
+		strcat(willTopicBuffer, "/state");
+
 		//initialise MQTT connection data
 		MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
-		data.MQTTVersion = 3;
+		data.willFlag = 1;
+		data.MQTTVersion = 4;
 		data.clientID.cstring = (char*)"sensor-1";
-
+		data.will.topicName.cstring = (char*)willTopicBuffer;
+		data.will.qos = 2;
+		data.will.retained = 1;
+		data.will.message.cstring = (char*)"error";
 		//connect to MQTT broker
 		returnCode = mqttClient.connect(data);
 		//if MQTT connection successful
@@ -96,7 +108,10 @@
 /**
 Publishes a message to the MQTT Broker
 */
-int publishToBroker(char topic[11], char message[11]) {
+void publishToBroker(char topic[11], char message[11]) {
+	//turn on send LED
+	digitalWrite(leds[3], HIGH);
+
 	//initialise variables
 	char topicBuffer[100];
 	char messageBuffer[100];
@@ -121,18 +136,27 @@
 	Serial.print("Message: ");
 	Serial.println((char*)payload);
 	int returnCode = mqttClient.publish(topicBuffer, payload, payloadlen, qos, retained);
-	return returnCode;
+	//if message publish not successful, error has occured
+	//report an error until board restarted and problem fixed
+	while (returnCode != 0) {
+		//turn off state LEDs
+		for (int i = 0; i < numLeds - 1; i++) {
+			digitalWrite(leds[i], LOW);
+		}
+		//flash send LED twice a second
+		digitalWrite(leds[3], HIGH);
+		delay(250);
+		digitalWrite(leds[3], LOW);
+		delay(250);
+	}
+	//turn off send LED
+	digitalWrite(leds[3], LOW);
 }

 /**
 Sets the current state of the room
 */
 void setRoomState() {
-	//initialise variable
-	int returnCode = -1;
-
-	//turn on send LED
-	digitalWrite(leds[3], HIGH);
 	//if new state is equal to current state
 	if (newRoomState == currentRoomState) {
 		//turn off state LEDs
@@ -141,7 +165,7 @@
 		}
 		//set current state to inactive
 		currentRoomState = INACTIVE;
-		returnCode = publishToBroker("state", "inactive");
+		publishToBroker("state", "inactive");
 	}
 	//else if emergency button pressed
 	else if (newRoomState == EMERGENCY) {
@@ -152,7 +176,7 @@
 		digitalWrite(leds[2], HIGH);
 		//set current state to emergency
 		currentRoomState = EMERGENCY;
-		returnCode = publishToBroker("state", "emergency");
+		publishToBroker("state", "emergency");
 	}
 	//else if caution button pressed
 	else if (newRoomState == CAUTION) {
@@ -163,7 +187,7 @@
 		digitalWrite(leds[1], HIGH);
 		//set current state to caution
 		currentRoomState = CAUTION;
-		returnCode = publishToBroker("state", "caution");
+		publishToBroker("state", "caution");
 	}
 	//else if active button pressed
 	else if (newRoomState == ACTIVE) {
@@ -174,23 +198,8 @@
 		digitalWrite(leds[0], HIGH);
 		//set current state to active
 		currentRoomState = ACTIVE;
-		returnCode = publishToBroker("state", "active");
-	}
-	//if message publish not successful, error has occured
-	//report an error until board restarted and problem fixed
-	while (returnCode != 0) {
-		//turn off state LEDs
-		for (int i = 0; i < numLeds - 1; i++) {
-			digitalWrite(leds[i], LOW);
-		}
-		//flash send LED twice a second
-		digitalWrite(leds[3], HIGH);
-		delay(250);
-		digitalWrite(leds[3], LOW);
-		delay(250);
-	}
-	//turn off send LED
-	digitalWrite(leds[3], LOW);
+		publishToBroker("state", "active");
+	}
 }

 /**


Addition de l'autostabilisation

Addition de l'autostabilisation

j'ai deplace la definition du setpoint en dehors de la boucle PID pour pouvoir calculer le setpoint autostabilise

--- Firmware/R2-Quadcopter/R2-Quadcopter.ino
+++ Firmware/R2-Quadcopter/R2-Quadcopter.ino
@@ -15,15 +15,15 @@
 // PID
 bool auto_stabilisation_mode = false; // Activer ou pas le mode auto-stabilisé
 int dt = 3;
-float pid_roll_out,   pid_roll_setpoint,  roll_error, Proportional_roll,  Integral_roll,  Derivative_roll,  last_roll_error, AS_roll_error, AS_Integral_roll, AS_Derivative_roll, AS_last_roll_error = 0;
-float pid_pitch_out,  pid_pitch_setpoint, pitch_error, Proportional_pitch, Integral_pitch, Derivative_pitch, last_pitch_error, AS_pitch_error, AS_Integral_pitch, AS_Derivative_pitch, AS_last_pitch_error = 0;
+float pid_roll_out,   pid_roll_setpoint,  roll_error, Proportional_roll,  Integral_roll,  Derivative_roll,  last_roll_error, roll_angle_adjust = 0;
+float pid_pitch_out,  pid_pitch_setpoint, pitch_error, Proportional_pitch, Integral_pitch, Derivative_pitch, last_pitch_error, pitch_angle_adjust = 0;
 float pid_yaw_out,    pid_yaw_setpoint,   yaw_error,  Proportional_yaw,   Integral_yaw,   Derivative_yaw,   last_yaw_error = 0;

 // MOTORS
 int motorFR, motorBL, motorFL, motorBR;

 // RX
-int throttle = THROTTLE_RMIN;
+int throttle;
 volatile int input0, input1, input2, input3, input4;
 volatile unsigned long chrono_start0, chrono_start1, chrono_start2, chrono_start3, chrono_start4;
 volatile int last_interrupt_time0, last_interrupt_time1, last_interrupt_time2, last_interrupt_time3, last_interrupt_time4;
@@ -117,10 +117,6 @@
 void pid_compute() {

   //ROLL calculations
-  pid_roll_setpoint = 0;
-  if (input0 > THROTTLE_RMID + 10)pid_roll_setpoint = (input0 - THROTTLE_RMID + 10) / 2.0;
-  else if (input0 < THROTTLE_RMID - 10)pid_roll_setpoint = (input0 - THROTTLE_RMID - 10) / 2.0;
-
   roll_error = roll_speed - pid_roll_setpoint;

   Proportional_roll = ROLL_PID_KP * roll_error;
@@ -137,10 +133,6 @@

   //PITCH calculations
-  pid_pitch_setpoint = 0;
-  if (input1 > THROTTLE_RMID + 10)pid_pitch_setpoint = (input1 - THROTTLE_RMID + 10) / 2.0;
-  else if (input1 < THROTTLE_RMID - 10)pid_pitch_setpoint = (input1 - THROTTLE_RMID - 10) / 2.0;
-
   pitch_error = pitch_speed - pid_pitch_setpoint;

   Proportional_pitch = PITCH_PID_KP * pitch_error;
@@ -156,6 +148,7 @@
   last_pitch_error = pitch_error;

   //YAW calculations
+  //On calcule le setpoint du yaw ici car il est le meme en stabilise ou en acro
   pid_yaw_setpoint = 0;
   if (input3 > THROTTLE_RMID + 10)pid_yaw_setpoint = (input3 - THROTTLE_RMID + 10) / 2.0;
   else if (input3 < THROTTLE_RMID - 10)pid_yaw_setpoint = (input3 - THROTTLE_RMID - 10) / 2.0;
@@ -271,15 +264,15 @@
   attachInterrupt(A3, calcSignal4, CHANGE);

   //Motors init
-  esc_1.attach(MOTOR_PIN_FRONT_RIGHT, 1000, 2000);
-  esc_2.attach(MOTOR_PIN_FRONT_LEFT, 1000, 2000);
-  esc_3.attach(MOTOR_PIN_BACK_LEFT, 1000, 2000);
-  esc_4.attach(MOTOR_PIN_BACK_RIGHT, 1000, 2000);
-
-  esc_1.writeMicroseconds(1000);
-  esc_2.writeMicroseconds(1000);
-  esc_3.writeMicroseconds(1000);
-  esc_4.writeMicroseconds(1000);
+  esc_1.attach(MOTOR_PIN_FRONT_RIGHT, MOTOR_ZERO_LEVEL, MOTOR_MAX_LEVEL);
+  esc_2.attach(MOTOR_PIN_FRONT_LEFT, MOTOR_ZERO_LEVEL, MOTOR_MAX_LEVEL);
+  esc_3.attach(MOTOR_PIN_BACK_LEFT, MOTOR_ZERO_LEVEL, MOTOR_MAX_LEVEL);
+  esc_4.attach(MOTOR_PIN_BACK_RIGHT, MOTOR_ZERO_LEVEL, MOTOR_MAX_LEVEL);
+
+  esc_1.writeMicroseconds(MOTOR_ZERO_LEVEL);
+  esc_2.writeMicroseconds(MOTOR_ZERO_LEVEL);
+  esc_3.writeMicroseconds(MOTOR_ZERO_LEVEL);
+  esc_4.writeMicroseconds(MOTOR_ZERO_LEVEL);

   Proportional_roll, Integral_roll, Derivative_roll = 0;
   Proportional_pitch, Integral_pitch, Derivative_pitch = 0;
@@ -298,37 +291,67 @@
     roll_speed = gyroscope.x() * 180 / pi;
     pitch_speed = gyroscope.y() * 180 / pi;
     yaw_speed = gyroscope.z() * 180 / pi;
+  //Setpoints calcules en deg/sec
+  //il sera de 0 quand le stick est au milieu
+    pid_roll_setpoint = 0;
+    if (input0 > THROTTLE_RMID + 10)pid_roll_setpoint = (input0 - THROTTLE_RMID + 10)/3.0;
+    else if (input0 < THROTTLE_RMID - 10)pid_roll_setpoint = (input0 - THROTTLE_RMID - 10)/3.0;
+
+    pid_pitch_setpoint = 0;
+    if (input1 > THROTTLE_RMID + 10)pid_pitch_setpoint = (input1 - THROTTLE_RMID + 10)/3.0;
+    else if (input1 < THROTTLE_RMID - 10)pid_pitch_setpoint = (input1 - THROTTLE_RMID - 10)/3.0;
+
   } else {
     imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
     roll_angle = euler.z();
     pitch_angle = euler.y();
     yaw_angle = euler.x();
-  }
-
+
+    //On transforme l'angle pour le soustraire au setpoint
+    roll_angle_adjust = roll_angle * 15;//la constante multipliee est a ajuster selon l'angle maximal que l'on veut
+    pitch_angle_adjust = pitch_angle *15;
+
+    //On definit setpoint qui avec un stick au milieu sera de 0
+    pid_roll_setpoint = 0;
+    if (input0 > THROTTLE_RMID + 10)pid_roll_setpoint = input0 - THROTTLE_RMID + 10;
+    else if (input0 < THROTTLE_RMID - 10)pid_roll_setpoint = input0 - THROTTLE_RMID - 10;
+
+    pid_roll_setpoint -= roll_angle_adjust;            //On soustrait roll adjust pour que le setpoint soit change avec langle
+    pid_roll_setpoint /= 3;                           //pour avoir des angles en deg
+
+    //////////////On procede de la meme maniere pour pitch/////////////////
+    pid_pitch_setpoint = 0;
+    if (input1 > THROTTLE_RMID + 10)pid_pitch_setpoint = input1 - THROTTLE_RMID + 10;
+    else if (input1 < THROTTLE_RMID - 10)pid_pitch_setpoint = input1 - THROTTLE_RMID - 10;
+
+    pid_pitch_setpoint -= pitch_angle_adjust;
+    pid_pitch_setpoint /= 3;
+  }

   //MOTORS
-  throttle = map(input2, THROTTLE_RMIN, THROTTLE_RMAX, MOTOR_ZERO_LEVEL, MOTOR_MAX_LEVEL);
+  throttle = input2;
   //PID
   pid_compute();

   ///ARM switch
   if (input4 > 1500) {
+    if(throttle > THROTTLE_WMAX)throttle = THROTTLE_WMAX;//Afin de laisser un peu de controlle meme en full throttle .ca fait 1850
     motorFR = throttle + pid_pitch_out + pid_roll_out - pid_yaw_out;
-    if (motorFR > 2000) motorFR = 2000;
-    else if (motorFR < 1000) motorFR = 1000;
+    if (motorFR > MOTOR_MAX_LEVEL) motorFR = MOTOR_MAX_LEVEL;
+    else if (motorFR < MOTOR_ZERO_LEVEL) motorFR = MOTOR_ARM_START;//histoire que les moteurs tournent quand meme quand on arme

     motorFL = throttle + pid_pitch_out - pid_roll_out + pid_yaw_out;
-    if (motorFL > 2000) motorFL = 2000;
-    else if (motorFL < 1000) motorFL = 1000;
+    if (motorFL > MOTOR_MAX_LEVEL) motorFL = MOTOR_MAX_LEVEL;
+    else if (motorFL < MOTOR_ZERO_LEVEL) motorFL = MOTOR_ARM_START;//histoire que les moteurs tournent quand meme quand on arme

     motorBL = throttle - pid_pitch_out - pid_roll_out - pid_yaw_out;
-    if (motorBL > 2000) motorBL = 2000;
-    else if (motorBL < 1000) motorBL = 1000;
+    if (motorBL > MOTOR_MAX_LEVEL) motorBL = MOTOR_MAX_LEVEL;
+    else if (motorBL < MOTOR_ZERO_LEVEL) motorBL = MOTOR_ARM_START;//histoire que les moteurs tournent quand meme quand on arme

     motorBR = throttle - pid_pitch_out + pid_roll_out + pid_yaw_out;
-    if (motorBR > 2000) motorBR = 2000;
-    else if (motorBR < 1000) motorBR = 1000;
+    if (motorBR > MOTOR_MAX_LEVEL) motorBR = MOTOR_MAX_LEVEL;
+    else if (motorBR < MOTOR_ZERO_LEVEL) motorBR = MOTOR_ARM_START;//histoire que les moteurs tournent quand meme quand on arme

     esc_1.writeMicroseconds(motorFR);
     esc_2.writeMicroseconds(motorFL);
@@ -350,5 +373,5 @@
   }

   print_rx();
-  delay(4);
-}
+  delay(20);
+}


Benchmarking and debugging, and made chip_size() return total bytes on the board rather than for one chip

--- a3000_rom_emulator/firmware/rom_emulator.ino
+++ a3000_rom_emulator/firmware/rom_emulator.ino
@@ -72,6 +72,12 @@

 // Disable USB serial commands (CPLD programming etc) by commenting this out:
 #define ENABLE_USB_SERIAL
+
+// Uncomment this to disable programming flash (for performance testing)
+// #define DEBUG_DONT_PROGRAM_FLASH
+
+// Uncomment this to fake out fetching data from USB (for performance testing)
+// #define DEBUG_DONT_GET_USB_DATA

 // We have the S29GL064S70DHI010 (S29GL064S 70-ns D-LAE064-BGA-pkg H-halogen/lead-free I-industrial 01-uniform sector 0-tray)
@@ -272,6 +278,7 @@
   Serial.println("OK");
 }

+// Return the number of bytes of flash on this board, i.e. double the byte count of one chip
 uint32_t chip_size() {
   flash_write_both(0x55, 0x0098L);  // Enter CFI mode
   uint32_t size_log2 = flash_read(0x27) & 0xffff;
@@ -280,7 +287,8 @@

   uint32_t size = 1;
   while (size_log2--) size <<= 1;
-  return size;
+
+  return size * 2;  // Double it because we have two flash chips
 }

 // returns true if we're disconnected and have been reset
@@ -296,6 +304,9 @@

 // request bytes from remote; range_start and range_end are word addresses
 bool get_range(uint32_t range_start, uint32_t range_end) {
+#ifdef DEBUG_DONT_GET_USB_DATA
+  return true;
+#endif
   if (check_disconnect()) return false;

   Serial.print(range_start * 4, DEC);
@@ -425,6 +436,7 @@
     }

     Serial.println("programming sector");
+#ifndef DEBUG_DONT_PROGRAM_FLASH
     for (uint32_t chunk_start = start_addr;
          chunk_start < start_addr + SECTOR_SIZE;
          chunk_start += CHUNK_SIZE) {
@@ -456,7 +468,7 @@
         }
         flash_write_both(program_start, 0x29); // (n+5) Program Buffer to Flash

-        Serial.println("Wait for completion");
+        // Serial.println("Wait for completion");
         // Poll last address written to buffer (program_start + PROGRAM_BLOCK_SIZE - 1), looking at DQ7/6/5/1
         uint32_t poll_comparison_value = read_buf[program_offset + PROGRAM_BLOCK_SIZE-1] & 0x00800080L;  // Compare with DQ7
         // Serial.print("Final word: ");
@@ -538,8 +550,10 @@
         // Block programmed
       }
       // If we got here, the chunk is programmed and we can continue
-      Serial.println("Chunk done");
+      Serial.println("Chunk programmed");
     }
+    Serial.println("Sector programmed");
+#endif // DEBUG_DONT_PROGRAM_FLASH
   }
 }

@@ -568,11 +582,26 @@
   if (Serial.available()) {
     int c = Serial.read();
     switch (c) {
+      case 'B': {
+        // benchmark
+        chip_end = chip_size();
+        chip_end = 512 * 1024;
+        Serial.print("Reading ");
+        Serial.print(chip_end);
+        Serial.println(" bytes from flash...");
+        for (uint32_t addr = 0; addr < chip_end / 4; ++addr) {
+          (void)flash_read(addr);
+        }
+        Serial.println("Done.");
+        reset();
+        break;
+      }
       case 'C': {
         // program CPLD
         Serial.println("SEND SVF");
         arduino_play_svf(TMS_PIN, TDI_PIN, TDO_PIN, TCK_PIN, -1);
         Serial.println("SVF DONE");
+        reset();
         break;
       }
       case 'I': {
@@ -596,7 +625,7 @@

         chip_end = chip_size();
         Serial.print("Size = ");
-        Serial.println(chip_end * 2);  // Because we actually have double this
+        Serial.println(chip_end);

         Serial.println("OK");

@@ -609,8 +638,8 @@
         if (Serial.read() != '\n') break;
         chip_end = chip_size();
         Serial.print("Program whole chip.  Size = ");
-        Serial.println(chip_end * 2);  // Because we actually have double this
-        program_range(0, chip_end / 2);  // Program chip_end/2 words
+        Serial.println(chip_end);
+        program_range(0, chip_end / 4);  // Program chip_end/4 words
         flash_unlock();
         reset();
         break;
@@ -618,16 +647,20 @@
       case 'R': {
         chip_end = chip_size();
         Serial.print("Read whole chip.  Size = ");
-        Serial.println(chip_end * 2);
+        Serial.println(chip_end);
         Serial.print("DATA:");
         // chip_end == number of bytes in a single chip, i.e. 2 * number of words
-        for (uint32_t addr = 0; addr < chip_end / 2; ++addr) {
+        for (uint32_t chunk_start = 0; chunk_start < chip_end / 4; chunk_start += CHUNK_SIZE / 4) {
+          // Read 16kB from flash
+          for (uint32_t offset = 0; offset < CHUNK_SIZE/4; ++offset) {
+            read_buf[offset] = flash_read(chunk_start + offset);
+          }
           // fail gracefully on disconnect
+          uint32_t bytes_to_write = CHUNK_SIZE, bytes_written = 0;
           do {
             if (check_disconnect()) return;
-          } while (!Serial.availableForWrite());
-          // read a byte from flash and send it to the remote host
-          serial_put_uint32(flash_read(addr));
+            bytes_written += Serial.write(((char *)read_buf) + bytes_written, bytes_to_write);
+          } while (bytes_written < bytes_to_write);
         }
         flash_unlock();
         reset();


tweaked DS18B20 code seems to work on REV9

--- COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -1539,7 +1539,7 @@
       // to give the user a decent chance to enter a command string
       // and/or that may involve encryption.
       const uint8_t stopBy = min((OTV0P2BASE::GSCT_MAX/4)*3, nearOverrunThreshold - 1);
-      if(timeToHandleMessage()) { pollCLI(stopBy, 0 == TIME_LSD); }
+      pollCLI(stopBy, 0 == TIME_LSD);
       }
     break;
     }


Updated code for 60s GPS warm up

Updated code for 60s GPS warm up

--- mwsLRWHFv2/mwsLRWHFv2.ino
+++ mwsLRWHFv2/mwsLRWHFv2.ino
@@ -249,8 +249,18 @@

   // turn on interrupts
   interrupts();
-
-  //Serial.println("Weather Shield online!");
+  digitalWrite(STAT1, HIGH); //Blink stat LED 1 second
+  delay(1000);
+  digitalWrite(STAT1, LOW); //Blink stat LED
+  smartdelay(60000); //Wait 60 seconds, and gather GPS data
+  minutes = gps.time.minute();
+  minutes_10m = gps.time.minute();
+  seconds = gps.time.second();
+  lastSecond = millis();
+  digitalWrite(STAT1, HIGH); //Blink stat LED 1 second
+  delay(1000);
+  digitalWrite(STAT1, LOW); //Blink stat LED
+  lcd.print("Weather Station online!");

 }


TW-86: Updated tinywatch.ino to follow Arduino style guidelines.

--- src/tinywatch/tinywatch.ino
+++ src/tinywatch/tinywatch.ino
@@ -4,7 +4,15 @@
   Controls TinyScreen+, BLE Nordic Tinyshield, Proto Board Tinyshield, Li-po Battery 3.7V 270mAh, and DC3V/0.1A 1.5V/0.05A 10x2.7mm Coin Mobile Phone Vibration Motor to work as a smart watch.

   The circuit:
-    * The Vibration Motor or Piezo Element is attached to output pins 5 and 6.
+    * The Proto Tinyshield uses pins:
+    ** 5 and 6 set to output
+    * The BLE Tinyshield uses pins:
+    ** 2-SPI_IRQ: Interupts output from nRF8001 to the tinyscreen+
+    ** 9-BLE_RST: Reset signal to the nRF8001
+    ** 10-SPI_CS: SPI chip select for the nRF8001
+    ** 11-MOSI: SPI data from tinyscreen+ to transceiver
+    ** 12-MISO: SPI data from transceiver to tinyscreen+
+    ** 13-SCLK: Serial SPI clock from tinyscreen+ to tranceiver

 */


added function to update leader, the variable tracking which lane is in the lead

--- Timer.ino
+++ Timer.ino
@@ -30,7 +30,15 @@
   }
 }

-inline void updateLeadre() {
+// Determine who is the current leader
+// The leader, after passing the car detect,
+// will always have the higher lap count
+inline void updateLeader() {
+  if (lap[0] > lap[1]) {
+    leader = 0;
+  } else if (lap[0] < lap[1]) {
+    leader = 1;
+  }
 }

 void timerStop() {


Fix weekly repetition logic...

Fix weekly repetition logic...

... to handle repeats from the day you're already on

--- alarm.ino
+++ alarm.ino
@@ -158,9 +158,9 @@

 static inline time_t next_repeat(time_t time, weekdays_t repetition) {
     enum week_day day = get_week_day(time);
-    for (uint8_t i = day + 1; i != day; i = ((i + 1) % DAYS_PER_WEEK))
-        if (repetition.mask & (1 << i))
-            return time + SECS_PER_DAY * ((i - day) % 7);
+    for (uint8_t i = 1; i != 8; i++)
+        if (repetition.mask & (1 << ((day + i) % DAYS_PER_WEEK)))
+            return time + SECS_PER_DAY * i;
     return day + SECS_PER_DAY;
     // TODO Here, we should find the next geek day! For now, treat geek_day as every_day!
 }


Update 3 e 4

Update 3 e 4

3 e 4

--- SeguidorDeParede.ino
+++ SeguidorDeParede.ino
@@ -57,7 +57,7 @@
 double errSum, lastErr;
 int cons = 15;
 int amostra = 1000; // 1seg
-
+double outMin, outMax;
 void definirErro(int setPoint){

   calcularTempo();
@@ -67,12 +67,17 @@
   if(distancia > 0 && dt >= amostra){
     Serial.println(distancia);
     erro =  setPoint - distancia;
-    if(errSum >= 50){
+   /* if(errSum >= 50){
       errSum = 0;
     }
-    errSum += erro;
+    errSum += erro; faz parte do sample TIME*/
     double dDistancia = (distancia - ultimaDistancia);
-    i = ki * errSum;
+    i += ki * erro; //Tuning Changes
+    if(i > outMax){// +90
+     i = outMax;
+    }else if(i < outMin){ // -90
+     i = outMin;
+    }
     d = kd * dDistancia;
     x = cons + ((erro*kp) - d + i);
     y = cons - ((erro*kp) - d + i);
@@ -85,6 +90,25 @@
     x = 10;
     y = 15;
   }
+}
+
+void SetOutputLimits(double Min, double Max) // RESET WIDNUP
+{
+   if(Min < Max){
+     outMin = Min;
+     outMax = Max;
+   }
+   if(Output > outMax){
+    Output = outMax;
+   }else if(Output < outMin){
+    Output = outMin;
+   }
+
+   if(i > outMax){
+    i = outMax;
+   }else if(i < outMin){
+    i = outMin;
+   }
 }

 void setTunings(double Kp, double Ki , double Kd){


src: make sure to call loop often enough

You need to call loop often enough to let background
work take place

--- MessageWaitingIndicator/MessageWaitingIndicator.ino
+++ MessageWaitingIndicator/MessageWaitingIndicator.ino
@@ -20,6 +20,7 @@
 boolean ledOn;

 void callback(const MQTT::Publish& pub) {
+  Serial.println("publish");
   if(0 == strcmp(pub.payload_string().c_str(), "1")) {
     messageWaiting = true;
   } else {
@@ -42,6 +43,7 @@
   client.set_callback(callback);
 }

+int count = 0;

 void loop() {
   client.loop();
@@ -64,14 +66,16 @@
     }
   }

-  if ((true == messageWaiting) && (false == ledOn)) {
-    digitalWrite(LED_PIN, HIGH);
-    ledOn = true;
-  } else {
-    digitalWrite(LED_PIN, LOW);
-    ledOn = false;
+  count++;
+  if (count >= 50 ) {
+    count = 0;
+    if ((true == messageWaiting) && (false == ledOn)) {
+      digitalWrite(LED_PIN, HIGH);
+      ledOn = true;
+    } else {
+      digitalWrite(LED_PIN, LOW);
+      ledOn = false;
+    }
   }
-
-  delay(BLINK_INTERVAL_SECONDS * 1000);
-
+  delay(BLINK_INTERVAL_SECONDS * 1000/50);
 }


Improve clock cal for STM32L0 in compliance sketch

--- examples/compliance-otaa-halconfig/compliance-otaa-halconfig.ino
+++ examples/compliance-otaa-halconfig/compliance-otaa-halconfig.ino
@@ -631,7 +631,7 @@
     LMIC_reset();

     // set clock rate error to 0.1%
-    LMIC_setClockError(1 * MAX_CLOCK_ERROR / 1000);
+    //LMIC_setClockError(1 * MAX_CLOCK_ERROR / 1000);

     // do the network-specific setup prior to join.
     setupForNetwork(false);
@@ -967,20 +967,20 @@
     CalibLow = 0;
     CalibHigh = 0;
     mSecondLow = 0;
-    mSecondHigh = 2000;
+    mSecondHigh = 2000000;
     fHaveSeenLow = fHaveSeenHigh = false;

     /* loop until we have a new value */
     do	{
         /* meassure the # of millis per RTC second */
-        mSecond = MeasureMillisPerRtcSecond();
+        mSecond = MeasureMicrosPerRtcSecond();

         /* invariant: */
         if (Calib == CalibNew)
             mSecondNew = mSecond;

         /* if mSecond is low, this meaans we must increase the system clock */
-        if (mSecond <= 1000)
+        if (mSecond <= 1000000)
             {
             Serial.print('-');
             /*
@@ -1098,6 +1098,7 @@

     if (CalibNew != Calib)
         {
+        Serial.print(CalibNew < Calib ? '+' : '-');
         if (fCalibrateMSI)
             {
             __HAL_RCC_MSI_CALIBRATIONVALUE_ADJUST(CalibNew);
@@ -1109,11 +1110,13 @@
         delay(500);
         }

+    Serial.print(" 0x");
+    Serial.println(CalibNew, HEX);
     return CalibNew;
     }

 uint32_t
-MeasureMillisPerRtcSecond(
+MeasureMicrosPerRtcSecond(
     void
     )
     {
@@ -1128,7 +1131,7 @@
     /* wait for a new second to start, and capture millis() in start */
     do	{
         now = RTC->TR & (RTC_TR_ST | RTC_TR_SU);
-        start = millis();
+        start = micros();
         } while (second == now);

     /* update our second of interest */
@@ -1140,7 +1143,7 @@
     /* wait for the next second to start, and capture millis() */
     do	{
         now = RTC->TR & (RTC_TR_ST | RTC_TR_SU);
-        end = millis();
+        end = micros();
         } while (second == now);

     /* return the delta */


Displaying temperature.

Displaying temperature.

--- TempControl.ino
+++ TempControl.ino
@@ -7,7 +7,7 @@
 #include <DHT.h>

 // Constants
-#define DHTPIN  7         // Temperature Sense pin
+#define DHTPIN  2         // Temperature Sense pin
 #define DHTTYPE DHT11     // DHT 11
 DHT dht(DHTPIN, DHTTYPE); // Initialize DHT Sensor

@@ -15,17 +15,83 @@
 float hum;  // Humidity
 float temp; // Temperature

+// Turn off temperature indicator by default.
+int sensorState = LOW;
+int oneState = HIGH;
+int tenState = HIGH;
+
+// Variable to store current time.
+unsigned long previousMillis = 0;
+
+// Set interval to read temperature.
+const long interval = 2000;
+
+// LED pins
+const int segmentA = 3;
+const int segmentB = 4;
+const int segmentE = 5;
+const int segmentD = 6;
+const int segmentC = 7;
+const int segmentG = 8;
+const int segmentP = 9;
+const int segmentF = 10;
+const int displayOnes = 11;
+const int displayTens = 12;
+
 void setup()
 {
-    Serial.begin(9600);
-    dht.begin();
+  Serial.begin(9600);
+  dht.begin();
+
+  // Set display pins.
+  pinMode(segmentA, OUTPUT);
+  pinMode(segmentB, OUTPUT);
+  pinMode(segmentC, OUTPUT);
+  pinMode(segmentD, OUTPUT);
+  pinMode(segmentE, OUTPUT);
+  pinMode(segmentF, OUTPUT);
+  pinMode(segmentG, OUTPUT);
+
+  // Set digits.
+  pinMode(displayOnes, OUTPUT);
+  pinMode(displayTens, OUTPUT);
+}
+
+void displayTemp(float temp)
+{
+  digitalWrite(segmentA, LOW);
+  digitalWrite(segmentB, LOW);
+  digitalWrite(segmentC, HIGH);
+  digitalWrite(segmentD, LOW);
+  digitalWrite(segmentE, LOW);
+  digitalWrite(segmentF, HIGH);
+  digitalWrite(segmentG, LOW);
+  digitalWrite(segmentP, HIGH);
 }

 void loop()
 {
-    // Wait a few seconds between measurements.
-    delay(2000);
-
+  unsigned long currentMillis = millis();
+
+  if (currentMillis - previousMillis >= interval) {
+    // Save the last time we've read the temperature.
+    previousMillis = currentMillis;
+
+    // Turn temperature indicator on and off.
+    if (sensorState == LOW) {
+      sensorState = HIGH;
+      oneState = HIGH;
+      tenState = LOW;
+    } else {
+      sensorState = LOW;
+      oneState = LOW;
+      tenState = HIGH;
+    }
+
+    // Toggle digits.
+    digitalWrite(displayOnes, oneState);
+    digitalWrite(displayTens, oneState);
+
     // Read data and store it to variables hum and temp.
     hum = dht.readHumidity();
     temp= dht.readTemperature();
@@ -36,5 +102,9 @@
     Serial.print(" %, Temp: ");
     Serial.print(temp);
     Serial.print(" *C\n");
+  }
+
+  // Display temperature.
+  displayTemp(temp);
 }


The SD card example run on Arduino Uno with a history size of 200 now we use integer and not float for each history array cell

--- examples/SdCardCsvLogger/SdCardCsvLogger.ino
+++ examples/SdCardCsvLogger/SdCardCsvLogger.ino
@@ -1,5 +1,5 @@
  // You can change here the history length to reduce the memory footprint.
-#define HISTORY_LENGTH 150
+#define HISTORY_LENGTH 200
 #include "RadiationWatch.h"
 #include <SD.h>
 #include <SPI.h>


Fixed

Fixed

--- Garduino.ino
+++ Garduino.ino
@@ -16,16 +16,16 @@
  */

 // Libraries
-#include <DHT.h> // DHT library
-#include <DHT_U.h> // DHT 11 & 22 detecting library
-#include <Servo.h> // Servo library
+#include <DHT.h>    // DHT library
+#include <DHT_U.h>  // DHT 11 & 22 detecting library
+#include <Servo.h>  // Servo library
 // Wi-Fi network identification
-#define ssid "SSID" // Your Wi-Fi SSID
-#define pass "Pass" // Your Wi-Fi password
-#define IP "184.106.153.149"    // thingspeak.com IP address
+#define ssid "SSID"            // Your Wi-Fi SSID
+#define pass "Pass"            // Your Wi-Fi password
+#define IP "184.106.153.149"   // thingspeak.com IP address

 // DHT Sensor
-#define DHTPIN 2 // DHT to Arduino Digital 2 / DHT sensörü 2. pine bağlı
+#define DHTPIN 2  // DHT to Arduino Digital 2 / DHT sensörü 2. pine bağlı
 #define DHTTYPE DHT11
 DHT dht(DHTPIN, DHTTYPE);


Account for millis() rollover.

Account for millis() rollover.

--- aquacontrol2.ino
+++ aquacontrol2.ino
@@ -243,7 +243,7 @@
 }

 void loop() {
-  if ( numberOfSensors > 0 && nextDallasUpdate <= millis() ) {
+  if ( numberOfSensors > 0 && (long)(millis() - nextDallasUpdate ) >= 0 ) {
     updateDallasTemperature();
   }


Don't save WiFi state information to flash.

--- aquacontrol2.ino
+++ aquacontrol2.ino
@@ -71,6 +71,7 @@
 Ticker channelUpdateTimer;

 void setup() {
+  WiFi.persistent( false );
   system_update_cpu_freq( 160 );
   analogWriteRange( PWMdepth );


compiled anna.ino @ 4K

compiled anna.ino @ 4K

--- arduino/anna.ino
+++ arduino/anna.ino
@@ -2,85 +2,93 @@
 enum ActType{
   linear = 0, sigmoid, tangenth, none, bias };

+
 template <class T>
-T actBias( T n )
+class funcs
 {
-  return (T)1.0;
-}
-
-template <typename T>
-T actNone( T n )
-{
-  return n;
-}
-
-template <typename T>
-T actLinear( T n )
-{
-  return n;
-}
-
-
-template <typename T>
-T actSigmoid( T n )
-{
-  return 1.0 / ( 1.0 + exp(-n) );
-}
-
-
-template <typename T>
-T derivLinear( T n )
-{
-  return 1.0;
-}
-
-
-template <typename T>
-T derivSigmoid( T n )
-{
-  return n * ( 1.0 - n );
-}
-
-
-
-template<class T>
-class vector
-{
-  T _vec;
-  int _sz;
-  int _trk;
-
+  public:
+  static T actBias( T n )
+  {
+    return 1.0;
+  }
+
+  static T actNone( T n )
+  {
+    return n;
+  }
+
+  static T actLinear( T n )
+  {
+    return n;
+  }
+
+  static T actSigmoid( T n )
+  {
+    return 1.0 / ( 1.0 + exp(-n) );
+  }
+
+  static T derivLinear( T n )
+  {
+    return 1.0;
+  }
+
+  static T derivSigmoid( T n )
+  {
+    return n * ( 1.0 - n );
+  }
+};
+
+
+// Minimal class to replace std::vector
+template<class Data>
+class Vector {
+  size_t d_size; // Stores no. of actually stored objects
+  size_t d_capacity; // Stores allocated capacity
+  Data *d_data; // Stores data
 public:
-  vector(int sz=10) :
-  _sz(sz), _trk(0) {
-    _vec = malloc( sizeof(T) * sz );
-  };
-  ~vector(){
-    free(_vec);
-  };
-  void push_back( T p )
-  {
-    ((T)(_vec+_trk)) = p;
-    _trk++;
-    if( _trk > _sz )
-    {
-      _sz+=10;
-      _vec = realloc( _vec, sizeof(T) * _sz );
-    }
-  };
-  T operator[](int i){
-    return _vec+i;
-  };
-
-  boolean empty() {
-    return _trk == 0;
-  };
-  int size() {
-    return _trk;
-  };
-
-
+  Vector() :
+  d_size(0), d_capacity(0), d_data(0) {
+  }; // Default constructor
+  Vector(Vector const &other) :
+  d_size(other.d_size), d_capacity(other.d_capacity), d_data(0) {
+    d_data = (Data *)malloc(d_capacity*sizeof(Data));
+    memcpy(d_data, other.d_data, d_size*sizeof(Data));
+  }; // Copy constuctor
+  ~Vector() {
+    free(d_data);
+  }; // Destructor
+  Vector &operator=(Vector const &other) {
+    free(d_data);
+    d_size = other.d_size;
+    d_capacity = other.d_capacity;
+    d_data = (Data *)malloc(d_capacity*sizeof(Data));
+    memcpy(d_data, other.d_data, d_size*sizeof(Data));
+    return *this;
+  }; // Needed for memory management
+  void push_back(Data const &x) {
+    if (d_capacity == d_size) resize();
+    d_data[d_size++] = x;
+  }; // Adds new value. If needed, allocates more space
+  size_t size() const {
+    return d_size;
+  }; // Size getter
+  Data const &operator[](size_t idx) const {
+    return d_data[idx];
+  }; // Const getter
+  Data &operator[](size_t idx) {
+    return d_data[idx];
+  }; // Changeable getter
+private:
+  void resize() {
+    d_capacity = d_capacity ? d_capacity*2 : 1;
+    Data *newdata = (Data *)malloc(d_capacity*sizeof(Data));
+    memcpy(newdata, d_data, d_size * sizeof(Data));
+    free(d_data);
+    d_data = newdata;
+  };// Allocates double the old space
 };
+
+

 template<typename T>
 class Node
@@ -94,7 +102,7 @@

   class Connection;

-  vector<Connection*> conns, inConns;
+  Vector<Connection*> conns, inConns;

   bool _activate;

@@ -194,7 +202,7 @@
 {
 public:

-  vector<Node<T>*> nodes;
+  Vector<Node<T>*> nodes;

   Layer<T>* prevLayer;
   Layer<T>* nextLayer;
@@ -213,9 +221,7 @@

   T sumIn;

-  String _name;
-
-  Layer( int n, int act, bool bias )
+  Layer( int n, ActType act, bool bias )
 :
     count(n), prevLayer(NULL), nextLayer(NULL), _activation(act), _bias(bias),
     sumIn(0.0)
@@ -223,13 +229,13 @@

       if( act == linear )
       {
-        _actFunc = actLinear;
-        _derivActFunc = derivLinear;
+        _actFunc = funcs<T>::actLinear;
+        _derivActFunc = funcs<T>::derivLinear;
       }
       else if( act == sigmoid )
       {
-        _actFunc = actSigmoid;
-        _derivActFunc = derivSigmoid;
+        _actFunc = funcs<T>::actSigmoid;
+        _derivActFunc = funcs<T>::derivSigmoid;
       }
       /*
       else if( act == tangenth )
@@ -240,8 +246,8 @@
        */
       else if( act == none )
       {
-        _actFunc = actNone;
-        _derivActFunc = actNone;
+        _actFunc = funcs<T>::actNone;
+        _derivActFunc = funcs<T>::actNone;
       }

       for( int i=0; i < count; i++ )
@@ -251,7 +257,7 @@

       if( bias == true )
       {
-        nodes.push_back( new Node<T>( actBias, true ) );
+        nodes.push_back( new Node<T>( funcs<T>::actBias, true ) );
       }
     }

@@ -269,7 +275,7 @@
     }
   }

-  T calcError( vector<T> &targets )
+  T calcError( Vector<T> &targets )
   {
     T netErr = (T)0.0, delta;
     // minus bias
@@ -305,7 +311,7 @@
     return sum;
   }

-  void calcGradient( vector<T> &targets )
+  void calcGradient( Vector<T> &targets )
   {
     if( nextLayer == NULL )	 // output layer
     {
@@ -399,11 +405,13 @@
   T _momentum;
   Layer<T> *_inLayer, *_outLayer;

-  vector<Layer<T>*> layers;
-
-  vector<T> vecBackPrepTargets;
-
-  NeuralNet( T learn_rate = 0.0001, T momentum = 0.001 )
+  Vector<Layer<T>*> layers;
+
+  Vector<T> vecBackPrepTargets;
+
+public:
+
+  NeuralNet( T learn_rate = 0.01, T momentum = 0.0001 )
 :
     _learnRate( learn_rate ), _momentum( momentum )
     {
@@ -525,4 +533,21 @@
 };

-
+NeuralNet<double> nn( 0.05, 0.0001 );
+
+void setup()
+{
+  nn.addLayer( 2, linear, bias );
+  nn.addLayer( 2, sigmoid, bias );
+  nn.addLayer( 1, linear, bias );
+
+}
+
+
+void loop()
+{
+
+
+}
+
+


Update tin_counter.ino

Update tin_counter.ino

--- tin_counter/tin_counter.ino
+++ tin_counter/tin_counter.ino
@@ -1,74 +1,71 @@
-/*
-HC-SR04 Ping distance sensor]
-VCC to arduino 5v GND to arduino GND
-Echo to Arduino pin 13 Trig to Arduino pin 12
-Red POS to Arduino pin 11
-Green POS to Arduino pin 10
-560 ohm resistor to both LED NEG and GRD power rail
-More info at: http://goo.gl/kJ8Gl
-Original code improvements to the Ping sketch sourced from Trollmaker.com
-Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
-*/
-
-#define trigPin 13
-#define echoPin 12
-#define green 11
-#define red 10
-int count = 0;
-int withoutLabel;
-void setup() {
-  Serial.begin (9600);
-  pinMode(trigPin, OUTPUT);
-  pinMode(echoPin, INPUT);
-  pinMode(green, OUTPUT);
-  pinMode(red, OUTPUT);
-  pinMode(withoutLabel, OUTPUT);
-  pinMode(9, OUTPUT);
-  beep(50);
-  beep(50);
-  delay(1000);
-}
-
-void loop() {
-  long duration, distance;
-  digitalWrite(trigPin, LOW);  // Added this line
-  delayMicroseconds(2); // Added this line
-  digitalWrite(trigPin, HIGH);//  delayMicroseconds(1000); - Removed this line
-  delayMicroseconds(10); // Added this line
-  digitalWrite(trigPin, LOW);
-  duration = pulseIn(echoPin, HIGH);
-  distance = (duration/2) / 29.1;
-  if (distance < 12) {  // This is where the count happens
-  count = count +1;
-  Serial.println(count);
-  delay (500);
-   }
-   if(count%4==0) {
-digitalWrite(green, HIGH);
-delay (500);
-digitalWrite(green, LOW);
-
-   }
-   int contact = analogRead(A0); //reading the voltage on pin A0, to know whether a can is in contact or not
- Serial.println(contact); //prints the value of the contact on the serial monitor(on screen)\
-
-  delay(100);
-  if(contact == 0){
-    digitalWrite(red,HIGH);//red led on
-    delay (500); //delay for half a second
-    digitalWrite(red,  LOW); //turn off led
-    beep (200);
-    }
-
-
-}
-
-
-void beep(unsigned char delayms){
-  analogWrite(9, 50);      // Almost any value can be used except 0 and 255
-                           // experiment to get the best tone
-  delay(delayms);          // wait for a delayms ms
-  analogWrite(9, 0);       // 0 turns it off
-  delay(delayms);          // wait for a delayms ms
-}
+/*
+HC-SR04 Ping distance sensor]
+VCC to arduino 5v GND to arduino GND
+Echo to Arduino pin 13 Trig to Arduino pin 12
+Red POS to Arduino pin 11
+Green POS to Arduino pin 10
+560 ohm resistor to both LED NEG and GRD power rail
+*/

+#define trigPin 13
+#define echoPin 12
+#define green 11
+#define red 10
+int count = 0;
+int withoutLabel;
+void setup() {
+  Serial.begin (9600);
+  pinMode(trigPin, OUTPUT);
+  pinMode(echoPin, INPUT);
+  pinMode(green, OUTPUT);
+  pinMode(red, OUTPUT);
+  pinMode(withoutLabel, OUTPUT);
+  pinMode(9, OUTPUT);
+  beep(50);
+  beep(50);
+  delay(1000);
+}
+
+void loop() {
+  long duration, distance;
+  digitalWrite(trigPin, LOW);  // Added this line
+  delayMicroseconds(2); // Added this line
+  digitalWrite(trigPin, HIGH);//  delayMicroseconds(1000); - Removed this line
+  delayMicroseconds(10); // Added this line
+  digitalWrite(trigPin, LOW);
+  duration = pulseIn(echoPin, HIGH);
+  distance = (duration/2) / 29.1;
+  if (distance < 12) {  // This is where the count happens
+  count = count +1;
+  Serial.println(count);
+  delay (500);
+   }
+   if(count%4==0) {
+digitalWrite(green, HIGH);
+delay (500);
+digitalWrite(green, LOW);
+
+   }
+   int contact = analogRead(A0); //reading the voltage on pin A0, to know wether a can is in contact or not
+ Serial.println(contact); //prints the value of the contact on the serial monitor(on screen)\
+
+  delay(100);
+  if(contact == 0){
+    digitalWrite(red,HIGH);//red led on
+    delay (500); //delay for half a second
+    digitalWrite(red,  LOW); //turn off led
+    beep (200);
+    }
+
+
+}
+
+
+void beep(unsigned char delayms){
+  analogWrite(9, 50);      // Almost any value can be used except 0 and 255
+                           // experiment to get the best tone
+  delay(delayms);          // wait for a delayms ms
+  analogWrite(9, 0);       // 0 turns it off
+  delay(delayms);          // wait for a delayms ms
+}
+


adding Average.h

adding Average.h

--- _08_hc-sr04/_08_hc-sr04.ino
+++ _08_hc-sr04/_08_hc-sr04.ino
@@ -1,3 +1,5 @@
+#include <Average.h>
+
 #define Trig_pin 4

 volatile unsigned long echoBufferx[2];
@@ -6,8 +8,7 @@
 volatile unsigned int x = 0;
 volatile unsigned int y = 0;

-int distancex ;
-int distancey ;
+Average<float> ave(5);

 void setup() {
   Serial.begin (38400);
@@ -16,9 +17,13 @@
   pinMode(3, INPUT_PULLUP);
 }

-void check_distance() {
+long check_distance() {
+
   x = 0 ;
   y = 0 ;
+
+  int distancex = 0;
+  int distancey = 0;

   for ( int i = 0 ; i < 2 ; i++ ) {
     echoBufferx[i] = 0;
@@ -35,38 +40,43 @@
   digitalWrite(Trig_pin, HIGH);
   delayMicroseconds(10);
   digitalWrite(Trig_pin, LOW);
-
+
   delay(300);
-
-/*
-  Serial.println( echoBufferx[0] );
-  Serial.println( echoBufferx[1] );
-*/

   if ( echoBufferx[1] > echoBufferx[0]   ) {
     distancex = ( echoBufferx[1] - echoBufferx[0] ) / 29 / 2 ;
   } else {
-    distancex = 0 ;
+    distancex = 1000 ;
   }

   if ( echoBuffery[1] > echoBuffery[0]  ) {
-    distancey = ( echoBuffery[1] - echoBuffery[0] ) / 29 / 2 ;
+     distancey = ( echoBuffery[1] - echoBuffery[0] ) / 29 / 2 ;
   } else {
-    distancey = 0;
+    distancey = 1000;
   }

   detachInterrupt(0);
   detachInterrupt(1);
+
+  if ( distancex >= distancey ) {
+    return distancey;
+  } else {
+    return distancex;
+  }
+
 }

 void loop() {

-  check_distance();
-
-  Serial.print("distance X : ");
-  Serial.print(distancex);
-  Serial.print(" : distance Y : ");
-  Serial.println(distancey);
+  int distance = check_distance();
+  ave.push(distance);
+
+  Serial.print("distance : ");
+  Serial.print(distance);
+  Serial.print(" ave.mean : ");
+  Serial.print(int(ave.mean()));
+  Serial.print(" ave.stddev : ");
+  Serial.println(int(ave.stddev()));

   delay(1000); // pause 5 secs
 }


added varable to change the delay between sending packets - suspected we were flooding the buffer. massive improvement at 100ms :D bed time...

--- arduino/arduino_md03_v_5_0/arduino_md03_v_5_0.ino
+++ arduino/arduino_md03_v_5_0/arduino_md03_v_5_0.ino
@@ -5,6 +5,7 @@
 //settings:
 const float referenceVolts = 5.5; //set the refrence multiplyer for the volt meter
 unsigned long previousBattCheck = 10000;
+const int send_delay = 100; //delay between sending packets

 //#define DEBUG 1
 #define DEBUG
@@ -141,7 +142,7 @@
   //direct2 = manualSpeedControl(motorPinSpeed2, potPin2, rlyPin2, motorPinDir2, direct2, speedControl2);
   //direct3 = manualSpeedControl(motorPinSpeed3, potPin3, rlyPin3, motorPinDir3, direct3, speedControl3);

-  if (millis() - send_time >= 10) {
+  if (millis() - send_time >= send_delay) {
     send_time = millis();
     send_status();
   }


Fixed slave address determination code

Fixed slave address determination code

--- I2CTest/I2CTest_Slave/I2CTest_Slave.ino
+++ I2CTest/I2CTest_Slave/I2CTest_Slave.ino
@@ -13,8 +13,10 @@
 int my_address = 0;

 void setup() {
-  pinMode(PIN_ADDRESS_BIT0, INPUT);
-  pinMode(PIN_ADDRESS_BIT1, INPUT);
+  Serial.begin(9600);
+
+  pinMode(PIN_ADDRESS_BIT0, INPUT_PULLUP);
+  pinMode(PIN_ADDRESS_BIT1, INPUT_PULLUP);
   if (my_address == 0) {
     if (digitalRead(PIN_ADDRESS_BIT0) == HIGH) my_address |= 0x1;
     if (digitalRead(PIN_ADDRESS_BIT1) == HIGH) my_address |= 0x2;
@@ -35,7 +37,14 @@
 void loop() {
   if (led_on) digitalWrite(PIN_STATUS_LED, HIGH);
   else digitalWrite(PIN_STATUS_LED, LOW);
+
+  Serial.print(my_address);
+  Serial.print(" ");
+  Serial.print(digitalRead(PIN_ADDRESS_BIT0));
+  Serial.print(" ");
+  Serial.println(digitalRead(PIN_ADDRESS_BIT1));

+  delay(10);
 }

 void receiveEvent(int howMany) {


Versão testes Filtro Média Móvel

Versão testes Filtro Média Móvel

--- src/arduino/thermocoupleReader/thermocoupleReader.ino
+++ src/arduino/thermocoupleReader/thermocoupleReader.ino
@@ -1,4 +1,4 @@
-/**
+ /**
  * Medida de Temperatura usando LM35 e Termopar MTK-01
  *
  * @authors Rafael, Camila, Pamella
@@ -9,16 +9,31 @@
 #define PIN_LM35      A0
 #define PIN_MTK01     A1
 #define INTERVAL      500  //ms
+#define SIZE_BUFFER   10

 unsigned long lasttime = millis();

+int bufferLM35[SIZE_BUFFER];
+int bufferMTK01[SIZE_BUFFER];
+int k;
+int i;                        // Contador Leituras
+
 void setup() {
   // Inicia Porta Serial
-  Serial.begin(9600);
+  Serial.begin(57600);

   // Define Portas Sensores
   pinMode(PIN_LM35,INPUT);
   pinMode(PIN_MTK01,INPUT);
+
+  // Zera Buffer
+  for(k=0;k<SIZE_BUFFER;k++){
+    bufferLM35[k] = 0;
+    bufferMTK01[k] = 0;
+  }
+
+  // Zera Contador
+  i=0;
 }

 void loop() {
@@ -31,11 +46,38 @@
     int rawTemp1 = analogRead(PIN_LM35);
     int rawTemp2 = analogRead(PIN_MTK01);

+    // Filtragem
+    bufferLM35[k] = rawTemp1;
+    bufferMTK01[k] = rawTemp2;
+
+    int filteredData = filterMovingAverenge(bufferLM35,k);
+
     // Envia via Serial
-    Serial.print(lasttime);
+    Serial.print(k);
     Serial.print(' ');
     Serial.print(rawTemp1);
     Serial.print(' ');
-    Serial.println(rawTemp2);
+    Serial.println(filteredData);
+
+    // Incrementa Contadores
+    i = i+1;
+    k = (k<(SIZE_BUFFER-1))?k+1:0;
   }
 }
+
+/**
+ * Filtro de Média Móvel com tamanho definido por SIZE_BUFFER
+ *
+ * @author Rafael Lima
+ */
+int filterMovingAverenge(int buffer[],int i){
+  // Calcula Endereços
+  int a1 = (i>0)?i-1:SIZE_BUFFER-1;
+  int a2 = (i<(SIZE_BUFFER-1))?i+1:0; // O próximo termo é igual o i-n por ser um buffer circular
+
+  // Aplica Filtro
+  int filteredData = buffer[a1] + (buffer[i]-buffer[a2])/SIZE_BUFFER;
+
+  return filteredData;
+}
+


Call useNoDelay on server

Call useNoDelay on server

--- barf_esp8266.ino
+++ barf_esp8266.ino
@@ -70,6 +70,7 @@
 	}

 	server.begin();
+	server.setNoDelay(true);
 }

 bool connect() {


rewritten Weather Printing functions and added a sendWeather() function for SMS reporting to server

--- mwsSIMDUINO/mwsSIMDUINO.ino
+++ mwsSIMDUINO/mwsSIMDUINO.ino
@@ -142,7 +142,6 @@
   digitalWrite(SIM808, HIGH); //SWITCH ON SIM808
   delay(40000); //WAIT FOR SIM808
   //Serial.print(sendData("AT+CPIN?", 1000, DEBUG));
-  //Serial.print(sendData("AT+CPIN?", 1000, DEBUG));
   //delay(5000); //WAIT FOR SIM808
   //*//Serial.print(sendData(" ", 2000, DEBUG));
   //*//Serial.println(sendData("AT+CMGF=1", 1000, true));
@@ -161,7 +160,7 @@

   pinMode(WSPEED, INPUT_PULLUP); // input from wind meters windspeed sensor
   //pinMode(RAIN, INPUT_PULLUP); // input from wind meters rain gauge sensor
-  //When using hardware debounce (0.1uF capacitor from PIN2 to GND) no need of PULLUP resistor
+  //When using hardware debounce (1uF capacitor from PIN2 to GND) no need of PULLUP resistor
   pinMode(RAIN, INPUT); // input from wind meters rain gauge sensor

   pinMode(REFERENCE_3V3, INPUT);
@@ -244,8 +243,10 @@
   }
   rainHour[minutes] = 0; //Zero out this minute's rainfall amount
   windgust_10m[minutes_10m] = 0; //Zero out this minute's gust
-  //DEBUG: Report all readings every loop
+  //DEBUG: Report all readings every loop to Serial
   printWeather();
+  //DEBUG: Report all readings every loop to SMS
+  sendWeather();
   //Wait 1 second, and gather GPS data
   delay(1000);
   //digitalWrite(SIM808, HIGH); //SWITCH ON SIM808
@@ -260,13 +261,15 @@
     //Check that the actual hour is incremented from last report
     if (hourReport < gpshour) {
       //Serial.print(F("inside the reporting if 2"));
-      //Report all readings hourly to Serial port
+      //Report all readings hourly to Serial port for OpenLog
       printWeather();
+      //Report all readings every loop to SMS
+      sendWeather();
       //Send daily rain report at 2AM GMT
       if (gpshour == 2) {
         sprintf(sz, "\"%d (%.3f .3%f) : %.3f mm/d\"", STATION_NAME, gpslng, gpslat, dailyrainin); //[4]
         Serial.print(sendData(" ", 2000, DEBUG));
-        Serial.println(sendData("AT+CMGF=1", 1000, true));
+        Serial.println(sendData("AT+CMGF=1", 1000, DEBUG));
         Serial.println(sendData("AT+CMGS=\"+94773260142\"", 1000, DEBUG));    //Start accepting the text for the message SIRI_SA#4
         Serial.println(sendData(sz, 1000, DEBUG));   //The text for the message
         ss.write(0x1A);
@@ -279,7 +282,7 @@
       if (rainin > 10.0) {
         sprintf(sz, "\"%d : %.3f mm/h\"", STATION_NAME, rainin); //[4]
         Serial.print(sendData(" ", 2000, DEBUG));
-        Serial.println(sendData("AT+CMGF=1", 1000, true));
+        Serial.println(sendData("AT+CMGF=1", 1000, DEBUG));
         Serial.println(sendData("AT+CMGS=\"+94773260142\"", 1000, DEBUG));    //Start accepting the text for the message SIRI_SA#4
         Serial.println(sendData(sz, 1000, DEBUG));   //The text for the message
         ss.write(0x1A);
@@ -294,8 +297,6 @@

 void getgps(int LATLONG)
 {
-  //digitalWrite(SIM808, HIGH); //SWITCH ON SIM808
-  delay(2000);
   String gpsdata = "";
   String gpsdatatmp = "";
   String tmp = "";
@@ -307,9 +308,8 @@
   {
     //GET GPS DATA
     gpsdata = "";
-    gpsdata.concat(sendData( "AT+CGNSINF", 1000, DEBUG));
+    gpsdata.concat(sendData( "AT+CGNSINF", 2000, DEBUG));
     gpsdatatmp = "";
-    delay(1000);
     gpsdatatmp.concat(gpsdata);
     gpsdatatmp.remove(75);
     //get YEAR
@@ -646,7 +646,7 @@
 {
   calcWeather(); //Go calc all the various sensors
   char sz[200];
-  strcpy(sz,mkWeatherString());
+  strcpy(sz, mkWeatherString());
   Serial.print(sendData(" ", 2000, DEBUG));
   Serial.println(sendData("AT+CMGF=1", 1000, true));
   Serial.println(sendData("AT+CMGS=\"+94773260142\"", 1000, DEBUG));    //Start accepting the text for the message SIRI_SA#4


Custom shift out method

Custom shift out method

--- bolt-arduino.ino
+++ bolt-arduino.ino
@@ -9,7 +9,7 @@
 //const uint8_t LED_STATE_ON = 1;

-byte val = B01000000;
+byte val = B01010110;

 //byte states[8];

@@ -26,7 +26,9 @@

   //states[0] = LED_STATE_ON;

+  analogWrite(P_LED_LATCH, LOW);
   shiftOut();
+  analogWrite(P_LED_LATCH, HIGH);

 }

@@ -34,19 +36,21 @@

 void shiftOut() {
+  for (uint8_t i = 0; i < 8; i++)  {
+    digitalWrite(P_LED_DATA, !!(val & (1 << i)));

-  analogWrite(P_LED_LATCH, LOW);
+    digitalWrite(P_LED_CLOCK, HIGH);
+    digitalWrite(P_LED_CLOCK, LOW);
+  }

-  shiftOut(P_LED_DATA, P_LED_CLOCK, LSBFIRST, val);
-
   /*analogWrite(P_LED_CLOCK, LOW);

-  //Loop for every byte
-  for (uint8_t i = 0; i < 8; i++)  {
+    //Loop for every byte
+    for (uint8_t i = 0; i < 8; i++)  {
     Serial.println("Index : " + String(i) + ". State : OFF " + String(!!(val & (1 << i))));
     digitalWrite(P_LED_DATA, !!(val & (1 << i)));
     //Write byte
-
+
     switch (states[i]) {
       case LED_STATE_OFF:
         Serial.println("Index : " + String(i) + ". State : OFF " + String(states[i]));
@@ -57,15 +61,15 @@
         analogWrite(P_LED_DATA, LED_TWO_VOLTS);
         break;
     }
-
+

     //Clock
     analogWrite(P_LED_CLOCK, HIGH);
     analogWrite(P_LED_CLOCK, LOW);
-  }
+    }
   */

-  analogWrite(P_LED_LATCH, HIGH);
+
   Serial.println("Done");
 }


Add uptime code

Add uptime code

--- example/shadow.ino
+++ example/shadow.ino
@@ -26,6 +26,11 @@
   reportState();                  // Let shadow know our state
 }

+// static int uptime = 0;   // Time after last reboot in seconds
 void loop() {
   if (Serial.available() > 0) jsonrpc_process_byte(Serial.read());
+  // if (millis() / 1000 > uptime) {
+  //   uptime = millis() / 1000;
+  //   jsonrpc_call("{\"method\":\"Shadow.Report\",\"params\":{\"uptime\":%d}}", uptime);
+  // }
 }


Beep when remaining time has been reduced to half

--- firmware/StandupPotato/StandupPotato.ino
+++ firmware/StandupPotato/StandupPotato.ino
@@ -26,7 +26,8 @@
 const unsigned int ACCELEROMETER_IN = PB3;
 const unsigned int ACCELEROMETER_POWER = PB4;

-const unsigned long TURN_DURATION = 2 * 60 * 1000; // The time in milliseconds that each person can talk
+const unsigned long TURN_DURATION = 120000; // The time in milliseconds that each person can talk
+unsigned long halfOfRemainingTime = TURN_DURATION / 2;
 volatile bool watchDogBarked = false;
 bool watchDogEnabled = false;
 const WatchDogTimeout gameWdt = WDT_1sec;
@@ -92,7 +93,7 @@
    A utility method to derive a watchdog timeout's duration
    @return the amount of milliseconds corresponding to a watchdog timeout
 */
-unsigned int getTimeoutDuration() {
+unsigned long getTimeoutDuration() {
   return 1 << (currentWdt + 4);
 }

@@ -206,7 +207,8 @@
         watchDogBarked = false;
         watchDogEnabled = false;
         elapsedTime += getTimeoutDuration();
-        // Main game logic to follow
+        unsigned long remainingTime = TURN_DURATION - elapsedTime;
+        /* --- Main game logic --- */
         if (elapsedTime >= TURN_DURATION) {
           // Play a sound and vibration sequence to indicate the end of a game due to timeout
           ringFor(100);
@@ -218,6 +220,11 @@
           stopVibrating();
           currentState = DEEP_SLEEP;
           elapsedTime = 0;
+          halfOfRemainingTime = TURN_DURATION / 2; // reset the remaining time since the turn is over
+        } else if (remainingTime <= halfOfRemainingTime) {
+          // Ring when we reach half of the remaining time available
+          ringFor(150);
+          halfOfRemainingTime /= 2;
         }
       }
       if (buttonPressed) {
@@ -237,6 +244,7 @@
           watchDogBarked = false;
           watchDogEnabled = false;
           elapsedTime = 0;
+          halfOfRemainingTime = TURN_DURATION / 2; // reset the remaining time since the turn is over
           // Go back to the sleep state
           currentState = DEEP_SLEEP;
         }


Change flashing button to 0 from 1

Change flashing button to 0 from 1

--- bolt-arduino.ino
+++ bolt-arduino.ino
@@ -27,8 +27,8 @@
 void loop() {
   screen_display("READY");

-  led_setState(1, LED_STATE_FLASHING);
-  button_wait(1);
+  led_setState(0, LED_STATE_FLASHING);
+  button_wait(0);

   game_start();
 }


Fixing tilt to different pin of the cape

--- arduino/OpenROV/OpenROV.ino
+++ arduino/OpenROV/OpenROV.ino
@@ -24,7 +24,7 @@

   pinMode(13, OUTPUT);

-  tilt.attach(12);
+  tilt.attach(3);
   light.attach(6);

   motors.reset();


include a randomised delay

include a randomised delay

--- Xmas2013/chaseRedGreen/chaseRedGreen.ino
+++ Xmas2013/chaseRedGreen/chaseRedGreen.ino
@@ -15,7 +15,7 @@
 #endif

 // Delay after each bulb change
-#define BETWEEN_BULBS 250
+#define BETWEEN_BULBS 100

 void setup() {
 #ifdef TWO_STRINGS
@@ -30,9 +30,21 @@
   lights.fill_color(0, LIGHT_COUNT/2-1, G35::MAX_INTENSITY, COLOR_RED);
   lights.fill_color(LIGHT_COUNT/2, LIGHT_COUNT, G35::MAX_INTENSITY, COLOR_GREEN);
 #endif
+  // Assuming analogue pin 0 is floating then this should
+  // give us a different pattern every time, not really but
+  // it will do...
+  randomSeed(analogRead(0));
 }

+long time=0;
+int delayTime = BETWEEN_BULBS;
+
 void loop() {
+  // Change delay time every 10 seconds
+  if ( millis()-time > 10000 ) {
+    time = millis();
+    delayTime = random(2*BETWEEN_BULBS);
+  }
   for (int bulb=0; bulb < LIGHT_COUNT; bulb++) {
     #ifdef TWO_STRINGS
       lights1.set_color(bulb, G35::MAX_INTENSITY, COLOR_GREEN);
@@ -43,6 +55,7 @@
       lights.set_color(bulb, G35::MAX_INTENSITY, COLOR_GREEN);
       lights.set_color((bulb+LIGHT_COUNT/2) % LIGHT_COUNT, G35::MAX_INTENSITY, COLOR_RED);
     #endif
-    delay(BETWEEN_BULBS);
+    //delay(BETWEEN_BULBS);
+    delay(delayTime);
   }
 }


improve speed

improve speed

--- DigitalSynthVRA8.ino
+++ DigitalSynthVRA8.ino
@@ -10,30 +10,32 @@
 }

 void loop() {
-  static boolean demo = true;
+  while(true) {
+    static boolean demo = true;
 #if 1
-  if (Serial.available() > 0) {
-    uint8_t b = Serial.read();
-    Synth::receiveMIDIByte(b);
+    if (Serial.available() > 0) {
+      uint8_t b = Serial.read();
+      Synth::receiveMIDIByte(b);
+    }
+#else
+  // TODO: Demo Mode
+    if (demo) {
+      static uint16_t count = 0;
+      switch (count) {
+      case      0: Synth::noteOn (48); break;
+      case   2500: Synth::noteOff(48); break;
+      case   5000: Synth::noteOn (53); break;
+      case   7500: Synth::noteOff(53); break;
+      case  10000: Synth::noteOn (55); break;
+      case  12500: Synth::noteOff(55); break;
+      case  15000: Synth::noteOn (53); break;
+      case  17500: Synth::noteOff(53); break;
+      case  19999: count = 65535u;     break;
+      }
+      count++;
+    }
+#endif
+    int8_t level = Synth::clock();
+    AudioOut::write(level);
   }
-#else
-// TODO: Demo Mode
-  if (demo) {
-    static uint16_t count = 0;
-    switch (count) {
-    case      0: Synth::noteOn (48); break;
-    case   4000: Synth::noteOff(48); break;
-    case   5000: Synth::noteOn (53); break;
-    case   9000: Synth::noteOff(53); break;
-    case  10000: Synth::noteOn (55); break;
-    case  14000: Synth::noteOff(55); break;
-    case  15000: Synth::noteOn (53); break;
-    case  19000: Synth::noteOff(53); break;
-    case  19999: count = 65535u;     break;
-    }
-    count++;
-  }
-#endif
-  int8_t level = Synth::clock();
-  AudioOut::write(level);
 }


Reset game to the light show after losing or winning all rounds.

--- simon_says/simon_says.ino
+++ simon_says/simon_says.ino
@@ -6,7 +6,6 @@
  */

 // TODO Reset game in the middle of a game.
-// TODO Go back to light show after losing or winning a game.

 // Turn debug mode on or off.
 const boolean DEBUG = true;
@@ -74,41 +73,12 @@

     // Begin the game.
     playGame(pattern);
-}
-
-
-/**
- * Determine whether the player successfully matched the pattern.
- */
-boolean verifyPlayerInput(int *pattern, int currentLevel) {
-
-    // Get player input up through the current game level.
-    int lvl = 0;
-    while (lvl < currentLevel) {
-
-        // Wait for a button press.
-        int simonLed = -1;
-        while (simonLed == -1) {
-            simonLed = getSimonLed(analogRead(BUTTONS));
-        }
-
-        // Blink the corresponding LED.
-        digitalWrite(simonLed, HIGH);
-        delay(GAME_SPEED);
-        digitalWrite(simonLed, LOW);
-        delay(GAME_SPEED);
-
-        // Check if the button press was correct.
-        if (pattern[lvl] == simonLed) {
-            lvl++;
-        } else {
-            // Player input was incorrect.
-            return false;
-        }
-    }
-
-    // The player successfully matched the pattern.
-    return true;
+
+    // The game is over, so turn off all lights and reset the game.
+    for (int i = 0; i < QTY; i++) {
+        digitalWrite(LEDS[i], LOW);
+        gameStart = false;
+    }
 }

@@ -146,7 +116,7 @@
         // Display the pattern.
         for (int lvl = 0; lvl < currentLevel; lvl++) {

-            // Blink the LED.
+            // Blink the current pattern LED.
             digitalWrite(pattern[lvl], HIGH);
             delay(GAME_SPEED);
             digitalWrite(pattern[lvl], LOW);
@@ -160,6 +130,7 @@

             // The player was correct; move to the next level.
             currentLevel++;
+            delay(GAME_SPEED);

         // The player was incorrect; subtract a life.
         } else {
@@ -217,14 +188,14 @@
 boolean signalGameStart() {

     // Check the tilt switch and buttons for a new game.
-    if (digitalRead(TILT) || analogRead(BUTTONS) > 3) {
+    if (digitalRead(TILT) || (!gameStart && analogRead(BUTTONS) > 3)) {
         gameStart = true;
     }

     // Flash all LEDs to signal game start if appropriate.
     if (gameStart) {

-        // Blink lights twice.
+        // Blink all lights twice.
         for (int j = 0; j < 2; j++) {
             for (int k = 0; k < QTY; k++) {
                 digitalWrite(LEDS[k], HIGH);
@@ -243,3 +214,33 @@
     // The game has not begun.
     return false;
 }
+
+
+/**
+ * Determine whether the player successfully matched the pattern.
+ */
+boolean verifyPlayerInput(int *pattern, int currentLevel) {
+
+    // Get player input up through the current game level.
+    int lvl = 0;
+    while (lvl < currentLevel) {
+
+        // Wait for a button press.
+        int simonLed = -1;
+        while (simonLed == -1) {
+            simonLed = getSimonLed(analogRead(BUTTONS));
+        }
+
+        // Blink the corresponding LED.
+        digitalWrite(simonLed, HIGH);
+        delay(GAME_SPEED);
+        digitalWrite(simonLed, LOW);
+
+        // Check if the button press was correct.
+        if (pattern[lvl] == simonLed) lvl++;
+        else return false;
+    }
+
+    // The player successfully matched the pattern.
+    return true;
+}


TRIG timing

TRIG timing

Some Hero 3+ Black went panic if delay before asserting TRIG is too long

--- h_GenlockState.ino
+++ h_GenlockState.ino
@@ -39,15 +39,14 @@
       recording_state = STATE_END;
       break;
     case STATE_END:
-      if (millis() - command_sent > 400) {
+      if (millis() - command_sent > 200) {
         digitalWrite(TRIG, LOW); // video stops at FALLING edge
-        delay(1);
-        digitalWrite(TRIG, HIGH);
         recording_state = STATE_SYNC_OFF;
       }
       break;
     case STATE_SYNC_OFF:
-      if (millis() - command_sent > 1400) {
+      if (millis() - command_sent > 1200) {
+        digitalWrite(TRIG, HIGH);
         DEBUG_println(F("genlock signal stop"));
         StopSyncSignal();
         recording_state = STATE_IDLE;