Adjust timings

Adjust timings

--- UselessBox.ino
+++ UselessBox.ino
@@ -30,7 +30,7 @@
 Servo lidServo;

 int lidFrom = 1200; // adjustable
-int lidTo = 1900; // fixed
+int lidTo = 1850; // fixed
 int lidRange = lidTo - lidFrom;

 int switchFrom = 1800; // fixed
@@ -74,16 +74,27 @@

   randomSeed(getSeedFromAnalogPin(A5));

+  delay(20);
   digitalWrite(6, HIGH);  // turn on motor power
 }

 unsigned long getSeedFromAnalogPin(int pin)
 {
   // From http://www.utopiamechanicus.com/article/better-arduino-random-numbers/
-  unsigned long seed=0, count=32;
-  while (--count)
-    seed = (seed<<1) | (analogRead(pin)&1);
-  return seed;
+  unsigned long seed=0, noOfBits=32, limit=99;
+  int bit0=0, bit1=0;
+  while (noOfBits--)
+  {
+    for (int i=0;i<limit;++i)
+    {
+      bit0=analogRead(pin)&1;
+      bit1=analogRead(pin)&1;
+      if (bit1!=bit0)
+        break;
+    }
+    seed = (seed<<1) | bit1;
+  }
+  return seed;
 }

 void loop()
@@ -137,7 +148,7 @@

 void RunSequence()
 {
-  int sequence = random(0, 20);
+  int sequence = random(0, 22);

   if (sequence == 0) Sequence0();
   if (sequence == 1) Sequence1();
@@ -150,9 +161,10 @@
   if (sequence == 8) Sequence8();
   if (sequence == 9) Sequence9();
   if (sequence == 10) Sequence10();
-  if (sequence > 10) DefaultSequence();
+  if (sequence == 11) Sequence11();
+  if (sequence > 11) DefaultSequence();

-  delay(3000);
+  delay(2000);
 }

 void AdjustLid()
@@ -170,15 +182,13 @@
 // Plain old open the lid, press the switch, close the lid
 void DefaultSequence()
 {
-  delay(50);
-  Sweep(lidServo, lidFrom, lidTo, 1);
-  delay(200);
-  Sweep(switchServo, switchFrom, switchTo, 1);
-  delay(300);
-  Sweep(switchServo, switchTo, switchFrom, 1);
-  delay(150);
-  Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(400);
+  Sweep(lidServo, lidFrom, lidTo, 1);
+  delay(100);
+  Sweep(switchServo, switchFrom, switchTo, 1);
+  delay(275);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
 }

 void Sequence0()
@@ -187,7 +197,6 @@
   int lidMid4 = lidFrom  + lidRange * 0.60;
   int switchMid = switchTo + switchRange * 0.57;

-  delay(50);
   Sweep(lidServo, lidFrom, lidMid, 3000);
   delay(1000);
   Sweep(lidServo, lidMid, lidMid4, 500);
@@ -195,7 +204,7 @@
   Sweep(lidServo, lidMid4, lidTo, 1000);
   Sweep(switchServo, switchFrom, switchMid, 1800);
   Sweep(switchServo, switchMid, switchTo, 500);
-  delay(100);
+  delay(110);
   Sweep(switchServo, switchTo, switchFrom, 500);
   Sweep(lidServo, lidTo, lidFrom, 500);
 }
@@ -208,28 +217,27 @@
   int lidMid4 = lidFrom  + lidRange * 0.60;
   int switchMid = switchTo + switchRange * 0.57;

-  delay(50);
   Sweep(lidServo, lidFrom, lidMid2, 3000);
   Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(120);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(120);
-  Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(120);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(120);
-  Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(120);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(120);
+  delay(100);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(90);
+  Sweep(lidServo, lidMid2, lidMid3, 1);
+  delay(90);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(90);
+  Sweep(lidServo, lidMid2, lidMid3, 1);
+  delay(90);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(300);
   Sweep(lidServo, lidMid2, lidMid4, 3000);
   Sweep(lidServo, lidMid4, lidMid, 3000);
   delay(1000);
   Sweep(lidServo, lidMid, lidTo, 1000);
   Sweep(switchServo, switchFrom, switchMid, 1800);
-  Sweep(switchServo, switchMid, switchTo, 500);
-  delay(100);
-  Sweep(switchServo, switchTo, switchFrom, 500);
+  Sweep(switchServo, switchMid, switchTo, 200);
+  delay(110);
+  Sweep(switchServo, switchTo, switchFrom, 200);
   Sweep(lidServo, lidTo, lidFrom, 500);
 }

@@ -237,79 +245,73 @@
 {
   int switchMid2 = switchTo + switchRange * 0.28;   // Almost on the switch

-  delay(50);
   Sweep(lidServo, lidFrom, lidTo, 1);
   delay(1);
   Sweep(switchServo, switchFrom, switchMid2, 1);
   delay(450);
   Sweep(switchServo, switchMid2, switchTo, 30000);
-  delay(1);
-  Sweep(switchServo, switchTo, switchFrom, 1);
-  delay(200);
-  Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(400);
+  delay(100);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
 }

 void Sequence3()
 {
-  int switchMid2 = switchTo + switchRange * 0.05;   // Almost on the switch
-
-  delay(50);
-  Sweep(lidServo, lidFrom, lidTo, 1);
-  delay(200);
-  Sweep(switchServo, switchFrom, switchTo, 1);
-  delay(50);
-  Sweep(switchServo, switchTo, switchMid2, 1);
-  delay(50);
-  Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(50);
-  Sweep(switchServo, switchTo, switchMid2, 1);
-  delay(50);
-  Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(50);
-  Sweep(switchServo, switchTo, switchMid2, 1);
-  delay(50);
-  Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(50);
-  Sweep(switchServo, switchTo, switchMid2, 1);
-  delay(50);
-  Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(50);
-  Sweep(switchServo, switchTo, switchMid2, 1);
-  delay(50);
-  Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(50);
-  Sweep(switchServo, switchTo, switchMid2, 1);
-  delay(50);
-  Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(50);
-  Sweep(switchServo, switchTo, switchMid2, 1);
-  delay(50);
-  Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(50);
-  Sweep(switchServo, switchTo, switchFrom, 1);
-  delay(200);
-  Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(400);
+  int switchMid2 = switchTo + switchRange * 0.10;   // Almost on the switch
+
+  Sweep(lidServo, lidFrom, lidTo, 1);
+  delay(100);
+  Sweep(switchServo, switchFrom, switchTo, 1);
+  delay(60);
+  Sweep(switchServo, switchTo, switchMid2, 1);
+  delay(60);
+  Sweep(switchServo, switchMid2, switchTo, 1);
+  delay(60);
+  Sweep(switchServo, switchTo, switchMid2, 1);
+  delay(60);
+  Sweep(switchServo, switchMid2, switchTo, 1);
+  delay(60);
+  Sweep(switchServo, switchTo, switchMid2, 1);
+  delay(60);
+  Sweep(switchServo, switchMid2, switchTo, 1);
+  delay(60);
+  Sweep(switchServo, switchTo, switchMid2, 1);
+  delay(60);
+  Sweep(switchServo, switchMid2, switchTo, 1);
+  delay(60);
+  Sweep(switchServo, switchTo, switchMid2, 1);
+  delay(60);
+  Sweep(switchServo, switchMid2, switchTo, 1);
+  delay(60);
+  Sweep(switchServo, switchTo, switchMid2, 1);
+  delay(60);
+  Sweep(switchServo, switchMid2, switchTo, 1);
+  delay(60);
+  Sweep(switchServo, switchTo, switchMid2, 1);
+  delay(60);
+  Sweep(switchServo, switchMid2, switchTo, 1);
+  delay(80);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
 }

 void Sequence4()
 {
-  int lidMid4 = lidFrom  + lidRange * 0.85;
-
-  delay(50);
-  Sweep(lidServo, lidFrom, lidTo, 1);
-  delay(200);
-  Sweep(switchServo, switchFrom, switchTo, 1);
-  delay(450);
+  int lidMid4 = lidFrom  + lidRange * 0.75;
+
+  Sweep(lidServo, lidFrom, lidTo, 1);
+  delay(100);
+  Sweep(switchServo, switchFrom, switchTo, 1);
+  delay(300);
   Sweep(lidServo, lidTo, lidMid4, 1000);
   delay(2000);
   Sweep(lidServo, lidMid4, lidTo, 1000);
-  delay(2000);
-  Sweep(switchServo, switchTo, switchFrom, 1);
-  delay(200);
-  Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(400);
+  delay(1000);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
 }

 void Sequence5()
@@ -318,7 +320,34 @@
   int lidMid2 = lidFrom + lidRange * 0.68;
   int lidMid4 = lidFrom  + lidRange * 0.50;

-  delay(50);
+  Sweep(lidServo, lidFrom, lidMid, 1);
+  delay(150);
+  Sweep(lidServo, lidMid, lidMid2, 1);
+  delay(100);
+  Sweep(lidServo, lidMid2, lidMid, 1);
+  delay(100);
+  Sweep(lidServo, lidMid, lidMid2, 1);
+  delay(100);
+  Sweep(lidServo, lidMid2, lidMid, 1);
+  delay(100);
+  Sweep(lidServo, lidMid, lidMid4, 1);
+  delay(100);
+  Sweep(lidServo, lidMid4, lidTo, 1);
+  delay(1);
+  Sweep(switchServo, switchFrom, switchTo, 1);
+  delay(450);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
+}
+
+void Sequence6()
+{
+  int lidMid = lidFrom + lidRange * 0.85;
+  int lidMid2 = lidFrom + lidRange * 0.6;
+  int lidMid3 = lidFrom + lidRange * 0.7;
+  int lidMid4 = lidFrom  + lidRange * 0.40;
+
   Sweep(lidServo, lidFrom, lidMid, 1);
   delay(200);
   Sweep(lidServo, lidMid, lidMid2, 1);
@@ -327,81 +356,49 @@
   delay(100);
   Sweep(lidServo, lidMid, lidMid2, 1);
   delay(100);
-  Sweep(lidServo, lidMid2, lidMid, 1);
-  delay(100);
-  Sweep(lidServo, lidMid, lidMid4, 1);
+  Sweep(lidServo, lidMid2, lidMid3, 1);
+  delay(50);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(50);
+  Sweep(lidServo, lidMid2, lidMid3, 1);
+  delay(50);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(50);
+  Sweep(lidServo, lidMid2, lidMid3, 1);
+  delay(50);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(50);
+  Sweep(lidServo, lidMid2, lidMid3, 1);
+  delay(50);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(50);
+  Sweep(lidServo, lidMid2, lidMid3, 1);
+  delay(50);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(50);
+  Sweep(lidServo, lidMid2, lidMid3, 1);
+  delay(50);
+  Sweep(lidServo, lidMid3, lidMid2, 1);
+  delay(50);
+  Sweep(lidServo, lidMid2, lidMid4, 1);
   delay(200);
   Sweep(lidServo, lidMid4, lidTo, 1);
   delay(1);
   Sweep(switchServo, switchFrom, switchTo, 1);
-  delay(450);
-  Sweep(switchServo, switchTo, switchFrom, 1);
-  delay(200);
-  Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(400);
-}
-
-void Sequence6()
+  delay(250);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
+}
+
+void Sequence7()
 {
   int lidMid = lidTo;
   int lidMid2 = lidFrom + lidRange * 0.68;
   int lidMid3 = lidFrom + lidRange * 0.77;
-  int lidMid4 = lidFrom  + lidRange * 0.50;
-
-  delay(50);
-  Sweep(lidServo, lidFrom, lidMid, 1);
-  delay(200);
-  Sweep(lidServo, lidMid, lidMid2, 1);
-  delay(100);
-  Sweep(lidServo, lidMid2, lidMid, 1);
-  delay(100);
-  Sweep(lidServo, lidMid, lidMid2, 1);
-  delay(100);
-  Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(50);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(50);
-  Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(50);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(50);
-  Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(50);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(50);
-  Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(50);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(50);
-  Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(50);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(50);
-  Sweep(lidServo, lidMid2, lidMid3, 1);
-  delay(50);
-  Sweep(lidServo, lidMid3, lidMid2, 1);
-  delay(50);
-  Sweep(lidServo, lidMid2, lidMid4, 1);
-  delay(200);
-  Sweep(lidServo, lidMid4, lidTo, 1);
-  delay(1);
-  Sweep(switchServo, switchFrom, switchTo, 1);
-  delay(450);
-  Sweep(switchServo, switchTo, switchFrom, 1);
-  delay(200);
-  Sweep(lidServo, lidTo, lidFrom, 1);
+
+  Sweep(lidServo, lidFrom, lidMid, 2000);
   delay(400);
-}
-
-void Sequence7()
-{
-  int lidMid = lidTo;
-  int lidMid2 = lidFrom + lidRange * 0.68;
-  int lidMid3 = lidFrom + lidRange * 0.77;
-
-  delay(50);
-  Sweep(lidServo, lidFrom, lidMid, 2000);
-  delay(500);
   Sweep(lidServo, lidMid, lidMid2, 1000);
   delay(1);
   Sweep(lidServo, lidMid2, lidMid3, 1);
@@ -441,35 +438,35 @@
   Sweep(lidServo, lidMid, lidTo, 1000);
   delay(1);
   Sweep(switchServo, switchFrom, switchTo, 1);
-  delay(450);
-  Sweep(switchServo, switchTo, switchFrom, 1);
-  delay(200);
-  Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(400);
+  delay(250);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
 }

 void Sequence8()
 {
+  Sweep(lidServo, lidFrom, lidTo, 30000);
+  delay(1);
+  Sweep(switchServo, switchFrom, switchTo, 5000);
+  delay(1);
+  Sweep(switchServo, switchTo, switchFrom, 5000);
+  delay(700);
+  Sweep(lidServo, lidTo, lidFrom, 1);
+}
+
+void Sequence9()
+{
+  int switchMid2 = switchTo + switchRange * 0.28;
+
+  Sweep(lidServo, lidFrom, lidTo, 1);
+  delay(100);
+  Sweep(switchServo, switchFrom, switchTo, 1);
   delay(1000);
-  Sweep(lidServo, lidFrom, lidTo, 30000);
-  delay(1);
-  Sweep(switchServo, switchFrom, switchTo, 5000);
-  delay(1);
-  Sweep(switchServo, switchTo, switchFrom, 5000);
+  Sweep(switchServo, switchTo, switchMid2, 1);
+  delay(110);
+  Sweep(switchServo, switchMid2, switchTo, 1);
   delay(500);
-  Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(300);
-}
-
-void Sequence9()
-{
-  int switchMid2 = switchTo + switchRange * 0.28;
-
-  delay(100);
-  Sweep(lidServo, lidFrom, lidTo, 1);
-  delay(200);
-  Sweep(switchServo, switchFrom, switchTo, 1);
-  delay(1000);
   Sweep(switchServo, switchTo, switchMid2, 1);
   delay(110);
   Sweep(switchServo, switchMid2, switchTo, 1);
@@ -477,24 +474,18 @@
   Sweep(switchServo, switchTo, switchMid2, 1);
   delay(110);
   Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(500);
-  Sweep(switchServo, switchTo, switchMid2, 1);
   delay(110);
-  Sweep(switchServo, switchMid2, switchTo, 1);
-  delay(110);
-  Sweep(switchServo, switchTo, switchFrom, 1);
-  delay(200);
-  Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(400);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
 }

 void Sequence10()
 {
   int switchMid2 = switchTo + switchRange * 0.35;

-  delay(100);
-  Sweep(lidServo, lidFrom, lidTo, 1);
-  delay(200);
+  Sweep(lidServo, lidFrom, lidTo, 1);
+  delay(100);
   Sweep(switchServo, switchFrom, switchTo, 1);
   delay(2000);
   Sweep(switchServo, switchTo, switchMid2, 6000);
@@ -504,7 +495,28 @@
   Sweep(switchServo, switchTo, switchFrom, 2000);
   delay(200);
   Sweep(lidServo, lidTo, lidFrom, 1);
-  delay(400);
+}
+
+void Sequence11()
+{
+  int switchMid1 = switchTo + switchRange * 0.60;
+  int switchMid2 = switchTo + switchRange * 0.30;
+
+  Sweep(switchServo, switchFrom, switchMid1, 1000);
+  delay(2000);
+  Sweep(switchServo, switchMid1, switchFrom, 1);
+  delay(1000);
+  Sweep(switchServo, switchFrom, switchMid2, 1000);
+  delay(2000);
+  Sweep(switchServo, switchMid2, switchMid1, 6000);
+  delay(2000);
+  Sweep(lidServo, lidFrom, lidTo, 1);
+  delay(100);
+  Sweep(switchServo, switchMid1, switchTo, 1);
+  delay(250);
+  Sweep(switchServo, switchTo, switchFrom, 1);
+  delay(100);
+  Sweep(lidServo, lidTo, lidFrom, 1);
 }

 void Sweep(Servo& servo, int from, int to, int usec)


switch mode to black after closed serial connection

--- Arduino/adrilight/adrilight.ino
+++ Arduino/adrilight/adrilight.ino
@@ -11,6 +11,7 @@

 #define MODE_ANIMATION 0
 #define MODE_AMBILIGHT 1
+#define MODE_BLACK 2
 uint8_t mode = MODE_ANIMATION;

 byte MESSAGE_PREAMBLE[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
@@ -25,7 +26,6 @@
 CRGB leds[NUM_LEDS];
 byte buffer[NUM_BYTES];

-
 // Filler animation attributes
 CRGBPalette16 currentPalette = RainbowColors_p;
 TBlendType    currentBlending = LINEARBLEND;
@@ -33,102 +33,115 @@

 void setup()
 {
-  Serial.begin(115200);
-  FastLED.clear(true);
-  FastLED.addLeds<WS2812B, LED_DATA_PIN, GRB>(leds, NUM_LEDS);
-  FastLED.setBrightness(BRIGHTNESS);
+    Serial.begin(115200);
+    FastLED.clear(true);
+    FastLED.addLeds<WS2812B, LED_DATA_PIN, GRB>(leds, NUM_LEDS);
+    FastLED.setBrightness(BRIGHTNESS);
 }

 void loop()
 {
-	switch (mode) {
-		case MODE_ANIMATION:
-			fillLEDsFromPaletteColors();
-			break;
-
-		case MODE_AMBILIGHT:
-			processIncomingData();
-			break;
-	}
-
+    switch (mode) {
+        case MODE_ANIMATION:
+            fillLEDsFromPaletteColors();
+            break;
+
+        case MODE_AMBILIGHT:
+            processIncomingData();
+            break;
+
+            case MODE_BLACK:
+            showBlack();
+            break;
+    }
+
 }

 void processIncomingData()
 {
-	if (waitForPreamble(TIMEOUT))
-	{
-		Serial.readBytes(buffer, NUM_BYTES);
+    if (waitForPreamble(TIMEOUT))
+    {
+        Serial.readBytes(buffer, NUM_BYTES);

-		/* DEBUG
-		for (int i = 0; i < NUM_BYTES; i++)
-		{
-			Serial.write((char)buffer[i]);
-		}
-		*/
+        while (byte_counter < NUM_BYTES)
+        {
+            byte blue = buffer[byte_counter++];
+            byte green = buffer[byte_counter++];
+            byte red = buffer[byte_counter++];
+
+            leds[led_counter++] = CRGB(red, green, blue);
+        }

-		while (byte_counter < NUM_BYTES)
-		{
-			byte blue = buffer[byte_counter++];
-			byte green = buffer[byte_counter++];
-			byte red = buffer[byte_counter++];
+        FastLED.show();

-			leds[led_counter++] = CRGB(red, green, blue);
-		}
-
-		FastLED.show();
-
-		byte_counter = 0;
-		led_counter = 0;
-	}
-	else
-	{
-		mode = MODE_ANIMATION;
-	}
+        byte_counter = 0;
+        led_counter = 0;
+    }
+    else
+    {
+        //if we get here, there must have been data before(so the user already knows, it works!)
+        //simply go to black!
+        mode = MODE_BLACK;
+    }
 }

 bool waitForPreamble(int timeout)
 {
-	last_serial_available = millis();
-	while (current_preamble_position < PREAMBLE_LENGTH)
-	{
-		if (Serial.available() > 0)
-		{
-			last_serial_available = millis();
+    last_serial_available = millis();
+    while (current_preamble_position < PREAMBLE_LENGTH)
+    {
+        if (Serial.available() > 0)
+        {
+            last_serial_available = millis();

-			if (Serial.read() == MESSAGE_PREAMBLE[current_preamble_position])
-			{
-				current_preamble_position++;
-			}
-			else
-			{
-				current_preamble_position = 0;
-			}
-		}
+            if (Serial.read() == MESSAGE_PREAMBLE[current_preamble_position])
+            {
+                current_preamble_position++;
+            }
+            else
+            {
+                current_preamble_position = 0;
+            }
+        }

-		if (millis() - last_serial_available > timeout)
-		{
-			return false;
-		}
-	}
-	current_preamble_position = 0;
-	return true;
+        if (millis() - last_serial_available > timeout)
+        {
+            return false;
+        }
+    }
+    current_preamble_position = 0;
+    return true;
 }

 void fillLEDsFromPaletteColors()
 {
-	startIndex++; // speed
+    startIndex++;

-	uint8_t colorIndex = startIndex;
-	for( int i = 0; i < NUM_LEDS; i++) {
-        leds[i] = ColorFromPalette(currentPalette, colorIndex, BRIGHTNESS, currentBlending);
-		colorIndex += 3;
+    uint8_t colorIndex = startIndex;
+    for( int i = 0; i < NUM_LEDS; i++) {
+            leds[i] = ColorFromPalette(currentPalette, colorIndex, BRIGHTNESS, currentBlending);
+            colorIndex += 3;
+        }
+
+    FastLED.delay(1000 / UPDATES_PER_SECOND);
+
+    if (Serial.available() > 0)
+    {
+        mode = MODE_AMBILIGHT;
     }
-
-	FastLED.delay(1000 / UPDATES_PER_SECOND);
-
-	if (Serial.available() > 0)
-	{
-		mode = MODE_AMBILIGHT;
-	}
 }

+void showBlack()
+{
+    for( int i = 0; i < NUM_LEDS; i++)
+    {
+        leds[i] = CRGB(0,0,0);
+    }
+    FastLED.delay(1000 / UPDATES_PER_SECOND);
+
+    if (Serial.available() > 0)
+    {
+        mode = MODE_AMBILIGHT;
+    }
+}
+


Fix for last .ino file

Fix for last .ino file

Same changes as pull request #56

--- libraries/BLE/examples/ble_temperature_broadcast/ble_temperature_broadcast.ino
+++ libraries/BLE/examples/ble_temperature_broadcast/ble_temperature_broadcast.ino
@@ -41,6 +41,7 @@
  * The format used is IEEE 11073-20601 FLOAT
  */
 #include <SPI.h>
+#include <EEPROM.h>
 #include <avr/sleep.h>
 #include <avr/power.h>

@@ -60,7 +61,7 @@

 #define TEMPERATURE_NUM_SAMPLES  5

-static hal_aci_data_t setup_msgs[NB_SETUP_MESSAGES] PROGMEM = SETUP_MESSAGES_CONTENT;
+static const hal_aci_data_t setup_msgs[NB_SETUP_MESSAGES] PROGMEM = SETUP_MESSAGES_CONTENT;
 // aci_struct that will contain
 // total initial credits
 // current credit
@@ -284,7 +285,7 @@
     aci_state.aci_setup_info.services_pipe_type_mapping = NULL;
   }
   aci_state.aci_setup_info.number_of_pipes    = NUMBER_OF_PIPES;
-  aci_state.aci_setup_info.setup_msgs         = setup_msgs;
+  aci_state.aci_setup_info.setup_msgs         = (hal_aci_data_t*) setup_msgs;
   aci_state.aci_setup_info.num_setup_msgs     = NB_SETUP_MESSAGES;

   /*


add new line at end of file

add new line at end of file

--- Event_Printer/Event_Printer.ino
+++ Event_Printer/Event_Printer.ino
@@ -234,3 +234,4 @@
     value = HI_NIBBLE(data[5]);
     motorcycle_state.info_button = (K25_Info_Button_State)value;
 }
+


Units to m,rad,s; Rename vars; use double for alt; aprs update to procAprs.

--- PortableAntennaRotorControl.ino
+++ PortableAntennaRotorControl.ino
@@ -24,6 +24,11 @@
 const long maxTimeSyncAge = (long)( 0.5 + maxTimeTol / xtalTol );
 const long rotorUpdateInterval = 200000;
 const float deg2rad = 3.1415927 / 180.0;
+const float rEarth = 6.371e6; // meters
+const float deg2m = 1.124E5; // meters/deg on great circle at msl
+const float m2rad = 1.5696E-7; // radians/m on great circle at msl
+const float knots2mps = 0.51444444; // m/s
+const float ft2m = 0.3048; //  m
 /*
  * Set addresses of EEPROM parameters
  */
@@ -64,9 +69,13 @@
 int aprsIndex = 0;
 boolean aprsRdy, aprsChkFlg, aprsErrFlg, aprsBufCurrent, aprsValid;
 boolean aprsFlg, aprsNewFlg;
-long aprsTime, lastAprsTime; // standard time in seconds with decimal fraction to ms
-float aprsLat, aprsLon, aprsAlt, aprsVg, aprsHdg;
-float lastAprsAlt; // needed to keep track of prior value to calculate Vz
+float aprsLat, aprsLon, aprsVg, aprsHdg;
+double aprsAlt;
+
+// Derived aprs parameters
+double aprsTime, lastAprsTime;
+float aprsVlon, aprsVlat, aprsValt; // Derived from aprsVg, aprsHdg
+double lastAprsAlt = -1; // needed to keep track of prior value to calculate Vz

 char term[TERMLEN], aprsfiBuf[APRSFILEN], cmdBuf[CMDLEN];
 int termIndex = 0;
@@ -78,12 +87,15 @@
 boolean targetValid;

 long  targetTime;
-float targetPosX; //lon
-float targetPosY; //lat
-float targetPosZ; //alt
-float targetVelX;
-float targetVelY;
-float targetVelZ;
+float targetLon; //lon radians
+float targetLat; //lat radians
+double targetAlt; //alt meters
+float targetVlon; // rad/s
+float targetVlat; // rad/s
+float targetValt; // m/s
+
+float targetAz;
+float targetEl;

 Aprs aprsObj = Aprs( "WB9SKY,KC9LIG,KC9LHW" );

@@ -238,9 +250,13 @@
     }
     if ( gpsPosValid ) {
       // Get position, velocity data
-      gpsLat = getField( gpsTF, 6, ',' ).toFloat();
+      String latStr = getField( gpsTF, 6, ',' );
+      gpsLat = latStr.substring( 0,2 ).toFloat();
+      gpsLat = ( gpsLat + latStr.substring( 2 ).toFloat() / 60.0 ) * deg2rad;
       if ( getField( gpsTF, 7, ',' ) == 'S' ) gpsLat *= -1.0;
-      gpsLon = getField( gpsTF, 8, ',' ).toFloat();
+      String lonStr = getField( gpsTF, 8, ',' );
+      gpsLon = lonStr.substring( 0,3 ).toFloat();
+      gpsLon = ( gpsLon + lonStr.substring( 3 ).toFloat() / 60.0 ) * deg2rad;
       if ( getField( gpsTF, 9, ',' ) == 'W' ) gpsLon *= -1.0;
       gpsAlt = getField( gpsTF, 10, ',' ).toFloat();
     }
@@ -436,40 +452,62 @@
     Serial.println( "invalid" );
   }
   if ( callSgnFilt ) {
-    aprsTime = now();
-    aprsLat = aprsObj.getLatitude();
-    aprsLon = aprsObj.getLongitude();
-    aprsAlt = (float)aprsObj.getAltitude();
-    aprsVg = (float)aprsObj.getGroundspeed();
-    aprsHdg = (float)aprsObj.getCourse();
+    // Extract and convert params to m, rad, rad/s
+    aprsLat = aprsObj.getLatitude() * deg2rad;
+    aprsLon = aprsObj.getLongitude() * deg2rad;
+    aprsAlt = (double)aprsObj.getAltitude() * ft2m;
+    aprsVg = (float)aprsObj.getGroundspeed() * knots2mps * m2rad;
+    aprsHdg = (float)aprsObj.getCourse() * deg2rad;
     aprsNewFlg = true;
+
+    // Derived parameters
+    aprsVlon = aprsVg * sin( aprsHdg ) / cos( aprsLat );
+    aprsVlat = aprsVg * cos( aprsHdg );
+
+    if ( lastAprsTime == 0 ) {
+      lastAprsTime = (double)now();
+      aprsTime = lastAprsTime;
+      aprsValt = 0.0;
+    } else {
+      aprsTime = (double)now();
+      aprsValt = ( aprsAlt - lastAprsAlt ) / ( aprsTime - lastAprsTime );
+      Serial.print( "   :" );Serial.print(aprsTime);
+      Serial.print( " " );Serial.println( lastAprsTime );
+    }
+    double deltaZ = aprsAlt - lastAprsAlt;
+    double deltaT = aprsTime - lastAprsTime;
+    lastAprsTime = aprsTime;
+    lastAprsAlt = aprsAlt;
+    if ( DEBUG ) {
+      digitalClockDisplay( (long)aprsTime );
+      Serial.print("APRS: Lon Lat Alt Vg Hdg Vx Vy Vz:");
+      Serial.print( aprsLon, 4 );Serial.print(' ');
+      Serial.print( aprsLat, 4 );Serial.print(' ');
+      Serial.print( aprsAlt);Serial.print(' ');
+      Serial.print( aprsVg );Serial.print(' ');
+      Serial.print( aprsHdg );Serial.print(' ');
+      Serial.print( aprsVlon );Serial.print(' ');
+      Serial.print( aprsVlat );Serial.print(' ');
+      Serial.println( aprsValt );
+    }
+
   }

 }

 void updateTarget() {
-    // Time must be a long int, can't be float, so can't be part of target state
-    // array. Change this so that target state is just separate variables instead
-    // of an array.
+  // if a new APRS fix came in, use it as last target state
   if ( aprsNewFlg ) {
     if ( DEBUG ) Serial.println( "APRS target update" );
+    targetValid = true;
     // Set prior target state to new APRS data
     targetTime = aprsTime;
-    // Initialization for computed derivatives on first valid APRS fix
-    if ( targetValid ) {
-      targetVelZ = ( aprsAlt - lastAprsAlt ) / ( aprsTime - lastAprsTime );
-    } else {
-      targetVelZ = 0.0;
-      targetValid = true;
-    }
-    targetPosX = aprsLon;
-    targetPosY = aprsLat;
-    targetPosZ = aprsAlt;
-    targetVelX = aprsVg * cos( aprsHdg * deg2rad ) * cos( aprsLat * deg2rad );
-    targetVelY = aprsVg * sin( aprsHdg * deg2rad );
-    targetVelZ = ( aprsAlt - lastAprsAlt ) / ( targetTime - lastAprsTime );
-    lastAprsTime = targetTime;
-    lastAprsAlt = aprsAlt;
+    targetLon = aprsLon;
+    targetLat = aprsLat;
+    targetAlt = aprsAlt;
+    targetVlon = aprsVlon;
+    targetVlat = aprsVlat;
+    targetValt = aprsValt;
     aprsNewFlg = false;
   }

@@ -478,9 +516,9 @@
     long temp = targetTime; // old time, same as lastAprsTime??
     targetTime = now();
     temp = targetTime - temp; // delta t
-    targetPosX += ( targetVelX * temp );
-    targetPosY += ( targetVelY * temp );
-    targetPosZ += ( targetVelZ * temp );
+    targetLon += ( targetVlon * deltaT );
+    targetLat += ( targetVlat * deltaT );
+    targetAlt += ( targetValt * deltaT );
   }

   //FOR DEBUG PURPOSES


use user loop instead of ticker, fix a crash

The crash occurs when long msg arrives but the buffer allocated
in user mqtt processing routine is smaller, then wild pointer.

--- src/neurite.ino
+++ src/neurite.ino
@@ -431,6 +431,7 @@
 	}
 }

+/* FIXME is this necessary? */
 static void ticker_worker_task(void)
 {
 #if 0
@@ -983,7 +984,7 @@
 			mqtt_cli.publish(nd->cfg.topic_to, (const char *)payload_buf);

 			start_ticker_led_breath(nd);
-			start_ticker_worker(nd);
+			//start_ticker_worker(nd);
 			start_ticker_mon(nd);
 			CMD_SERIAL.println(FPSTR(STR_READY));
 			log_dbg("heap free: %d\n\r", ESP.getFreeHeap());
@@ -1066,6 +1067,9 @@
 		neurite_worker();
 	else
 		neurite_cfg_worker();
+#ifdef NEURITE_ENABLE_USER
+	neurite_user_loop();
+#endif
 }

 /*
@@ -1084,11 +1088,20 @@
  */

 #ifdef NEURITE_ENABLE_USER
-Ticker ticker_user;
-
-void ticker_user_task(void)
-{
+
+#define USER_LOOP_INTERVAL 1000
+static bool b_user_loop_run = false;
+
+void neurite_user_loop(void)
+{
+	static uint32_t prev_time = 0;
+	if (b_user_loop_run == false)
+		return;
 	/* do something as in a periodically loop */
+	if ((millis() - prev_time) < USER_LOOP_INTERVAL)
+		return;
+	else
+		prev_time = millis();
 #if 0
 	struct neurite_data_s *nd = &g_nd;
 	static int adc_prev = 0;
@@ -1136,7 +1149,7 @@
 				analogWrite(14, 1023);
 	}
 	char *token = NULL;
-	char *msg = (char *)malloc(64);
+	char *msg = (char *)malloc(MQTT_MSG_LEN);
 	__bzero(msg, sizeof(msg));
 	for (int i = 0; i < length; i++)
 		msg[i] = payload[i];
@@ -1145,12 +1158,18 @@
 	if (token == NULL) {
 		log_warn("no payload, ignore\n\r");
 	} else if (strcmp(token, "light:") == 0) {
-		int val = atoi(&msg[7]);
-		analogWrite(14, val);
+		token = strtok(NULL, "\0");
+		if (token) {
+			int val = atoi(token);
+			analogWrite(14, val);
+		}
 	} else if (strcmp(token, "servo:") == 0) {
-		int val = atoi(&msg[7]);
-		log_dbg("hit servo, msg(value): %s(%d)\n\r", &msg[7], val);
-		myservo.write(val);
+		token = strtok(NULL, "\0");
+		if (token) {
+			int val = atoi(token);
+			log_dbg("hit servo, msg(value): %s(%d)\n\r", token, val);
+			myservo.write(val);
+		}
 	} else {
 	}
 	free(msg);
@@ -1166,15 +1185,10 @@
 			static int val = 0;
 			char buf[4];
 			val = 1 - val;
-#if 0
-			sprintf(buf, "%d", val);
-			mqtt_cli.publish("/neuro/neurite-000c1636/io", (const char *)buf);
-#else
 			if (val)
 				mqtt_cli.publish("/neuro/chatroom", "light on");
 			else
 				mqtt_cli.publish("/neuro/chatroom", "light off");
-#endif
 		}
 #if 0
 		/* some experiment */
@@ -1215,6 +1229,5 @@
 	myservo.attach(13);
 	pinMode(14, OUTPUT);
 	analogWrite(14, 1023);
-	ticker_user.attach_ms(20, ticker_user_task);
-}
-#endif
+}
+#endif


tried to get to work with firmata, still problem with serials crossing

--- Sensorizer.ino
+++ Sensorizer.ino
@@ -1,7 +1,7 @@
 //uncomment this to set serial baud at bluetooth rate. otherwise, USB rate.
 //# define IS_BLUETOOTH

-#define ENABLE_TEST 1
+#define ENABLE_TEST 0
 #define DISABLE_FIRMATA 1

 #include <SoftwareSerial.h>
@@ -335,8 +335,6 @@
  *============================================================================*/
 void setup()
 {
-  Serial.println("BEGIN SETUP");
-
   byte i;

   Firmata.setFirmwareVersion(2, 2);
@@ -363,7 +361,7 @@
       setPinModeCallback(i, ANALOG);
     } else {
       // sets the output to 0, configures portConfigInputs
-      setPinModeCallback(i, OUTPUT);
+      //setPinModeCallback(i, OUTPUT);
     }
   }
   // by defult, do not report any analog inputs
@@ -375,12 +373,16 @@
 #else
   Firmata.begin(115200);
 #endif
+  //Firmata.begin(Serial);

   /* send digital inputs to set the initial state on the host computer,
    * since once in the loop(), this firmware will only send on change */
   for (i=0; i < TOTAL_PORTS; i++) {
-    outputPort(i, readPort(i, portConfigInputs[i]), true);
-  }
+    //outputPort(i, readPort(i, portConfigInputs[i]), true);
+  }
+
+
+  server.init();

   Serial.println("END SETUP");
 }
@@ -394,12 +396,12 @@

   /* DIGITALREAD - as fast as possible, check for changes and output them to the
    * FTDI buffer using Serial.print()  */
-  checkDigitalInputs();
+  //checkDigitalInputs();

   /* SERIALREAD - processing incoming messagse as soon as possible, while still
    * checking digital inputs.  */
-  while(Firmata.available())
-    Firmata.processInput();
+  //while(Firmata.available())
+  //  Firmata.processInput();

   /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over
    * 60 bytes. use a timer to sending an event character every 4 ms to
@@ -419,7 +421,7 @@
           server.readPin(pin, val);
 #endif

-          Firmata.sendAnalog(analogPin, val);
+          //Firmata.sendAnalog(analogPin, val);
         }
       }
     }
@@ -439,7 +441,7 @@

 #if ENABLE_TEST
-#define TEST_MAX 500
+#define TEST_MAX 90
 #define TEST_INTERVAL 50000

 int testCounter = -TEST_INTERVAL;
@@ -488,9 +490,12 @@

   server.init();
 }
-
+int thePin = 0;
 void loop() {
-  //testUpdate();
+#if ENABLE_TEST
+  testUpdate();
+  return;
+#endif

   while(Serial.available() == 0) ;

@@ -508,7 +513,14 @@
   //For this bank 0x78, the instrument does not matter, only the note
   //noteOn(0, note, 60);

-  server.readPin(1, 90);
+  thePin = (thePin + 1) % 6;
+
+  if (note < 60)
+    server.readPin(thePin, 0);
+  else if (note < 75)
+    server.readPin(thePin, note);
+  else
+    server.readPin(thePin, 1024);
   //Note will dissapate automatically


include freestack.h

include freestack.h

--- src/payload/payload.ino
+++ src/payload/payload.ino
@@ -13,7 +13,7 @@
 #include <SdFat.h>
 #include <SdFatConfig.h>
 #include <SysCall.h>
-//#include <FreeStack.h> // something is wrong with this library.
+#include <FreeStack.h> // something is wrong with this library.

 void setup() {


Commenting out import

Commenting out import

--- TeensyQuad.ino
+++ TeensyQuad.ino
@@ -6,7 +6,7 @@
 #include <L3G.h>
 #include <ADXL345.h>
 #include <HMC5883L.h>
-#include <Adafruit_BMP085.h>
+//#include <Adafruit_BMP085.h>
 #include <Servo.h>

 // Radio input values.


4 leg-system

4 leg-system

--- hardware/legsystem/legsystem.ino
+++ hardware/legsystem/legsystem.ino
@@ -17,54 +17,31 @@
 #define CALIB_MAX_M3 512
 #define CALIB_MIN_M3 100

+#define CALIB_MAX_M4 512
+#define CALIB_MIN_M4 100
+
 #define SAMPLE_DELAY 25 // in ms, 50ms seems good

 uint8_t recordButtonPin = 12;
 uint8_t playButtonPin = 7;
 uint8_t ledPin = 13;

-uint8_t servoPinM1 = 9;
+uint8_t servoPinM1 = 5;
 uint8_t feedbackPinM1 = A0;

-uint8_t servoPinM2 = 10;
+uint8_t servoPinM2 = 6;
 uint8_t feedbackPinM2 = A1;

-uint8_t servoPinM3 = 11;
+uint8_t servoPinM3 = 10;
 uint8_t feedbackPinM3 = A2;
+
+uint8_t servoPinM4 = 11;
+uint8_t feedbackPinM4 = A3;

 Servo m1Servo;
 Servo m2Servo;
 Servo m3Servo;
-
-/*
-// Calibration values
-int minDegrees;
-int maxDegrees;
-int minFeedback;
-int maxFeedback;
-int tolerance = 2; // max feedback measurement error
-
-*/
-/*
-  This function establishes the feedback values for 2 positions of the servo.
-  With this information, we can interpolate feedback values for intermediate positions
-*/
-/*
-void calibrate(Servo servo, int analogPin, int minPos, int maxPos)
-{
-  // Move to the minimum position and record the feedback value
-  servo.write(minPos);
-  minDegrees = minPos;
-  delay(2000); // make sure it has time to get there and settle
-  minFeedback = analogRead(analogPin);
-
-  // Move to the maximum position and record the feedback value
-  servo.write(maxPos);
-  maxDegrees = maxPos;
-  delay(2000); // make sure it has time to get there and settle
-  maxFeedback = analogRead(analogPin);
-}
-*/
+Servo m4Servo;

 void setup() {
@@ -88,14 +65,14 @@

   Serial.println("Servo RecordPlay");

-  // need to do calibration
-  //m1Servo.attach(servoM1Pin);
-  //calibrate(m1Servo, feedbackM1Pin, 20, 160);  // calibrate for the 20-160 degree range
-  //m1Servo.detach();
+  // need to do manual calibration
 }

 // main loop
 void loop() {
+
+  //Serial.println(analogRead(A5));
+  //delay(10);

    // record new sequence
    if (! digitalRead(recordButtonPin)) {
@@ -123,15 +100,43 @@
   Serial.println("Playing");

   m1Servo.attach(servoPinM1);
+  m2Servo.attach(servoPinM2);
+  m3Servo.attach(servoPinM3);
+  m4Servo.attach(servoPinM4);
+
   while (digitalRead(playButtonPin)) {
     uint8_t x = EEPROM.read(addr);
-    if ((addr % 3) == 0){
+    if ((addr % 4) == 0){
       Serial.print("Read M1: "); Serial.print(x);
       if (x == 255) break;
       // map to 0-180 degrees
       x = map(x, 0, 254, 0, 180);
       Serial.print(" -> "); Serial.println(x);
       m1Servo.write(x);
+    }
+    if ((addr % 4) == 1){
+      Serial.print("Read M2: "); Serial.print(x);
+      if (x == 255) break;
+      // map to 0-180 degrees
+      x = map(x, 0, 254, 0, 180);
+      Serial.print(" -> "); Serial.println(x);
+      m2Servo.write(x);
+    }
+    if ((addr % 4) == 2){
+      Serial.print("Read M3: "); Serial.print(x);
+      if (x == 255) break;
+      // map to 0-180 degrees
+      x = map(x, 0, 254, 0, 180);
+      Serial.print(" -> "); Serial.println(x);
+      m3Servo.write(x);
+    }
+    if ((addr % 4) == 3){
+      Serial.print("Read M4: "); Serial.print(x);
+      if (x == 255) break;
+      // map to 0-180 degrees
+      x = map(x, 0, 254, 0, 180);
+      Serial.print(" -> "); Serial.println(x);
+      m4Servo.write(x);
     }
     delay(SAMPLE_DELAY);

@@ -140,6 +145,9 @@
   }
   Serial.println("Done");
   m1Servo.detach();
+  m2Servo.detach();
+  m3Servo.detach();
+  m4Servo.detach();
   delay(250);
 }

@@ -153,15 +161,43 @@

   // check if button pressed (as stop recording)
   while (digitalRead(recordButtonPin)) {
-     uint16_t a = analogRead(feedbackPinM1);
-     if ((addr % 3) == 0){
-       Serial.print("Read M1 analog: "); Serial.print(a);
-       if (a < CALIB_MIN_M1) a = CALIB_MIN_M1;
-       if (a > CALIB_MAX_M1) a = CALIB_MAX_M1;
-       a = map(a, CALIB_MIN_M1, CALIB_MAX_M1, 0, 254);
-       Serial.print(" -> "); Serial.println(a);
-       EEPROM.write(addr, a);
-     }
+     uint16_t a1 = analogRead(feedbackPinM1);
+     if ((addr % 4) == 0){
+       Serial.print("Read M1 analog: "); Serial.print(a1);
+       if (a1 < CALIB_MIN_M1) a1 = CALIB_MIN_M1;
+       if (a1 > CALIB_MAX_M1) a1 = CALIB_MAX_M1;
+       a1 = map(a1, CALIB_MIN_M1, CALIB_MAX_M1, 0, 254);
+       Serial.print(" -> "); Serial.println(a1);
+       EEPROM.write(addr, a1);
+     }
+     uint16_t a2 = analogRead(feedbackPinM2);
+     if ((addr % 4) == 1){
+       Serial.print("Read M2 analog: "); Serial.print(a2);
+       if (a2 < CALIB_MIN_M2) a2 = CALIB_MIN_M2;
+       if (a2 > CALIB_MAX_M2) a2 = CALIB_MAX_M2;
+       a2 = map(a2, CALIB_MIN_M2, CALIB_MAX_M2, 0, 254);
+       Serial.print(" -> "); Serial.println(a2);
+       EEPROM.write(addr, a2);
+     }
+     uint16_t a3 = analogRead(feedbackPinM3);
+     if ((addr % 4) == 2){
+       Serial.print("Read M3 analog: "); Serial.print(a2);
+       if (a3 < CALIB_MIN_M3) a3 = CALIB_MIN_M3;
+       if (a3 > CALIB_MAX_M3) a3 = CALIB_MAX_M3;
+       a3 = map(a3, CALIB_MIN_M3, CALIB_MAX_M3, 0, 254);
+       Serial.print(" -> "); Serial.println(a3);
+       EEPROM.write(addr, a3);
+     }
+     uint16_t a4 = analogRead(feedbackPinM4);
+     if ((addr % 4) == 3){
+       Serial.print("Read M4 analog: "); Serial.print(a2);
+       if (a4 < CALIB_MIN_M4) a4 = CALIB_MIN_M4;
+       if (a4 > CALIB_MAX_M4) a4 = CALIB_MAX_M4;
+       a4 = map(a4, CALIB_MIN_M4, CALIB_MAX_M4, 0, 254);
+       Serial.print(" -> "); Serial.println(a4);
+       EEPROM.write(addr, a4);
+     }
+
      addr++;
      if (addr == 512) break;
      delay(SAMPLE_DELAY);
@@ -177,21 +213,4 @@
   //       make a buffer where it can be loaded dynamically from host computer (Raspi)
 }

-/*
-void Seek(Servo servo, int analogPin, int pos)
-{
-  // Start the move...
-  servo.write(pos);
-
-  // Calculate the target feedback value for the final position
-  int target = map(pos, minDegrees, maxDegrees, minFeedback, maxFeedback);
-
-  // Wait until it reaches the target
-  while(abs(analogRead(analogPin) - target) > tolerance){} // wait...
-}
-
-int getPos(int analogPin)
-{
-  return map(analogRead(analogPin), minFeedback, maxFeedback, minDegrees, maxDegrees);
-}
-*/
+


Remove experimental

Remove experimental

--- examples/Widgets/RTC/RTC.ino
+++ examples/Widgets/RTC/RTC.ino
@@ -31,7 +31,6 @@
  *
  **************************************************************/

-#define BLYNK_EXPERIMENTAL
 #define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
 #include <SPI.h>
 #include <Ethernet.h>


comments

comments

--- examples/central/central.ino
+++ examples/central/central.ino
@@ -1,5 +1,5 @@
 /*
- * Examples for AT command
+ * Central role example
  */

 #include "BLEPad_UART.h"
@@ -26,17 +26,19 @@
 };

 void loop() {
-  // Examples for AT commands
+  // Execute AT commands step by step
   unsigned long currentMillis = millis();
   if (currentMillis - previousMillis >= interval) {
     previousMillis = currentMillis;
     switch (i) {
       case 0:
         // Must reset for change role
+        // Change to central role
         ble.setRole(BLEPAD_MASTER_MODE);
         ble.write("<RESET>");
         break;
       case 1:
+        // Query the ROLE type, it should show central
         ble.write("<ROLETYPE>");
         break;
       case 2:
@@ -49,6 +51,7 @@
     i++;
   }

+  // show the response for AT command
   while (ble.available() > 0)  {
     tmp += char(ble.read());
     delay(2);


Fixed space in timestamp

Fixed space in timestamp

--- SenseBox-Arduino-Sketch/SenseBox-Arduino-Sketch.ino
+++ SenseBox-Arduino-Sketch/SenseBox-Arduino-Sketch.ino
@@ -159,7 +159,7 @@
       else
       {
         char sz[24];
-        sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
+        sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d",
                 month, day, year, hour, minute, second);
         //Serial.print(sz);
         dattim = String(sz);


Use FastSPI_LED2 library (need own xy-grid implementation)

--- MatrixEffect/MatrixEffect.ino
+++ MatrixEffect/MatrixEffect.ino
@@ -1,14 +1,14 @@
-#include "SPI.h"
-#include "Adafruit_WS2801.h"
+#include "FastSPI_LED2.h"

-Adafruit_WS2801 grid = Adafruit_WS2801((uint8_t)10, (uint8_t)10);
+#define ROWS 10
+#define COLS 10
+#define NUM_LEDS (ROWS*COLS)

+CRGB leds[NUM_LEDS];

 #define LOOP_TIME 50
 #define UPDATE_TIME 150

-#define ROWS 10
-#define COLS 10
 #define _R 0
 #define _G 1
 #define _B 2
@@ -17,15 +17,29 @@
 byte new_colors[ROWS][COLS][3];

+// Return 0-based led index for 0-based x and y grid co-ordinate values
+// The LED string snakes through the grid, so every row the positive x direction switches
+uint8_t xy2i(uint8_t x, uint8_t y){
+  if(y%2){
+    // It's an uneven row: x should be reversed---or subtracted from the next row's first i
+    return COLS*(y+1) - 1 - x;
+  } else {
+    // Even row: simply do COLS*y + x
+    return COLS*y + x;
+  }
+}
+
 void sendColors(){
   for(uint8_t y=0; y<ROWS; ++y)
     for(uint8_t x=0; x<COLS; ++x){
       for(uint8_t i=0; i<3; ++i)
         colors[y][x][i] = (uint8_t) (colors[y][x][i]*19.0/20.0 + new_colors[y][x][i]/20.0);

-      grid.setPixelColor(x,y,colors[y][x][0],colors[y][x][1],colors[y][x][2]);
+      leds[xy2i(x,y)] = CRGB(colors[y][x][0],colors[y][x][1],colors[y][x][2]);
+      // grid.setPixelColor(x,y,colors[y][x][0],colors[y][x][1],colors[y][x][2]);
     }
-  grid.show();
+  // grid.show();
+  LEDS.show();
 }

 /*
@@ -114,9 +128,14 @@
 }

 void setup(){
-
-  grid.begin();
-  grid.show();
+  delay(1000);
+  LEDS.addLeds<WS2801, RGB>(leds, NUM_LEDS);
+  LEDS.setBrightness(64);
+
+  for(uint8_t i=0; i<NUM_LEDS; ++i){
+    leds[i] = CRGB::Black;
+  }
+  LEDS.show();

   // Turn off all LEDs, initialise pixel seeds on first row
   for(uint8_t y=0; y<ROWS; ++y)


-Use interrupt touch.

-Use interrupt touch.

--- tfttask.ino
+++ tfttask.ino
@@ -137,7 +137,7 @@
     lastStatus = lightStatus;
   }

-  if ( touch.touched() )
+  if ( touch.tirqTouched() )
   {
     TS_Point p = touch.getPoint();


fix bug

fix bug

--- Arduino/linkit_duo_led7/linkit_duo_led7.ino
+++ Arduino/linkit_duo_led7/linkit_duo_led7.ino
@@ -39,7 +39,7 @@
     ::process_commands("16:stm:1:zon:blk:blk:2:zon:1:rev:blk:blk::rst");
     ::process_commands("17:stm:3:zon:blk:blk:4:zon:1:rev:blk:blk:rst");
     ::process_commands("18:stm:5:zon:blk:blk:6:zon:1:rev:blk:blk:rst");
-    ::process_commands("19:stm:0,11:sch:0,12:sch:0,13:sch");
+    ::process_commands("19:stm:0,12:sch:0,13:sch:0,14:sch");

     // bubbling up dots
     ::process_commands("20:stm:50,21:sch:50,22:sch:25,23:sch");


moved the sound addresses to the define block

--- tictactoe/tictactoe.ino
+++ tictactoe/tictactoe.ino
@@ -6,9 +6,17 @@
 #include <SM125.h> //RFID
 #include <SoundPlayer.h>

+// Hardware addresses
 #define DISPLAY_ADDRESS  0x51
 #define BUTTONS_CHANGE   43
 #define SM125_ADDRESS 0x46
+// Sound addresses
+#define WELCOME 0x5 //Welcome screen
+#define YOU_WIN 0x1 //The Player wins
+#define YOU_LOSE 0x2 //The Rival wins
+#define VICTORY_LOOP 0x3 //Victory loop!!!
+#define NO_NO 0x4 //Illegal move
+

 // Baseboard screen
 GraphicDisplay display;
@@ -111,10 +119,12 @@
         waitForMove = false;
       } else if (player_move == -2){
         // Player has moved 2 pieces, illegal move
-        msgAndWait("You moved two pieces! Correct you move.");
+        msgAndWait("You moved two pieces! Correct you move.");
+        soundPlayer.play(NO_NO);
       } else if (player_move == -3){
         // Player has moved the piece into an square already used.
         msgAndWait("You moved your piece into an already used square! Correct you move.");
+        soundPlayer.play(NO_NO);
       }
     }

@@ -125,7 +135,7 @@
     greenVictory = checkWin(greenStatus);
     if (greenVictory){
       printMsg("A winner is you"); //TODO think some proper msgs
-      soundPlayer.play(0x5);
+      soundPlayer.play(YOU_WIN);
       victoryLoop('g');
     }
   }
@@ -157,7 +167,8 @@
     // 3 -Check victory conditions
     redVictory = checkWin(redStatus);
     if (redVictory){
-      printMsg("You lose!");
+      printMsg("You lose!");
+     soundPlayer.play(YOU_LOSE);
       victoryLoop('r');
     }
   }
@@ -216,7 +227,7 @@
   display.clear();
   soundPlayer.stop();
   display.printText("Welcome to the tictactoe game!", 6, 1, BLUE);
-  soundPlayer.play(0x5);
+  soundPlayer.play(WELCOME);
   delay(1000);
   display.clear();
   display.printText("Press green button to find another player...", 6, 1, GREEN);
@@ -408,6 +419,7 @@

 void victoryLoop(char color){
   boolean doVictory = true;
+  soundPlayer.play(VICTORY_LOOP);
   while (doVictory){
     for (int i=0; i < 9; i++){
       clearSquares();
@@ -432,6 +444,7 @@
       // Green button
       if ((reply & 0x04) == 0x00){
           doVictory = false;
+          soundPlayer.stop();
           // new game!
           restartGame();
       }


comments updates

comments updates

few lines added of comments corrected

--- CHMachine_Arduino/CHMachine_Arduino.ino
+++ CHMachine_Arduino/CHMachine_Arduino.ino
@@ -104,7 +104,7 @@
     knobstate = 0;
     encoderValue = 0;

-    if (Serial.peek() == 'V') {      //check for the character that signifies that this will be on
+    if (Serial.peek() == 'V') {      //The 'V' character preced the PWM value for the PWM pin
       Serial.read();                 //remove the first character(V)
       Value = Serial.parseInt();     //read the value
       Serial.read();                 //remove the last character(S)
@@ -113,13 +113,13 @@
     }

-    else if (Serial.peek() == 'K') {      //the character K must be sent to reset the timer and keep the analog pin ON
+    else if (Serial.peek() == 'K') {      //the character 'K' reset the timer and keep the analog pin ON (if the connection is lost the pin goes LOW for safety precaution)
       Serial.read();                 //remove the first character
       timer = millis();              //reset the timer
     }

-    else if (Serial.peek() == 'T') {      //check for the character T that estabilish the connection
-      Serial.read();   //clean the serial buffer
+    else if (Serial.peek() == 'T') {      //the character 'T' is used to check if the connection is established
+      Serial.read();                      //clean the serial buffer
       Serial.println("connOK");         //send a string

@@ -130,11 +130,11 @@

   }

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

-
+////rotary encoder stuffs:
   if (knobstate == 1) {
     updateButton();


Update Master-board.ino

Update Master-board.ino

--- Firmware/Ball/Master-Board/Master-board.ino
+++ Firmware/Ball/Master-Board/Master-board.ino
@@ -41,25 +41,43 @@
   EXEMPLE COMMAND
   ===============

+  Argument List
+
+  a = Speed Motor A       / Step per second
+  b = Speed Motor B       / Step per second
+  c = Direction Motor A  / 1 = Front | 0 = Back
+  d = direction motor B  / 1 = Front | 0 = Back
+
 */

-#include "Wire.h"
-#include "MPU6050.h"
-
-#include <SPI.h>
-#include <nRF24L01.h>
-#include <RF24.h>
-#include <RF24_config.h>
-#include "PCF8574.h"
+#include "Wire.h"       .// For I2C
+#include "MPU6050.h"     // For the gyroscope MPU6050
+#include "PCF8574.h"     // For the PCF8574
+
+#include <SPI.h>         // For the SPI
+#include <nRF24L01.h>    // For the Wireless remote controll i/o
+#include <RF24.h>        // Idem
+#include <RF24_config.h> // Idem

 int i2cAdress      = 1;

 int pinDirA        = 2;      // PIN DIRECTION FOR X
 int pinStepA       = 3;      // PIN STEP FOR X
+
 int pinEnable      = 4;      // Activation off all stepper

 int pinDirB        = 5;      // PIN DIRECTION FOR Y
 int pinStepB       = 6;      // PIN STEP FOR Y
+
+int speedA         = 0;
+int speedB         = 0;
+bool runA          = false;
+bool runB          = false;
+bool dirA          = true;   // true = Front | false = back
+bool dirB          = true;   // true = Front | false = back
+
+bool invertA       = false;
+bool invertB       = false;

 int CurrentBat1    = 0;
 int CurrentBat2    = 1;
@@ -76,6 +94,19 @@
 bool ifPing        = false;
 bool emgStop       = false;
 bool production    = false;
+
+int setpointX      = 0;
+int setpointY      = 0;
+int multiplier     = 0;
+int hysteresis     = 0;
+bool invertXY      = 0;
+bool invertX       = 0;
+bool invertY       = 0;
+
+unsigned long currentA = 0;
+unsigned long previousMillisA = 0;
+unsigned long currentB = 0;
+unsigned long previousMillisB = 0;

 unsigned long trigSec  = 1000;
 unsigned long trigS    = 0;
@@ -119,37 +150,47 @@
     pinMode( PING        , OUTPUT );

 	Serial.begin(9600);
-	Serial.println("Booting up...");
+
+
+    Serial.println("==================================================");
+	Serial.println("  _______ ______     _     _  ______  ____ ______ ");
+	Serial.println(" (____   (____  )   | |   | |/ ___  |(____|______)");
+	Serial.println("  ____)  )____)  )__| |   | | |   | | | |   | |   ");
+	Serial.println(" |  __  (|  __  (___) |   | | |   | | | |   | |   ");
+	Serial.println(" | |__)  ) |__)  )  | |___| | |   | |_| |_  | |   ");
+	Serial.println(" |______/|______/   |______/|_|   |_(_____) |_|   ");
+	Serial.println("            _ Astromech Industrie _               ");
+	Serial.println("      > https://github.com/Gruniek/BB-UNIT <      ");
+	Serial.println("           > http://r2builders.fr/ <              ");
+	Serial.print("           FIRMWARE VERSION : ");
+	Serial.print(version);
+	Serial.println("               ");
+    Serial.println("==================================================");
+
     Serial.println(" ");
-    Serial.println("_ Astromech Industrie _");
-    Serial.print("  BB-8 Version ");
-    Serial.println(version);
-    Serial.println("===================");
-    Serial.println(" ");
-
-
-
-
-    Serial.print("Initializing I2C devices...  I2C ADRESS :");
+	Serial.println("[1]-Booting up...");
+
+    Serial.print("[2]-Initializing I2C devices...  I2C ADRESS : ");
     Serial.print(i2cAdress);

     Wire.begin(i2cAdress);

+    Serial.println("[3]-Connect to the MPU6050... ");
     accelgyro.initialize();
-	Serial.println(" [ OK ]");
-
-    Serial.print("Connect to the MPU6050 : ");
-    Serial.println(accelgyro.testConnection());
-    //Serial.println(accelgyro.testConnection() ? "Connection successful" : "Connection failed");
-
-    Serial.println("Initializing RF24 devices...  ");
+
+    //Serial.println(accelgyro.testConnection());
+    Serial.println(accelgyro.testConnection() ? "Connection successful" : "Connection failed");
+
+    Serial.println("[4]-Initializing RF24 devices...  ");
     radio.begin();
     radio.openWritingPipe(pipe);
     radio.startListening();

     /* Start I2C bus and PCF8574 instance */
+    Serial.print("[5]-Initializing PCF8574...");
   	expander.begin(0x20);
-
+
+    Serial.print("[6]-Setup pinout of the PCF8574...");
   	/* Setup some PCF8574 pins for demo */
   	expander.pinMode(0, OUTPUT);
   	expander.pinMode(1, OUTPUT);
@@ -159,28 +200,16 @@
     expander.pinMode(5, OUTPUT);
     expander.pinMode(6, OUTPUT);
     expander.pinMode(7, OUTPUT);
-
-    Serial.println("Booting successful !");
-    Serial.println("====================");
+
+    Serial.println("========================");
+    Serial.println("[7]-Booting successful !");
+    Serial.println("========================");

 }

 void loop()
 {
-	/* SEND
-	String theMessage = "Hello there!";
-	int messageSize = theMessage.length();
-	for (int i = 0; i < messageSize; i++)
-	{
-    	int charToSend[1];
-    	charToSend[0] = theMessage.charAt(i);
-    	radio.write(charToSend,1);
-  	}
-
-	msg[0] = 2;
-    radio.write(msg,1);
-    */
-
+	// GET DATA FROM REMOTE
     if (radio.available())
     {
     	bool done = false;
@@ -201,7 +230,7 @@
 			// Copy it over
 			theMessage.toCharArray(msg, str_len);

-    		if (strcmp(strtok(msg, " "), "SET") == 0)
+    		if (strcmp(strtok(msg, " "), "MOVE") == 0)
     		{
         		Serial.println("UPDATE SETPOINT");
       			// trouvé le message
@@ -211,28 +240,143 @@
         			int val = atoi(p + 1);
         			switch (*p)
         			{
-          			//	case 'x': setpointX  = val; break;
-          			//	case 'y': setpointY  = val; break;
-      	  			//	case 'm': multiplier = val; break;
-      				//	case 'i': invertXY   = val; break;
-      				//	case 'j': invertX    = val; break;
-      				//	case 'k': invertX    = val; break;
-      				//	case 'h': hysteresis = val; break;
+          				case 'a': speedA  = val; break;
+          				case 'b': speedB  = val; break;
+      	  				case 'c': dirA    = val; break;
+      					case 'd': dirB    = val; break;
         			}
       			}
     		}
+
+       		if (strcmp(strtok(msg, " "), "HEADSET") == 0)
+    		{
+        		Serial.println("UPDATE SETPOINT");
+      			// trouvé le message
+      			char *p;
+      			while ((p = strtok(NULL, " ")) != NULL)
+      			{
+        			int val = atoi(p + 1);
+        			switch (*p)
+        			{
+          				case 'x': setpointX  = val; break;
+          				case 'y': setpointY  = val; break;
+      	  				case 'm': multiplier = val; break;
+      					case 'i': invertXY   = val; break;
+      					case 'j': invertX    = val; break;
+      					case 'k': invertY    = val; break;
+      					case 'h': hysteresis = val; break;
+        			}
+      			}
+    		}
+    		Serial.print("SET x");
+    		Serial.print(setpointX);
+    		Serial.print(" y");
+    		Serial.print(setpointY);
+    		Serial.print(" m");
+    		Serial.print(multiplier);
+    		Serial.print(" i");
+    		Serial.print(invertXY);
+    		Serial.print(" j");
+    		Serial.print(invertX);
+    		Serial.print(" k");
+    		Serial.print(invertY);
+    		Serial.print(" h");
+    		Serial.println(hysteresis);
+
+
+       		if (strcmp(strtok(msg, " "), "HEADROTATE") == 0)
+    		{
+        		Serial.println("UPDATE SETPOINT");
+      			// trouvé le message
+      			char *p;
+      			while ((p = strtok(NULL, " ")) != NULL)
+      			{
+        			int val = atoi(p + 1);
+        			switch (*p)
+        			{
+          				case 'd': setpointX  = val; break;
+          				case 's': setpointY  = val; break;
+        			}
+      			}
+    		}
+    		Serial.print("ROTATE d");
+    		Serial.print(setpointX);
+    		Serial.print(" y");
+    		Serial.print(setpointY);
+    		Serial.print(" m");
+    		Serial.print(multiplier);
+    		Serial.print(" i");
+    		Serial.print(invertXY);
+    		Serial.print(" j");
+    		Serial.print(invertX);
+    		Serial.print(" k");
+    		Serial.print(invertY);
+    		Serial.print(" h");
+    		Serial.println(hysteresis);
+
        		theMessage= "";
       	}
    }

-
-
-
-
-
-
-
+	// MOTOR A (Left)
+	// Run the motor
+	if(speedA > 0) runA = true;
+	else runA = false;
+	speedA = 1000 / speedA;
+
+	// Motor direction / With inversion
+	if(invertA)
+  	{
+    	if(dirA) dirA = false;
+    	else dirA = true;
+  	}
+	digitalWrite(pinDirA, dirA); // Set the direction
+
+	// Send Step inpultion to the motor
+	unsigned long currentA = millis(); // millis();
+   	if (currentA - previousMillisA >= speedA)
+   	{
+      	previousMillisA = currentA;
+
+      	if(runA)
+      	{
+        	digitalWrite(pinStepA, 1);
+        	delayMicroseconds( 500 );
+        	digitalWrite(pinStepA, 0);
+        	delayMicroseconds( 500 );
+      	}
+  	}
+
+	// MOTOR B (Right)
+	// Run the motor
+	if(speedB > 0) runB = true;
+	else runB = false;
+	speedB = 1000 / speedB;
+
+	// Motor direction / With inversion
+	if(invertB)
+  	{
+    	if(dirB) dirB = false;
+    	else dirB = true;
+  	}
+	digitalWrite(pinDirB, dirB); // Set the direction
+
+	// Send Step inpultion to the motor
+	unsigned long currentB = millis(); // millis();
+   	if (currentB - previousMillisB >= speedB)
+   	{
+      	previousMillisB = currentB;
+
+      	if(runB)
+      	{
+        	digitalWrite(pinStepB, 1);
+        	delayMicroseconds( 500 );
+        	digitalWrite(pinStepB, 0);
+        	delayMicroseconds( 500 );
+      	}
+  	}
+

@@ -286,6 +430,21 @@
     			production = true;
     		}
     	}
+
+
+    	// SEND RF24 //
+		String theMessage = "Hello there!";
+		int messageSize = theMessage.length();
+		for (int i = 0; i < messageSize; i++)
+		{
+    		int charToSend[1];
+    		charToSend[0] = theMessage.charAt(i);
+    		radio.write(charToSend,1);
+  		}
+
+		msg[0] = 2;
+    	radio.write(msg,1);
+
     }

 }


calculate two minute average; added state machine

--- sketches/LaundryMeasure/LaundryMeasure.ino
+++ sketches/LaundryMeasure/LaundryMeasure.ino
@@ -56,6 +56,16 @@
 double rmsValue = 0.0;
 double peakValue = 0.0;

+#define NUMMEASURE 24
+double twoMinuteMeasurements[NUMMEASURE];
+double twoMinuteAverage = 0.0;
+double twoMinuteSum = 0.0;
+unsigned int MeasurementCounter = 0;
+bool enoughMeasurements = false;
+bool calibrated = false;
+
+unsigned int globalState = 0;
+
 unsigned int debounceInterval = 200;
 unsigned int lastJoystick = 0;
 bool triggeredJoystick = false;
@@ -77,6 +87,9 @@
 #define OFFSET 8820
 #define SCALE (1.65/OFFSET)
 #define VTOA (22.0/1.65)
+
+#define TENTHOUSAND 10000.0
+double calibrationOffset = 3.867123;

 double Volts(int digits)
 {
@@ -104,6 +117,71 @@
     }
     peakValue = sqrt(value);
     return VTOA * sqrt(sumSquares / (double)samples);
+}
+
+void calcAverage(double value)
+{
+    MeasurementCounter++;
+    if(!enoughMeasurements && MeasurementCounter >= NUMMEASURE)
+    {
+        enoughMeasurements = true;
+    }
+    if(enoughMeasurements)
+    {
+        twoMinuteSum -= twoMinuteMeasurements[MeasurementCounter%NUMMEASURE];
+    }
+    twoMinuteSum += value;
+    twoMinuteAverage = twoMinuteSum / NUMMEASURE;
+    twoMinuteMeasurements[MeasurementCounter%NUMMEASURE] = value;
+}
+
+void updateStatemachine()
+{
+    switch(globalState)
+    {
+        case 0:
+            if( twoMinuteAverage > 1 )
+            {
+                globalState = 1;
+            }
+            break;
+        case 1:
+            if( twoMinuteAverage > 10 )
+            {
+                globalState = 2;
+            }
+            break;
+        case 2:
+            if( twoMinuteAverage > 2000 )
+            {
+                globalState = 3;
+            }
+            break;
+        case 3:
+            if( twoMinuteAverage < 1000 )
+            {
+                globalState = 4;
+            }
+            break;
+        case 4:
+            if( twoMinuteAverage > 1000 )
+            {
+                globalState = 5;
+            }
+            break;
+        case 5:
+            if( twoMinuteAverage < 10 )
+            {
+                globalState = 6;
+            }
+            break;
+        case 6:
+            if( twoMinuteAverage < 1 )
+            {
+                globalState = 0;
+            }
+            break;
+    }
 }

 void msOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {
@@ -130,9 +208,12 @@
     /* display->drawString(0 + x, 10 + y, "Arial 10"); */

     display->setFont(ArialMT_Plain_16);
-    display->drawString(0 + x, 17 + y, "Digits: " + String( ads.readADC_SingleEnded(1) ) );
-    display->drawString(0 + x, 28 + y, "Volts:  " + String( Volts(ads.readADC_SingleEnded(1)) ) );
-    display->drawString(0 + x, 39 + y, "Amps:   " + String( rmsValue ) + " " + String(peakValue) );
+    display->drawString(0 + x, 13 + y, "Irms: " + String( rmsValue, 6 ) );
+    display->drawString(0 + x, 26 + y, "Iavg: " + String( twoMinuteAverage ) );
+    display->drawString(0 + x, 39 + y, "Mcnt: " + String( MeasurementCounter%NUMMEASURE ) );
+    /* display->drawString(0 + x, 17 + y, "Digits: " + String( ads.readADC_SingleEnded(1) ) ); */
+    /* display->drawString(0 + x, 28 + y, "Volts:  " + String( Volts(ads.readADC_SingleEnded(1)) ) ); */
+    /* display->drawString(0 + x, 39 + y, "Amps:   " + String( rmsValue ) + " " + String(peakValue) ); */

     /* display->setFont(ArialMT_Plain_24); */
     /* display->drawString(0 + x, 34 + y, "Arial 24"); */
@@ -352,6 +433,13 @@
     if( (millis() - rmsLastUpdate) > rmsInterval )
     {
         rmsValue = Irms(1);
+        if(!calibrated)
+        {
+            calibrationOffset = rmsValue;
+            calibrated = true;
+        }
+        double measurement = (rmsValue - calibrationOffset) * TENTHOUSAND ;
+        calcAverage(measurement);
         Serial.printf("%d Irms: ", millis());
         Serial.print(rmsValue);
         Serial.println("");


[mm] Update disconnected display on connect failure to show err

--- arduino/MeterMonitor/MeterMonitor.ino
+++ arduino/MeterMonitor/MeterMonitor.ino
@@ -108,6 +108,10 @@
 {
   Serial.print(F("Socket Error ")); Serial.println(err);
   g_LastClientError = err;
+
+  // There's no "disconnect" event if never connected, so trigger display err
+  if (hm.getProtocolState() == HeaterMeterClient::hpsConnecting)
+    ledsShowDisconnected();
 }

 static void proxy_onWifiConnect(void)


Stay awake for a minute

Stay awake for a minute

--- arduino/stair_sensor/stair_sensor.ino
+++ arduino/stair_sensor/stair_sensor.ino
@@ -67,7 +67,7 @@
 unsigned long msgTime[MSG_QUEUE_LENGTH];
 byte msgTransmitted[MSG_QUEUE_LENGTH]; // Number of times the message has been transmitted.

-long powerTimeout = 10000;      // Time to wait in milliseconds to power down if no detection.
+long powerTimeout = 30000;      // Time to wait in milliseconds to power down if no detection.

 unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
 unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.


Update direction of LEDs

Update direction of LEDs

--- arduino_neopixel/arduino_neopixel.ino
+++ arduino_neopixel/arduino_neopixel.ino
@@ -41,7 +41,7 @@
   }

 void colorWipe(uint32_t c, uint8_t wait) {
-  for(uint16_t i=0; i<strip.numPixels(); i++) {
+  for(int i = (strip.numPixels()-1); i >= 0; i = i - 1) {
     strip.setPixelColor(i, c);
     strip.show();
     delay(wait);


Cleaned Up and Commented Sensor Code

Cleaned Up and Commented Sensor Code

--- Sensors/Sensor-Main/Sensor-Main.ino
+++ Sensors/Sensor-Main/Sensor-Main.ino
@@ -9,11 +9,8 @@
 #include <Adafruit_TSL2561_U.h> //Luminosity Sensor

 /*Deffinations*/
-int ledPin = 5; //Pin for LEDs
-
  //Accel
- #define DS1307_ADDRESS 0x86;//Need to get updated I2C Address
- byte zero = 0x00; //Needed as a workaround for issue #537 RTC Support
+ #define DS1307_ADDRESS 0x86; //10000110, I2C address of ADXL345
  Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

  //RTC
@@ -27,15 +24,17 @@
  File dataFile;

  //UV
- int UVOUT = A0; //Output from the sensor
- int REF_3V3 = A2; //3.3V power on the Arduino board
+ int UVOUT = A0; //Output from the ML8511
+ int REF_3V3 = A2; //3.3V power on the Arduino board to use as reference

  //Luminosity
  Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);
+
  //Magneto
- #define address 0x1E //0011110b, I2C 7bit address of HMC5883
+ #define magnetoAddress 0x1E //0011110b, I2C address of HMC5883
+
 //Humidity
-int HIH4030_Pin = A3;
+int HIH4030_Pin = A3; //Output from HIH-4030

 /*End Deffinations*/

@@ -43,40 +42,31 @@
 void setup()
 {
   /*Serial Setup*/
-	Serial.begin(9600);
-  Wire.begin();
-
-  /*Led Setup*/
-  pinMode(ledPin, OUTPUT);
+	Serial.begin(9600); //Start Serial
+
+  /*I2C Setup*/
+  Wire.begin(); //Start I2C

 	/*Barometer Setup*/
-	if (pressure.begin())
-  {
-  }
+	pressure.begin(); //Start Baro
+

 	/*RTC Setup*/
-	#ifdef AVR
-		Wire.begin();
-	#else
-		Wire1.begin(); // Shield I2C pins connect to alt I2C bus on Arduino Due
-	#endif
-		rtc.begin();
-	if (! rtc.isrunning()) {
-
-	}
+	rtc.begin(); //Start RTC

   /*Accel Setup*/
-	if(!accel.begin()){
-	}
-	accel.setRange(ADXL345_RANGE_16_G);
+	accel.begin(); //Start Accelrometer
+	accel.setRange(ADXL345_RANGE_16_G); //Set Accelrometer Range

   /*SDcard Setup*/
-	if (!SD.begin(4)) {
-	}
-	dataFile = SD.open("datatest.csv", FILE_WRITE);
-  dataFile.println(",");
+	SD.begin(4); //Start SD
+
+  //Print Header
+  dataFile = SD.open("datatest.csv", FILE_WRITE); //Open dataFile
+
+  dataFile.println(","); //println is used to start a new row
   dataFile.print("Timestamp");
-  dataFile.print(",");
+  dataFile.print(","); //Commas are used to declare a new cell in .CSV
   dataFile.print("External Temp F");
   dataFile.print(",");
   dataFile.print("Absolute Pressure(mB)");
@@ -105,27 +95,30 @@
   dataFile.println(",");

-	dataFile.close();
+	dataFile.close(); //Close dataFile

   /*UV */
-	pinMode(UVOUT, INPUT);
-	pinMode(REF_3V3, INPUT);
+	pinMode(UVOUT, INPUT); //Set the pin used to read the UV Sensor to Input
+	pinMode(REF_3V3, INPUT); //Set reference 3.3V pin to Input

   /*Luminosity*/
-  tsl.begin();
-  configureSensor();
+  tsl.begin(); //Start Luminosity Sensor
+  configureLumin(); //Run Config Fucntion
   /*Magneto*/
-  Wire.beginTransmission(address); //open communication with HMC5883
-  Wire.write(0x02); //select mode register
-  Wire.write(0x00); //continuous measurement mode
+  Wire.beginTransmission(magnetoAddress); //Open Communication with HMC5883
+  Wire.write(0x02); //Select Mode Register
+  Wire.write(0x00); //Set Continuous Measurement Mode
   Wire.endTransmission();
 }

 void loop(){
-	/*Time*/
-	DateTime now = rtc.now();
-
-	dataFile = SD.open("datatest.csv", FILE_WRITE);
+	Serial.println();
+
+  /*Time*/
+	DateTime now = rtc.now(); //Define now
+
+	dataFile = SD.open("datatest.csv", FILE_WRITE); //Open dataFile
+  //Print Time
   dataFile.print(now.month(), DEC);
   dataFile.print("/");
   dataFile.print(now.day(), DEC);
@@ -139,25 +132,23 @@
   dataFile.print(now.second(), DEC);
   dataFile.print(",");

-
-
-	/*Leds*/
-  digitalWrite(ledPin, HIGH);
-
   /*Barometer*/
+
   char status;
   double T,P,p0,a;
-  Serial.println();
   status = pressure.startTemperature();
+
   if (status != 0)
   {
     delay(status);
     status = pressure.getTemperature(T);
-    if (status != 0)
+    if (status != 0) //If status does not = zero there was an error starting temp measurement
     {
+      //Print to Serial
       Serial.print("temp: ");
       Serial.print((9.0/5.0)*T+32.0,2);
       Serial.println(" deg F");
+      //Write to SD
       dataFile.print((9.0/5.0)*T+32.0,2);
       dataFile.print(",");

@@ -166,7 +157,7 @@
       {
         delay(status);
         status = pressure.getPressure(P,T);
-        if (status != 0)
+        if (status != 0) //If status does not = zero there was an error retrieving pressure measurement
         {
           Serial.print("aP: ");
           Serial.print(P,2);
@@ -193,36 +184,44 @@
   }

 	/*Accel*/
-  sensors_event_t events;
-  accel.getEvent(&events);
-	dataFile.print(events.acceleration.x);
-  dataFile.print(",");
-  dataFile.print(events.acceleration.y);
-  dataFile.print(",");
-  dataFile.print(events.acceleration.z);
-  dataFile.print(",");
-  Serial.print(events.acceleration.x);
-	Serial.print(events.acceleration.y);
-	Serial.print(events.acceleration.z);
+  sensors_event_t accelEvent; //New Sensor Even
+
+  accel.getEvent(&accelEvent); //Get Event
+
+  //Write Reading to SD
+  dataFile.print(accelEvent.acceleration.x);
+  dataFile.print(",");
+  dataFile.print(accelEvent.acceleration.y);
+  dataFile.print(",");
+  dataFile.print(accelEvent.acceleration.z);
+  dataFile.print(",");
+  //Write Reading to Serial
+  Serial.println(accelEvent.acceleration.x);
+	Serial.println(accelEvent.acceleration.y);
+	Serial.println(accelEvent.acceleration.z);

 	/*Humidity*/
-  float temperature = 25; //replace with a thermometer reading if you have it
+
   float relativeHumidity  = getHumidity(T);
+
   dataFile.print(relativeHumidity);
   dataFile.print(",");
   Serial.println(relativeHumidity);
-	/*Luminosity*/
-  sensors_event_t event;
-  tsl.getEvent(&event);
-  if (event.light)
+
+  /*Luminosity*/
+
+  sensors_event_t luminEvent; //New Lumin Even
+  tsl.getEvent(&luminEvent); //Get Reading
+
+  if (luminEvent.light)
   {
-    Serial.print(event.light); Serial.println(" lux");
-    dataFile.print(event.light);
+    Serial.print(luminEvent.light); Serial.println(" lux");
+    dataFile.print(luminEvent.light);
     dataFile.print(",");
   }
   else
   {
-    Serial.println("Sensor overload");
+    Serial.println("Sensor overload"); //Sensor is Over Saturalted
   }

 	/*UV Sensor*/
@@ -241,14 +240,13 @@
   dataFile.print(",");

   /*Magneto*/
-  int x,y,z; //triple axis data
-
-  //Tell the HMC5883L where to begin reading data
-  Wire.beginTransmission(address);
+  int x,y,z; //Triple Axis Data
+
+  Wire.beginTransmission(magnetoAddress);
   Wire.write(0x03); //select register 3, X MSB register
   Wire.endTransmission();

-  Wire.requestFrom(address, 6);
+  Wire.requestFrom(magnetoAddress, 6);
   if(6<=Wire.available()){
     x = Wire.read()<<8; //X msb
     x |= Wire.read(); //X lsb
@@ -268,26 +266,15 @@
   dataFile.print(z);
   dataFile.println(",");

-
-  Serial.println();
-	dataFile.close();
-  delay(500);
-
-}
-
-float getHumidity(float degreesCelsius){
-  float supplyVolt = 5.0;
-
-  int HIH4030_Value = analogRead(HIH4030_Pin);
-  float voltage = HIH4030_Value/1023. * supplyVolt; // convert to voltage value
-
-  float sensorRH = 161.0 * voltage / supplyVolt - 25.8;
-  float trueRH = sensorRH / (1.0546 - 0.0026 * degreesCelsius); //temperature adjustment
-
-  return trueRH;
-}
-
-void configureSensor(void)
+  /*Odds and Ends*/
+  Serial.println(); //Print a line to show separate readings
+	dataFile.close(); //Close dataFile
+
+  delay(500); //Wait 0.5 Seconds before taking next readings.
+}
+
+
+void configureLumin(void)
 {
   // tsl.setGain(TSL2561_GAIN_1X);      /* No gain ... use in bright light to avoid sensor saturation */
   // tsl.setGain(TSL2561_GAIN_16X);     /* 16x gain ... use in low light to boost sensitivity */
@@ -298,7 +285,9 @@
   // tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS);  /* 16-bit data but slowest conversions */
 }

-//Values
+/*Values*/
+
+//Used to find average of UV reading is voltage being supplied.
 int averageAnalogRead(int pinToRead){
   byte numberOfReadings = 8;
   unsigned int runningValue = 0;
@@ -310,7 +299,20 @@
   return(runningValue);
 }

-
+//Used to map UV sensor readings
 float mapfloat(float x, float in_min, float in_max, float out_min, float out_max){
   return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
 }
+
+//Used to find average of readings of humidity sensor
+float getHumidity(float degreesCelsius){
+  float supplyVolt = 5.0; //Need to change to reading
+
+  int HIH4030_Value = analogRead(HIH4030_Pin);
+  float voltage = HIH4030_Value/1023. * supplyVolt; // convert to voltage value
+
+  float sensorRH = 161.0 * voltage / supplyVolt - 25.8;
+  float trueRH = sensorRH / (1.0546 - 0.0026 * degreesCelsius); //temperature adjustment
+
+  return trueRH;
+}


We finished the pin setting capability.

We finished the pin setting capability.


Update motorctrl.ino

Update motorctrl.ino

AHRS was moved elsewhere long time ago. Also the motor controller was changed so no need to include the library.

--- arduino/motorctrl/motorctrl.ino
+++ arduino/motorctrl/motorctrl.ino
@@ -1,4 +1,4 @@
-// Motor controller and AHRS for Urpobotti
+// Motor controller for Urpobotti

 // Get this library from http://bleaklow.com/files/2010/Task.tar.gz (and fix WProgram.h -> Arduino.h)
 // and read http://bleaklow.com/2010/07/20/a_very_simple_arduino_task_manager.html for background and instructions
@@ -8,12 +8,6 @@

 // Pin change interrupt lib https://github.com/rambo/PinChangeInt_userData
 #include "PinChangeInt_userData.h"
-
-
-// Motor shield https://www.pololu.com/product/2502
-#include "DualVNH5019MotorShield.h"
-DualVNH5019MotorShield md;
-// Reminder: speeds go from -400 to +400

 // To hold data for reach motor encoder
 typedef struct {


Deep Sleep with ATiny85

Deep Sleep with ATiny85

Without BOD	: ~7µA
With BOD	: ~30µA

--- DeepSleep/DeepSleep.ino
+++ DeepSleep/DeepSleep.ino
@@ -14,106 +14,134 @@
 #include <avr/interrupt.h>
 #include <avr/sleep.h>

-#undef ECO // Power Saving On/Off ?
+#define ECO // Power Saving On/Off ?

-int setupLed = 3;
-int loopLed = 4;
+#define WATCHDOG_TIMER WDTO_8S // 8 sec
+#define SLEEP_LOOP  2 // Deep Sleep total time = WATCHDOG_TIMER * SLEEP_LOOP

-volatile boolean isOn = true;
+int pinLed = 3;

+#ifdef ECO
+
+// WatchDof Counter
+volatile byte _watchdogCounter;

 // WatchDog interruption
-EMPTY_INTERRUPT(WDT_vect);
+ISR(WDT_vect) {
+  _watchdogCounter++;
+}
+
+#endif

 void setup() {
   //
   // Setup
-  pinMode(setupLed,OUTPUT);
-  pinMode(loopLed,OUTPUT);
-  digitalWrite(setupLed,HIGH);
-  digitalWrite(loopLed,HIGH);
+  pinMode(pinLed,OUTPUT);
+  digitalWrite(pinLed,HIGH);

   delay(1000);

-
-#ifdef ECO
-  // Turn Off ADC
-  power_adc_disable();
-
-  // Turn Off USI
-  power_usi_disable();
-
-
-  // Setup WatchDog
-  setupWatchdog();
-#endif
-
-
-  digitalWrite(setupLed,LOW);
+  digitalWrite(pinLed,LOW);
 }

 void loop() {
-
-  if(isOn)
-  {
-    digitalWrite(loopLed,LOW);
-  }
-  else{
-    digitalWrite(loopLed,HIGH);
-  }
-
-  // Toggle
-  isOn=!isOn;
+  // Turn LED ON then OFF
+  digitalWrite(pinLed,HIGH);
+  delay(5000);
+  digitalWrite(pinLed,LOW);

   deepSleep();
 }
-

 void deepSleep()
 {
 #ifndef ECO

-  delay(8000);
+  delay(8000*SLEEP_LOOP);

 #else
+
+  //
+  // Prepare for shutdown
+
+  bitClear(ADCSRA,ADEN); //Disable ADC
+  //bitSet(PRR,PRADC); not working...
+  //power_adc_disable(); not working...

-  // Power Down
-  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
+  ACSR = (1<<ACD); //Disable the analog comparator
+  DIDR0 = 0x3F; //Disable digital input buffers on all ADC0-ADC5 pins

-  // Stop Interruption
-  cli();
+  PRR = 0x0F; //Reduce all power right before sleep
+
+
+  //
+  // Start Watchdog
+  setup_watchdog(WATCHDOG_TIMER);
+
+  //
+  // Prepare for Sleep
+
+  while(_watchdogCounter<SLEEP_LOOP){
+
+  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode
+
+  noInterrupts();
   sleep_enable();
-  //sleep_bod_disable(); // Turn Off BOD
-
-  // Start interrupt then go to sleep !
-  sei();
-  sleep_cpu(); // Bye Bye
-
-  sleep_disable(); // Wake Up
+  // Disable BOD : my ATtiny85 doesn't have this fonctionality ...
+  interrupts();
+
+
+  sleep_cpu();                   // System sleeps here
+  sleep_disable();               // System continues execution here when watchdog timed out
+
+  }
+
+  //
+  // Stop WatchDog
+  setup_watchdog(-1);
+
+
+  // Restore Power
+  PRR = 0x00; //Restaure power reduction

 #endif
 }

 #ifdef ECO
-//setup the watchdog to timeout every 8 second and make an interrupt (not a reset!)
-void setupWatchdog(){
-  //README : must set the fuse WDTON to 0 to enable the watchdog

-    //disable interrupts
-  cli();
+//
+// From https://github.com/jcw/jeelib/blob/master/Ports.cpp
+//
+void setup_watchdog(char mode) {

-  //make sure watchdod will be followed by a reset (must set this one to 0 because it resets the WDE bit)
-  MCUSR &= ~(1 << WDRF);
-  //set up WDT interrupt (from that point one have 4 cycle to modify WDTCSR)
-  WDTCR = (1<<WDCE)|(1<<WDE);
-  //Start watchdog timer with 1s prescaller and interrupt only
-  WDTCR = (1<<WDIE)|(0<<WDE)|(1<<WDP3)|(1<<WDP0);
+  // correct for the fact that WDP3 is *not* in bit position 3!
+  if (mode & bit(3))
+  {
+    mode ^= bit(3) | bit(WDP3);
+  }
+  // pre-calculate the WDTCSR value, can't do it inside the timed sequence
+  // we only generate interrupts, no reset
+  byte wdtcsr = mode >= 0 ? bit(WDIE) | mode : 0;
+
+  MCUSR &= ~(1<<WDRF);

-  //Enable global interrupts
-  sei();
+  noInterrupts();
+
+  WDTCR |= (1<<WDCE) | (1<<WDE); // timed sequence
+  WDTCR = wdtcsr;
+
+  // Reset counter
+   _watchdogCounter=0;
+
+  interrupts();
 }
+
+
+
 #endif

+
+


disable serial out

disable serial out

--- _06-power_meter/_06-power_meter.ino
+++ _06-power_meter/_06-power_meter.ino
@@ -13,7 +13,7 @@
 #include "ap_setting.h"
 #endif

-#define DEBUG_PRINT 1
+#define DEBUG_PRINT 0
 #define EVENT_PRINT 0

 //


memory

memory

--- _09_ir_tx_rx/_09_ir_tx_rx.ino
+++ _09_ir_tx_rx/_09_ir_tx_rx.ino
@@ -16,6 +16,8 @@
 #define eeprom_write_from(src_p, eeprom_field, src_size) eeprom_write_block(src_p, (void *)offsetof(__eeprom_data, eeprom_field), MIN(src_size, sizeof((__eeprom_data*)0)->eeprom_field))
 #define eeprom_write(src, eeprom_field) { typeof(src) x = src; eeprom_write_from(&x, eeprom_field, sizeof(x)); }
 #define MIN(x,y) ( x > y ? y : x )
+
+#define DEBUG_PRINT 0

 // eeprom
 // Change this any time the EEPROM content changes
@@ -186,9 +188,11 @@
 void setup()
 {
   // start serial
-  Serial.begin (38400);
-  Serial.println();
-  Serial.println("TV controller Starting");
+  if (DEBUG_PRINT) {
+    Serial.begin (38400);
+    Serial.println();
+    Serial.println("TV controller Starting");
+  }
   delay(20);

   // lcd
@@ -200,7 +204,7 @@

   // Timer start
   temp_Mills = millis();
-  pir_Mills = millis();
+  //pir_Mills = millis();

   // ir
   irrecv.enableIRIn();
@@ -251,7 +255,9 @@

   // temp sensor
   sensors.begin();
-  if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
+  if (DEBUG_PRINT) {
+    if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
+  }
   sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);

   // lcd
@@ -314,11 +320,13 @@

 void loop()
 {
+
+  t.update();
+
+
   // receiving ir and change status
   // remote on / off, tv remote on / off
   decode_results results;
-
-  t.update();

   // PIR
   if ( pirOnOff != o_pirOnOff) {
@@ -432,21 +440,23 @@
   } else {

     pirOnOff = digitalRead(PIR_IN_PIN);
-    Serial.println("PIRp called");
+    if (DEBUG_PRINT) {
+      Serial.println("PIRp called");
+    }
     pir_Mills = millis();
   }
 }

 void tvOnTimer()
 {
-
+
   tvIsOnEvent = t.every((o_tvOnTime * 1000 * 60) , doTvOffTimer);
   t.stop(tvIsOffEvent);
 }

 void tvOffTimer()
 {
-
+
   tvIsOffEvent = t.every((o_tvOffTime * 1000 * 60) , doTvOnTimer);
   t.stop(tvIsOnEvent);
 }
@@ -531,12 +541,16 @@
 void irSendTvOut(int a)
 {
   if ( o_offMode == 1 ) {
-    Serial.println("IRSend on/off called");
+    if (DEBUG_PRINT) {
+      Serial.println("IRSend on/off called");
+    }
     irsend.sendNEC(tv_onoff, 32);
     delay(300);
     irrecv.enableIRIn();
   } else {
-    Serial.println("IRSend CH change called");
+    if (DEBUG_PRINT) {
+      Serial.println("IRSend CH change called");
+    }
     switch (a) {
       case 0:
         irsend.sendNEC(tv_input, 32);
@@ -592,7 +606,9 @@
   tempCinside = getdalastemp();
   displayTemperature(tempCinside);
   displaytimeleft();
-  Serial.println(digitalRead(PIR_IN_PIN));
+  if (DEBUG_PRINT) {
+    Serial.println(digitalRead(PIR_IN_PIN));
+  }
 }

 // update every 5 mins
@@ -709,6 +725,7 @@
   }
 }

+
 void run_initialise_setup() {

   decode_results results;
@@ -721,6 +738,7 @@
   lcd.setCursor(15, 1);
   lcd.print("*");

+
   irrecv.resume();
   while (irrecv.decode(&results) != 1 ) { }
   alarm_set();
@@ -743,7 +761,7 @@
   lcd.setCursor(0, 1);
   lcd.print("OFF: from other");

-  int pwrSrc = initialise_boolean_select();
+  o_pwrSrc = initialise_boolean_select();
   alarm_set();

   lcd.clear();
@@ -764,7 +782,7 @@
   lcd.setCursor(0, 1);
   lcd.print("OFF: thermo");

-  int wrkMode = initialise_boolean_select();
+  o_wrkMode = initialise_boolean_select();
   alarm_set();

   lcd.clear();
@@ -785,7 +803,7 @@
   lcd.setCursor(0, 1);
   lcd.print("OFF: do nothing");

-  int startMode = initialise_boolean_select();
+  o_startMode = initialise_boolean_select();
   alarm_set();

   lcd.clear();
@@ -806,7 +824,7 @@
   lcd.setCursor(0, 1);
   lcd.print("OFF: beep off");

-  int beepMode = initialise_boolean_select();
+  o_beepMode = initialise_boolean_select();
   alarm_set();

   lcd.clear();
@@ -827,7 +845,7 @@
   lcd.setCursor(0, 1);
   lcd.print("OFF: IN change");

-  int offMode = initialise_boolean_select();
+  o_offMode = initialise_boolean_select();
   alarm_set();

   lcd.clear();
@@ -848,7 +866,7 @@
   lcd.setCursor(0, 1);
   lcd.print("OFF: done");

-  int channelGap = initialise_number_select(1, 5, 1, 1);
+  o_channelGap = initialise_number_select(1, 5, 1, 1);
   alarm_set();

   lcd.clear();
@@ -869,7 +887,7 @@
   lcd.setCursor(0, 1);
   lcd.print("OFF: done");

-  int tvOnTime = initialise_number_select(30, 90, 50, 5);
+  o_tvOnTime = initialise_number_select(30, 90, 50, 5);
   alarm_set();

   lcd.clear();
@@ -890,13 +908,15 @@
   lcd.setCursor(0, 1);
   lcd.print("OFF: done");

-  int tvOffTime = initialise_number_select(5, 20, 10, 5);
+  o_tvOffTime = initialise_number_select(5, 20, 10, 5);
   alarm_set();

   //
-  int initialise_eeprom_done =  initialise_eeprom(pwrSrc, wrkMode, startMode, beepMode, offMode, channelGap, tvOnTime, tvOffTime) ;
-
-  while (initialise_eeprom_done != 1 ) { }
+  // int initialise_eeprom_done =  initialise_eeprom(o_pwrSrc, o_wrkMode, o_startMode, o_beepMode, o_offMode, o_channelGap, o_tvOnTime, o_tvOffTime) ;
+
+  //while (initialise_eeprom_done != 1 ) { }
+
+  while ( initialise_eeprom(o_pwrSrc, o_wrkMode, o_startMode, o_beepMode, o_offMode, o_channelGap, o_tvOnTime, o_tvOffTime) != 1 ) {}

   lcd.clear();
   lcd.setCursor(0, 0);
@@ -943,3 +963,4 @@

   return 1;
 }
+


Added 'reset' menu option - close #7

Added 'reset' menu option - close #7

--- DigitalVFO.ino
+++ DigitalVFO.ino
@@ -1239,6 +1239,39 @@
 }

 //----------------------------------------
+// Reset everything in the VFO - Dangerous!
+//   menu      address of 'calling' menu
+//   item_num  index of MenuItem we were actioned from
+//----------------------------------------
+
+void reset_action(struct Menu *menu, int item_num)
+{
+  Frequency zero_freq = 0L;
+  SelOffset zero_offset = 0;
+
+  // zero the frequency+selected values
+  VfoFrequency = MIN_FREQ;
+  VfoSelectDigit = 0;
+  LcdBrightness = DefaultLcdBrightness;
+  LcdContrast = DefaultLcdContrast;
+  ReHoldClickTime = DefaultHoldClickTime;
+
+  save_to_eeprom();
+
+  // zero the save slots
+  for (int i = 0; i < NumSaveSlots; ++i)
+  {
+    put_slot(i, zero_freq, zero_offset);
+  }
+
+  display_flash();
+}
+
+void reset_no_action(struct Menu *menu, int item_num)
+{
+}
+
+//----------------------------------------
 // Draw a bar of a given length on row 1 of LCD.
 //   length  length of the bar [1, 16]
 //----------------------------------------
@@ -1469,6 +1502,15 @@

 //----------------------------------------
+// Reset menu
+//----------------------------------------
+
+struct MenuItem mi_reset_no = {"No", NULL, &reset_no_action};
+struct MenuItem mi_reset_yes = {"Yes", NULL, &reset_action};
+struct MenuItem *mia_reset[] = {&mi_reset_no, &mi_reset_yes};
+struct Menu reset_menu = {"Reset all", ARRAY_LEN(mia_reset), mia_reset};
+
+//----------------------------------------
 // Settings menu
 //----------------------------------------

@@ -1486,7 +1528,8 @@
 struct MenuItem mi_restore = {"Restore slot", NULL, &restoreslot_action};
 struct MenuItem mi_del = {"Delete slot", NULL, &deleteslot_action};
 struct MenuItem mi_settings = {"Settings", &settings_menu, NULL};
-struct MenuItem *mia_main[] = {&mi_save, &mi_restore, &mi_del, &mi_settings};
+struct MenuItem mi_reset = {"Reset all", &reset_menu, NULL};
+struct MenuItem *mia_main[] = {&mi_save, &mi_restore, &mi_del, &mi_settings, &mi_reset};
 struct Menu menu_main = {"Menu", ARRAY_LEN(mia_main), mia_main};