Use longer sleep (and activity window); print more debug

--- Wetteranzeige/Wetteranzeige.ino
+++ Wetteranzeige/Wetteranzeige.ino
@@ -17,8 +17,8 @@
 #include "Wave29Display.h"
 Wave29Display display;

-unsigned long systemSleepSeconds = 180; // including the awaked time
-unsigned long systemAwakeSeconds = 12;
+unsigned long systemSleepSeconds = 240; // including the awaked time
+unsigned long systemAwakeSeconds = 14;

 #include "TH.h"
 #include "WeatherServer.h"
@@ -148,8 +148,8 @@

   unsigned long systemActive = millis() - systemStart;
   unsigned int secondsUntilOff = 0;
-  if ((systemAwakeSeconds - 2)*1000 > systemActive) // -2 lie a little bit here; more time to connect
-    secondsUntilOff = ((systemAwakeSeconds - 2)*1000 - systemActive) / 1000;
+  if ((systemAwakeSeconds - 3)*1000 > systemActive) // -3 lie a little bit here; more time to connect
+    secondsUntilOff = ((systemAwakeSeconds - 3)*1000 - systemActive) / 1000;

   TH externalData;
   bool dataReceived = server.receiveData(&externalData, secondsUntilOff);
@@ -218,8 +218,11 @@
     unsigned long sleepMillis = 1;
     if (systemSleepSeconds * 1000 > systemActive)
       sleepMillis = systemSleepSeconds * 1000 - systemActive;
-
-    Serial.print("Sleeping ");
+
+    systemState.accumulatedSystemMillis = systemState.accumulatedSystemMillis + systemActive + sleepMillis;
+    Serial.print(systemState.accumulatedSystemMillis / (1000 * 60));
+
+    Serial.print("m Sleeping ");
     if (shouldSleepNow && !sleepNow)
       Serial.print("in vain ");
     Serial.println(sleepMillis);
@@ -227,7 +230,6 @@
     DisplayStateWrapper *displayState = display.getState();
     displayState->writeToRtc(1, sizeof(DisplayStateWrapper));

-    systemState.accumulatedSystemMillis = systemState.accumulatedSystemMillis + systemActive + sleepMillis;
     systemState.writeToRtc(0, sizeof(SystemState));

     ESP.deepSleep(sleepMillis * 1000);


trying to fit it to the actual robot

trying to fit it to the actual robot

--- v2/06oct/06oct/06oct.ino
+++ v2/06oct/06oct/06oct.ino
@@ -123,7 +123,8 @@

   pinMode(startModule, INPUT);
   int initial = digitalRead(startModule);
-  while (initial == digitalRead(startModule)) {}
+//  while (initial == digitalRead(startModule)) {
+//    Serial.println(digitalRead(startModule));}
   delay(5000);

   past = 'f'; //set default move to forward


modified:   led_weather_indicator.ino

modified:   led_weather_indicator.ino

--- led_weather_indicator.ino
+++ led_weather_indicator.ino
@@ -16,7 +16,7 @@
 uint32_t color100 = strip.Color(12,  6,  0); // sunny
 uint32_t color200 = strip.Color( 6,  6,  6); // cloudy
 uint32_t color300 = strip.Color( 0,  0, 12); // rainy
-uint32_t color400 = strip.Color( 6,  6, 12); // snowy
+uint32_t color400 = strip.Color( 0,  6,  6); // snowy
 uint32_t color500 = strip.Color( 6,  1,  1); // hot
 uint32_t color850 = strip.Color( 4,  0, 12); // heavy rain


Fixed incorrect color when all three hands overlap

--- Firmware/spark-ring/spark-ring.ino
+++ Firmware/spark-ring/spark-ring.ino
@@ -1,10 +1,10 @@
 /*-------------------------------------------------------------------------
-
+
   Spark Core sketch to control a NeoPixel 24 RGB LED ring: https://www.adafruit.com/product/1586
   Written by Jason Coon
-
+
   Based on:
-
+
   Written by Phil Burgess / Paint Your Dragon for Adafruit Industries.
   Modified to work with Spark Core by Technobly.
   Contributions by PJRC and other members of the open source community.
@@ -50,7 +50,7 @@
     else if (args.startsWith("tz:")) {
         return setTimezone(args.substring(3));
     }
-
+
     return -1;
 }

@@ -60,7 +60,7 @@
         power = 0;
     else if (power > 1)
         power = 1;
-
+
     return power;
 }

@@ -71,12 +71,12 @@
         brightness = 1;
     else if(brightness > 255)
         brightness = 255;
-
+
     strip.setBrightness(brightness);
     strip.show();
-
+
     EEPROM.write(0, brightness);
-
+
     return brightness;
 }

@@ -86,16 +86,16 @@
         power = -12;
     else if (power > 13)
         power = 13;
-
+
     Time.zone(timezone);
-
+
     if(timezone < 0)
         EEPROM.write(1, 0);
     else
         EEPROM.write(1, 1);
-
+
     EEPROM.write(2, abs(timezone));
-
+
     return power;
 }

@@ -106,11 +106,11 @@
         patternIndex = 0;
     else if (patternIndex >= patternCount)
         patternIndex = patternCount - 1;
-
+
     pixelIndex = 0;
-
+
     EEPROM.write(3, patternIndex);
-
+
     return patternIndex;
 }

@@ -121,94 +121,94 @@
         pattern = 0;
     else if (pattern >= patternCount)
         pattern = patternCount - 1;
-
+
     switch(pattern)
     {
         case 0:
         strcpy(patternName, "Color Wipe Red");
         break;
-
+
         case 1:
         strcpy(patternName, "Color Wipe Green");
         break;
-
+
         case 2:
         strcpy(patternName, "Color Wipe Blue");
         break;
-
+
         case 3:
         strcpy(patternName, "Rainbow Cycle");
         break;
-
+
         case 4:
         default:
         strcpy(patternName, "Rainbow Spin");
         break;
-
+
         case 5:
         strcpy(patternName, "Color All Magenta");
         break;
-
+
         case 6:
         strcpy(patternName, "Sparkle White");
         break;
-
+
         case 7:
         strcpy(patternName, "Sparkle Rainbow");
         break;
-
+
         case 8:
         strcpy(patternName, "Wave Slow");
         break;
-
+
         case 9:
         strcpy(patternName, "Analog Clock");
         break;
   }
-
+
     return pattern;
 }

 void setup() {
     Serial.begin(9600);
-
+
     // load settings from EEPROM
     brightness = EEPROM.read(0);
     if(brightness < 1)
         brightness = 1;
     else if(brightness > 255)
         brightness = 255;
-
+
     uint8_t timezoneSign = EEPROM.read(1);
     if(timezoneSign < 1)
         timezone = -EEPROM.read(2);
     else
         timezone = EEPROM.read(2);
-
+
     if(timezone < -12)
         power = -12;
     else if (power > 13)
         power = 13;
-
+
     patternIndex = EEPROM.read(3);
     if(patternIndex < 0)
         patternIndex = 0;
     else if (patternIndex >= patternCount)
         patternIndex = patternCount - 1;
-
+
     Spark.function("variable", setVariable);
     Spark.function("patternIndex", setPatternIndex);
     Spark.function("patternName", setPatternName);
-
+
     Spark.variable("power", &power, INT);
     Spark.variable("brightness", &brightness, INT);
     Spark.variable("timezone", &timezone, INT);
     Spark.variable("patternCount", &patternCount, INT);
     Spark.variable("patternIndex", &patternIndex, INT);
     Spark.variable("patternName", patternName, STRING);
-
+
     Time.zone(timezone);
-
+
     strip.begin();
     strip.setBrightness(brightness);
     strip.show(); // Initialize all pixels to 'off'
@@ -220,64 +220,64 @@
     Spark.syncTime();
     lastTimeSync = millis();
   }
-
+
   if(power < 1) {
       colorAll(strip.Color(0, 0, 0)); // Black
       strip.show();
       delay(250);
       return;
   }
-
+
   uint8_t wait = 30;
-
+
   switch(patternIndex)
   {
       case 0:
       wait = colorWipe(strip.Color(255, 0, 0)); // Red
       break;
-
+
       case 1:
       wait = colorWipe(strip.Color(0, 255, 0)); // Green
       break;
-
+
       case 2:
       wait = colorWipe(strip.Color(0, 0, 255)); // Blue
       break;
-
+
       case 3:
       wait = rainbowCycle();
       break;
-
+
       case 4:
       default:
       wait = rainbowSpin();
       break;
-
+
       case 5:
       wait = colorAll(strip.Color(0, 255, 255)); // Magenta
       break;
-
+
       case 6:
       wait = sparkle(strip.Color(255, 255, 255));
       break;
-
+
       case 7:
         colorIndex++;
         if(colorIndex >= 256)
             colorIndex = 0;
-
+
       wait = sparkle(Wheel(colorIndex));
       break;
-
+
       case 8:
       wait = wave(.1);
       break;
-
+
       case 9:
       wait = analogClock();
       break;
   }
-
+
   strip.show();
   delay(wait);
 }
@@ -287,18 +287,18 @@
   for(uint16_t i=0; i<strip.numPixels(); i++) {
     strip.setPixelColor(i, c);
   }
-
+
   return 50;
 }

 // Fill the dots one after the other with a color
 uint8_t colorWipe(uint32_t c) {
     strip.setPixelColor(pixelIndex, c);
-
+
     pixelIndex++;
     if(pixelIndex >= strip.numPixels())
         pixelIndex = 0;
-
+
     return 50;
 }

@@ -306,11 +306,11 @@
     for(uint16_t i=0; i<strip.numPixels(); i++) {
         strip.setPixelColor(i, Wheel((i+colorIndex) & 255));
     }
-
+
     colorIndex++;
     if(colorIndex >= 256)
         colorIndex = 0;
-
+
     return 20;
 }

@@ -319,19 +319,19 @@
     for(uint16_t i=0; i< strip.numPixels(); i++) {
         strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + colorIndex) & 255));
     }
-
+
     colorIndex++;
     if(colorIndex >= 256)
         colorIndex = 0;
-
+
     return 20;
 }

 uint8_t sparkle(uint32_t c) {
     colorAll(strip.Color(0, 0, 0)); // Black
-
+
     strip.setPixelColor(random(0, strip.numPixels()), c);
-
+
     return 20;
 }

@@ -343,23 +343,37 @@
         float level = sin(i+pos) * 255;
         strip.setPixelColor(i,(int)level,0,0);
     }
-
+
     return 20;
 }

 uint8_t analogClock() {
     colorAll(strip.Color(0, 0, 0)); // Black
-
+
     int secondIndex = Time.second() * 0.4;
     int minuteIndex = Time.minute() * 0.4;
     int hourIndex = Time.hourFormat12() * 2;
-
+
+    // // draw a fading trail behind the second hand
+    // // start at 0 V, at secondIndex + 1
+    // // slowly increase V up to 255 at secondIndex
+    // int v = 0;
+    // for(int i = 0; i < strip.numPixels(); i++) {
+    //     int j = secondIndex + 1 + i;
+    //     if(j >= strip.numPixels())
+    //         j -= strip.numPixels();
+
+    //     strip.setPixelColor(j, hsv(240, 255, v));
+
+    //     v += 10;
+    // }
+
     // hour hand is red
     // minute hand is green
     // second hand is blue
-
+
     // if all hands are at the same position, draw a white pixel
-    if(secondIndex == minuteIndex == hourIndex) {
+    if(secondIndex == minuteIndex && minuteIndex == hourIndex) {
         strip.setPixelColor(secondIndex, strip.Color(255, 255, 255));
     }
     // if the second and minute hands are at the same position, draw a cyan pixel
@@ -374,7 +388,7 @@
     }
     // if the minute and hour hands are at the same position, draw a yellow pixel
     else if (minuteIndex == hourIndex) {
-        strip.setPixelColor(secondIndex, strip.Color(255, 255, 0));
+        strip.setPixelColor(hourIndex, strip.Color(255, 255, 0));
         strip.setPixelColor(secondIndex, strip.Color(0, 0, 255));
     }
     // all hands are separate, just draw them
@@ -383,7 +397,7 @@
         strip.setPixelColor(minuteIndex, strip.Color(0, 255, 0));
         strip.setPixelColor(hourIndex, strip.Color(255, 0, 0));
     }
-
+
     return 20;
 }

@@ -401,9 +415,13 @@
   }
 }

-uint32_t HSVtoRGB(int hue, int sat, int val) {
+uint32_t dimColor(uint32_t color, uint8_t width) {
+   return (((color&0xFF0000)/width)&0xFF0000) + (((color&0x00FF00)/width)&0x00FF00) + (((color&0x0000FF)/width)&0x0000FF);
+}
+
+uint32_t hsv(int hue, int sat, int val) {
     int r, g, b, base;
-
+
     // hue: 0-359, sat: 0-255, val (lightness): 0-255

 	if (sat == 0) { // Achromatic color (gray).
@@ -445,6 +463,6 @@
 				break;
 		}
 	}
-
+
 	return strip.Color(r, g, b);
 }


Small fixes completed

Small fixes completed

--- node_A/node_A.ino
+++ node_A/node_A.ino
@@ -53,10 +53,7 @@
 bool buzzPin_state = LOW;
 unsigned long start_buzz_time = 0;
 bool soft_alarm_state = false;
-<<<<<<< HEAD
 bool pir_alarm_state = false;
-=======
->>>>>>> 2e87ac67c97485ac5c1b4994cb3e968dcd442e6a

 unsigned long currentTime = 0;
 unsigned long startTime   = 0;
@@ -128,7 +125,7 @@
         else if (pir_alarm_state) {
           digitalWrite(led_A_Pin, LOW);
           pir_alarm_state = false;
-        }
+        }
     }

   }


Additional formatting

Additional formatting

--- ManeAvis.ino
+++ ManeAvis.ino
@@ -83,16 +83,23 @@

     Display.clearDisplay();
     Display.setTextSize(3);
-    Display.setCursor(0, 22);
+    Display.setCursor(12, 22);

     if(hour < 10) Display.print(' ');
     Display.print(hour);
     Display.print(second % 2 == 0 ? ' ' : ':');
     if(minute < 10) Display.print('0');
     Display.print(minute);
-    Display.print(' ');
-    if(Time.isAM()) Display.print('A');
-    if(Time.isPM()) Display.print('P');
+    /*Display.print(' ');*/
+
+    Display.setTextSize(1);
+
+    if(Time.isAM()) {
+      Display.print("AM");
+    } else {
+      Display.setCursor(102, 37);
+      Display.print("PM");
+    }

     Display.display();
   }


Update Sensors.ino

Update Sensors.ino

--- DroidMain/Sensors.ino
+++ DroidMain/Sensors.ino
@@ -55,7 +55,7 @@

 void JsonReportSensorEdge() {
   // Create Json and publish
-  String jsonEdge = String("{\"sensor\":\"edge\",\"time\":\"" + TimeStr + "\",\"data\":[" + left_edge + "," + right_edge + "]}");
+  String jsonEdge = String("{\"sensor\":\"edge\",\"time\":\"" + TimeStr + "\",\"data\":[" + digitalRead(left_edge) + "," + digitalRead(right_edge) + "]}");
   if (debugging == true) { Serial.println(jsonEdge);}
   memset(bufff, 0, 512); jsonEdge.toCharArray(bufff, 512);
   mqtt.publish("iot-uplink", bufff);


reduce payload size

reduce payload size

--- examples/RF12/otRelay/otRelay.ino
+++ examples/RF12/otRelay/otRelay.ino
@@ -1,5 +1,7 @@
 /// @dir otRelay
 /// Read out the OpenTherm gateway and relay readings using RFM12B.
+/// @see http://jeelabs.org/2012/11/20/opentherm-relay/
+/// @see http://jeelabs.org/2012/11/21/reducing-the-payload-size/
 // 2012-11-11 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

 #include <JeeLib.h>
@@ -7,10 +9,39 @@
 // buffer to collect last data received
 byte lastChars[9], lastFill;

+static bool shouldSend (const byte* payload) {
+  return true;
+}
+
+static byte hex2bin (const byte* hex) {
+  byte result = (hex[0] - (hex[0] <= '9' ? 0 : 7)) << 4;
+  result |= (hex[1] - (hex[1] <= '9' ? 0 : 7)) & 0x0F;
+  return result;
+}
+
+static void sendMessage () {
+  byte payload [3];
+  payload[0] = hex2bin(lastChars + 3);
+  payload[1] = hex2bin(lastChars + 5);
+  payload[2] = hex2bin(lastChars + 7);
+
+  if (shouldSend(payload)) {
+    while (!rf12_canSend())
+      rf12_recvDone();
+    rf12_sendStart(0, payload, sizeof payload);
+  }
+}
+
 static void processMessage () {
-  while (!rf12_canSend())
-    rf12_recvDone();
-  rf12_sendStart(0, lastChars, lastFill);
+  switch (lastChars[0]) {
+    case 'T': // from thermostat
+    case 'B': // from boiler (heater)
+      switch (lastChars[1] & 7) {
+        case 1: // Write-Data
+        case 4: // Read-Ack
+          sendMessage();
+      }
+  }
 }

 void setup () {


better logging example

better logging example

--- examples/skynetim_logger/skynetim_logger.ino
+++ examples/skynetim_logger/skynetim_logger.ino
@@ -9,8 +9,8 @@
  * SkynetClient for http://skynet.im, OPEN COMMUNICATIONS NETWORK & API FOR
  * THE INTERNET OF THINGS.
  *
- * This sketch send data to the Skynet data endpoint for logging and graphing
- * by skynet itself!
+ * This sketch reads analog0 and analog1 and sends data to the Skynet data
+ * endpoint for logging and graphing!
  *
  * Works with ethernet shields compatible with EthernetClient library from
  * Arduino. If you don't know, grab the original
@@ -73,8 +73,22 @@
     Serial.println(uuid);
   }

+  char buf[5];
+  char message[30];
+
+  strcpy(message, "\"light\":");
+  itoa(analogRead(A0), buf, 10);
+  strcat(message,buf);
+
+  strcat(message, ",\"temp\":");
+  itoa(analogRead(A1), buf, 10);
+  strcat(message,buf);
+
+  //Serial.println(message);
+
   //message to log MUST be comma seperated key value pair(s) and may
   //not be be an object or array
-  skynetclient.logMessage("\"humidity\":123,\"temperature\":\"21C\"");
+  //looks like "light":"423","temp":"356"
+  skynetclient.logMessage(message);
   delay(1000);
 }


examples: fix api call for restartBluetooth()

--- examples/services/setServices.ino
+++ examples/services/setServices.ino
@@ -5,7 +5,7 @@
   // Reset the services to default
   Bean.resetServices();
   // Reset the Bluetooth module itself
-  Bean.resetBluetooth();
+  Bean.restartBluetooth();
   // Wait for a few moments for Bluetooth to come back up...
   Bean.sleep(5000);
   // Set services to include standard advertising (default)


humidity added to arduino

humidity added to arduino

--- serial/arduino2/arduino2.ino
+++ serial/arduino2/arduino2.ino
@@ -1,5 +1,8 @@
 #include <Servo.h>
+#include <dht.h>

+dht DHT;
+const int DHT11_PIN = 7;
 const int relay = 2;
 const int relay2 = 3;
 const int relay3 = 4;
@@ -33,6 +36,7 @@
   int lampstatus = bitRead(PORTD, relay);
   int lampstatus2 = bitRead(PORTD, relay2);
   int lampstatus3 = bitRead(PORTD, relay3);
+  int chk = DHT.read11(DHT11_PIN);

   if(Serial.available())
   {
@@ -57,6 +61,10 @@
       Serial.print(lampstatus3);
       Serial.print(" ");
       Serial.print(myservo.read());
+      Serial.print(" ");
+      Serial.print(DHT.temperature);
+      Serial.print(" ");
+      Serial.print(DHT.humidity);
       Serial.print("\n");
       break;
       case 4:


modified some of the pin settings on arduino

--- marsduino/marsduino.ino
+++ marsduino/marsduino.ino
@@ -27,7 +27,7 @@
 int enablePin = 13; //enable/disable motor
 int revPin = 11; //seting fwd/rev
 int brakePin = 12; //brake pin
-int speedPin = 9; //speedPin
+int speedPin = 6; //speedPin
 int voltagePin = A0; //ammeter voltage pin
 int currentPin = A1; //ammeter current pin
 int encoderPin = A5; //pin for motor controller


Completed full duplex SLIP+OSC over Bluetooth in the Typeatron

--- typeatron/mark1/arduino/typeatron/typeatron.ino
+++ typeatron/mark1/arduino/typeatron/typeatron.ino
@@ -99,12 +99,14 @@

 const unsigned long WHITE = 0xffffff;
 const unsigned long RED = 0xff0000;
+const unsigned long ORANGE = 0xff8000;
 const unsigned long YELLOW = 0xffff00;
 const unsigned long GREEN = 0x00ff00;
 const unsigned long CYAN = 0x00ffff;
 const unsigned long BLUE = 0x0000ff;
 const unsigned long PURPLE = 0xff00ff;
 const unsigned long BLACK = 0x000000;
+const unsigned long GRAY = 0x808080;

 unsigned long currentRGBColor = 0;

@@ -260,32 +262,60 @@
     while(!Serial); // Leonardo "feature"
 #endif

-    startupSequence();
-}
-
-
-////////////////////////////////////////////////////////////////////////////////
+    startupSequence();
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+const char *BUFFER_FULL_msg = "BUFFER_FULL",
+    *INVALID_OSC_msg = "INVALID_OSC",
+    *ALLOCFAILED_msg = "ALLOCFAILED",
+    *INDEX_OUT_OF_BOUNDS_msg = "INDEX_OUT_OF_BOUNDS",
+    *unknown_msg = "unknown";
+
+void sendOSCMessageError(class OSCMessage &message) {
+    OSCErrorCode code = message.getError();
+    const char *name;
+
+    switch(code) {
+      case BUFFER_FULL:
+          name = BUFFER_FULL_msg;
+          break;
+      case INVALID_OSC:
+         name = INVALID_OSC_msg;
+         break;
+      case ALLOCFAILED:
+         name = ALLOCFAILED_msg;
+         break;
+      case INDEX_OUT_OF_BOUNDS:
+         name = INDEX_OUT_OF_BOUNDS_msg;
+         break;
+      default:
+         name = unknown_msg;
+    }
+
+    sprintf(errstr, "OSC message hasError (error type: %s)", name);
+    sendError(errstr);
+}
+

 void receiveOSCMessage(class OSCMessage &messageIn) {
-    writeRGBColor(CYAN);
+    writeRGBColor(WHITE);

     if (messageIn.hasError()) {
-        sendError("OSC message hasError");
+        sendOSCMessageError(messageIn);
     } else {
-//char addrBuffer[100];
-//messageIn.getAddress(addrBuffer, 0);
-//sprintf(errstr, "address of message: %s", addrBuffer);
-//sendInfo(errstr);
-        int called;
-        called = messageIn.dispatch("/exo/tt/morse", receiveMorseMessage);
-        called = messageIn.dispatch("/exo/tt/photo/get", receivePhotoGetMessage);
-        called = messageIn.dispatch("/exo/tt/ping", receivePingMessage);
-        called = messageIn.dispatch("/exo/tt/rgb/set", receiveRgbSetMessage);
-        called = messageIn.dispatch("/exo/tt/vibro", receiveVibroMessage);
-    }
-
-    messageIn.empty();
-    writeRGBColor(GREEN);
+        writeRGBColor(GREEN);
+
+        boolean called = 0
+        || messageIn.dispatch("/exo/tt/morse", receiveMorseMessage)
+        || messageIn.dispatch("/exo/tt/photo/get", receivePhotoGetMessage)
+        || messageIn.dispatch("/exo/tt/ping", receivePingMessage)
+        || messageIn.dispatch("/exo/tt/rgb/set", receiveRgbSetMessage)
+        || messageIn.dispatch("/exo/tt/vibro", receiveVibroMessage)
+        ;
+    }
 }

 void sendOSC(class OSCMessage &messageOut) {
@@ -312,22 +342,23 @@
 ////////////////////////////////////////////////////////////////////////////////

 void receiveMorseMessage(class OSCMessage &m) {
-  sendInfo("received morse message");
+  //sendInfo("received morse message");
     if (m.isString(0)) {
+        writeRGBColor(YELLOW);
+
         int length = m.getDataLength(0);
         char buffer[length+1];
         m.getString(0, buffer, length+1);

-        unsigned long lastColor = currentRGBColor;
-        writeRGBColor(YELLOW);
         playMorseString(buffer, morseStopTest);
-        writeRGBColor(lastColor);
     } else {
         sendError("expected string argument to Morse code control");
     }
 }

 void receivePhotoGetMessage(class OSCMessage &m) {
+    writeRGBColor(WHITE);
+
     sampler_photoresistor.reset();
     sampler_photoresistor.beginSample();
     sampler_photoresistor.measure();
@@ -337,15 +368,13 @@
 }

 void receivePingMessage(class OSCMessage &m) {
-//char addrBuffer[100];
-//m.getAddress(addrBuffer, 0);
-//sprintf(errstr, "address of ping message: %s", addrBuffer);
-//sendInfo(errstr);
+    writeRGBColor(PURPLE);
+
     // send reply as soon as possible
     sendPingReply();

-    writeRGBColor(GREEN);
-    playMorseString("p", morseStopTest);
+    playMorseString("p", morseStopTest);
+    writeRGBColor(GREEN);
 }

 void receiveRgbSetMessage(class OSCMessage &m) {
@@ -359,6 +388,7 @@

 void receiveVibroMessage(class OSCMessage &m) {
     writeRGBColor(PURPLE);
+
   //sendInfo("we made it into the vibro control!");
     if (m.isInt(0)) {
         int d = m.getInt(0);
@@ -381,24 +411,32 @@
 ////////////////////////////////////////////////////////////////////////////////

 void sendError(const char *message) {
+    writeRGBColor(ORANGE);
+
     OSCMessage m("/exo/tt/error");
     m.add(message);

     sendOSC(m);
+
+    writeRGBColor(RED);
 }

 void sendInfo(const char *message) {
+    writeRGBColor(BLUE);
+
     OSCMessage m("/exo/tt/info");
     m.add(message);

     sendOSC(m);
+
+    writeRGBColor(CYAN);
 }

 void sendKeyEvent(const char *keys) {
     OSCMessage m("/exo/tt/keys");
     m.add(keys);

-    sendOSC(m);
+    sendOSC(m);
 }

 void sendLightLevel() {
@@ -410,40 +448,52 @@
 }

 void sendPingReply() {
+    writeRGBColor(YELLOW);
+
     OSCMessage m("/exo/tt/ping/reply");
     m.add((int32_t) micros());

-    sendOSC(m);
-}
-
-
-////////////////////////////////////////////////////////////////////////////////
-
-OSCMessage messageIn;
-
+    sendOSC(m);
+
+    writeRGBColor(GREEN);
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
 void loop() {
 #ifdef USE_BLUETOOTH
-    // this must be kept in loop() to receive events via Amarino
-    //meetAndroid.receive();
-
-    if (int size = SLIPSerial.available() > 0) {
+    int done = SLIPSerial.endofPacket();
+
+    int size;
+    OSCMessage messageIn;
+    while ((size = SLIPSerial.available()) > 0) {
+        writeRGBColor(GRAY);
+
         while (size--) {
-            messageIn.fill(SLIPSerial.read());
-
-            // note: we may start writing before we are done reading available bytes
-            if (SLIPSerial.endofPacket()) {
-                receiveOSCMessage(messageIn);
-            }
+            int c = SLIPSerial.read();
+            messageIn.fill(c);
+            //sprintf(errstr, "received a byte: %d. bytes: %d, size: %d, hasError: %d", c, messageIn2.bytes(), messageIn2.size(), messageIn2.hasError());
+            //sendInfo(errstr);
         }
     }
+    done = done || SLIPSerial.endofPacket();
+    if (done) {
+        if (messageIn.hasError()) {
+            sendOSCMessageError(messageIn);
+        } else {
+            receiveOSCMessage(messageIn);
+        }
+
+        messageIn.empty();
+    }
 #endif
-
+    writeRGBColor(BLACK);
+
     readKeys();

     if (keyState != lastKeyState) {
         colorDebug();
-//sprintf(errstr, "input changed from %d to %d\n", lastKeyState, keyState);
-//ƒsendInfo(errstr);

         // bells and whistles
         if (keys[4] == HIGH) {


Test wit hadded space ^^

Test wit hadded space ^^


More immediacy. Turn on relay before trying network stuff

--- src/homie-sonoff-touch.ino
+++ src/homie-sonoff-touch.ino
@@ -74,13 +74,13 @@
   if ( function > 0 ) {
     Serial.println("One-shot");
     if ( function == 1 ) {
-      Serial.println("SINGLE click");
-      buttonNode.setProperty("event").setRetained(false).send("SINGLE");
       #ifdef IMMEDIATEON
         digitalWrite(PIN_RELAY, HIGH);
         relayNode.setProperty("relayState").send("ON");
         Serial.println("Relay is on");
       #endif
+      Serial.println("SINGLE click");
+      buttonNode.setProperty("event").setRetained(false).send("SINGLE");
     }

     if ( function == 2 ) {


refactor

refactor

--- esp8266_160227_filesysLib.ino
+++ esp8266_160227_filesysLib.ino
@@ -1,14 +1,14 @@

 // File System Library

-// TODO: 0c > some problem including <FS.h>, which cause invisibility for other library functions
-// instead, use EEPROM library (2016 Feb. 27)
+// some problem including <FS.h>, which cause invisibility for other library functions
+// instead, start using EEPROM library (2016 Feb. 27)

 //#include <FS.h>
 #include <EEPROM.h>

 /*
-Fils sytem
+File system
 Checked on staging 2.1.0-rc1 Arduino IDE 1.6.6 (2016 Feb. 27)
 */


whoops, should be an address

whoops, should be an address

--- master/master.ino
+++ master/master.ino
@@ -42,7 +42,7 @@
       input += c;
     } else {
       input.toCharArray(cmd,10);
-      byte okparse = sscanf(cmd, "%d %d", &address, state);
+      byte okparse = sscanf(cmd, "%d %d", &address, &state);
       printf("%d", state);

       if (okparse == 2 ) {


Added serial startup message

Added serial startup message

--- GarHAge.ino
+++ GarHAge.ino
@@ -307,6 +307,7 @@
 }

 void setup() {
+  Serial.println("Starting GarHAge...");
   // Setup the output and input pins used in the sketch
   // Set the lastStatusValue variables to the state of the status pins at setup time
   pinMode(door1_openPin, OUTPUT);


Reverted back to rising edge logic

Reverted back to rising edge logic

--- module/module.ino
+++ module/module.ino
@@ -208,33 +208,33 @@
 			// check for new ON signal aka rising edge
 			// so, if lastPeriodX and lastPeriodY WAS NOT a valid pair,
 			// begin accumulating time
-			/*if ( !inRange(lastPeriodX, lastPeriodY) ) {
+			if ( !inRange(lastPeriodX, lastPeriodY) ) {
 				startTime = millis();
 			}
 			// tracking number of valid pulses
-			pulseCount += 1;*/
-
-			if (checkHistory(signals) == flag.detectedJobStart) {
+			pulseCount += 1;
+
+			/*if (checkHistory(signals) == flag.detectedJobStart) {
 				if (startTime == 0) {
 					startTime = millis();
 				}
-			}
+			}*/
 		}
 		// if periodX and periodY IS NOT a valid pair
 		if ( !inRange(periodX, periodY) ) {
 			// check for new OFF signal aka falling edge
 			// so, if lastPeriodX and lastPeriodY WAS a valid pair
-			/*if ( inRange(lastPeriodX, lastPeriodY) ) {
+			if ( inRange(lastPeriodX, lastPeriodY) ) {
 				// check if the job was more than 5 seconds
 				if (pulseCount > minCount) {
 					// calculate elapsed time in seconds
 					return calculateTime(startTime);
 				}
 				pulseCount = 0;
-			}*/
+			}

 			// check if enough negative signals have been detected
-			if (checkHistory(signals) == flag.detectedJobEnd) {
+			/*if (checkHistory(signals) == flag.detectedJobEnd) {
 				elapsedTime = calculateTime(startTime);
 				if (startTime > 0) {
 					return elapsedTime;
@@ -244,7 +244,7 @@
 					elapsedTime = 0;
 					pulseCount = 0;
 				}
-			}
+			}*/
 		}

 		// record the previous state


start 1hr later

start 1hr later

--- SBR/SBR.ino
+++ SBR/SBR.ino
@@ -124,15 +124,17 @@
       measurevol();
       lcd.setCursor(0,1);
       lcd.print(tank);lcd.print("gal");
-      delay(30000);
+      delay(3000);
       measurevol();
       lcd.setCursor(0,1);
       lcd.print(tank);lcd.print("gal");
-      delay(30000);
-      digitalWrite(air,LOW);
+      //digitalWrite(air,LOW);
       if ((airadd == 1) && (millis()-lastair > 300000)){
        digitalWrite(air,HIGH);
        lastair = millis();
+      }
+      else if ((airadd == 1) && (millis()-lastair > 30000)){
+       digitalWrite(air,LOW);
       }
     }
   digitalWrite(fillpump, LOW);
@@ -286,12 +288,20 @@
   lcd.setCursor(0,1);
   lcd.print(tank);
   float starttime = millis();
+  digitalWrite(decantpump, HIGH);
+  delay(2000);
+  digitalWrite(decantpump, LOW);
+  delay(1000);
+  digitalWrite(decantpump, HIGH);
+  delay(2000);
+  digitalWrite(decantpump, LOW);
+  delay(1000);
  while (tank>level){
     digitalWrite(decantpump, HIGH);
     measurevol();
     lcd.setCursor(0,1);
   lcd.print(tank);lcd.print("gal  ");
-  delay(10000);}
+  delay(3000);}
     digitalWrite(decantpump, LOW);
 }
 void rest(float longt){ //everything off except maybe stir
@@ -424,27 +434,31 @@
   float current = now.unixtime();
   lcd.clear();
   lcd.setCursor(0, 0);
-  lcd.print(daysOfTheWeek[now.dayOfTheWeek()]);//"loop        ");
+  lcd.print(daysOfTheWeek[now.dayOfTheWeek()]);
   delay(100);
   lcd.setCursor(0,1);
   lcd.print(tank);
   while (x<1){
-   decant(6);//loading();
+   //aeration(60,19);
+   //delay(1000);
+   //settle(180,18);
+   //delay(1000);
+   //decant(6);//loading();
     x++;}
     //write conditions for running sequence here and add functions
   if (now.dayOfTheWeek()== 1){//"Monday"
-    if (now.hour()>6 && now.hour()<8){normalsequence();}}
+    if (now.hour()>7 && now.hour()<9){normalsequence();}}
   if (now.dayOfTheWeek()== 2){//"Tuesday"
-    if (now.hour()>6 && now.hour()<8){normalsequence();}}
+    if (now.hour()>7 && now.hour()<9){normalsequence();}}
   if (now.dayOfTheWeek()== 3){//"Wednesday"
-    if (now.hour()>6 && now.hour()<8){normalsequence();}}
+    if (now.hour()>7 && now.hour()<9){normalsequence();}}
   if (now.dayOfTheWeek()== 4){//"thursday"
-    if (now.hour()>6 && now.hour()<8){normalsequence();}}
+    if (now.hour()>7 && now.hour()<9){normalsequence();}}
   if (now.dayOfTheWeek()== 5){//"Friday"
-    if (now.hour()>6 && now.hour()<8){normalsequence();}}
+    if (now.hour()>7 && now.hour()<9){normalsequence();}}
   if (now.dayOfTheWeek()== 6){//"Saturday"
-    if (now.hour()>6 && now.hour()<8){normalsequence();}}//fillplusair(21,1);thirtysecaeration(100,10);}}
+    if (now.hour()>7 && now.hour()<9){normalsequence();}}//fillplusair(21,1);thirtysecaeration(100,10);}}
   if (now.dayOfTheWeek()== 0){//"Sunday"
-    if (now.hour()>6 && now.hour()<8){normalsequence();}}//weekend();}
+    if (now.hour()>7 && now.hour()<9){normalsequence();}}//weekend();}
   delay(20000);
   weekend();}


cleaned up and removed unessary variables

--- Arduino/sketches/Sensor_Module/RawSensorData.ino
+++ Arduino/sketches/Sensor_Module/RawSensorData.ino
@@ -4,21 +4,18 @@
 #define SAMPLERATE // uncomment to display sampling rate over serial port updates every 2 seconds with sampleing rate in Hz

 #include <avr/eeprom.h>
-// some of these variables probably are not useful eventually we should try and remove them.
+
 static uint16_t calibratingG;
 static int16_t  gyroADC[3],accADC[3],accSmooth[3],magADC[3];
 static int16_t gyroZero[3] = {0,0,0};
 static uint16_t acc_1G;             // this is the 1G measured acceleration
 static uint16_t calibratingA = 0;  // the calibration is done in the main loop. Calibrating decreases at each cycle down to 0, then we enter in a normal mode.
-static int16_t lookupPitchRollRC[6];// lookup table for expo & RC rate PITCH+ROLL
-static int16_t lookupThrottleRC[11];// lookup table for expo & mid THROTTLE
 static int16_t  acc_25deg;

 // ************************************************************************************************************
 // Main Program
 // ************************************************************************************************************
-
 void setup()
 {
   initSensors();
@@ -36,7 +33,6 @@
 	#endif

 }
-
 // ************************************************************************************************************
 // Helper Functions
 // ************************************************************************************************************


Delete TimeSync.ino

Delete TimeSync.ino

--- TimeSync/TimeSync.ino
+++ TimeSync/TimeSync.ino
@@ -1,64 +0,0 @@
-// go to the UNIX terminal and type: date +T%s -d +2hours > /dev/ttyACM1
-// of course, during the running sketch
-
-#include <TimeLib.h>
-
-const char TIME_HEADER = 'T'; // for serial time sync message
-int TIME_REQUEST = 7; // ASCII bell character requests a time sync message
-
-void setup()  {
-  Serial.begin(115200);
-  setSyncProvider( requestSync);  //set function to call when sync required
-  Serial.println("Send the message: 'date +T%s -d +2hours > /dev/ttyACM0' from the Terminal ");
-}
-
-void loop(){
-  if (Serial.available()) {
-    processSyncMessage();
-  }
-  if (timeStatus()!= timeNotSet) {
-    digitalClockDisplay();
-  }
-  delay(1000);
-}
-
-void digitalClockDisplay(){
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  Serial.print(month());
-  Serial.print(" ");
-  Serial.print(year());
-  Serial.println();
-}
-
-void printDigits(int digits){
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
-
-void processSyncMessage() {
-  unsigned long pctime;
-  const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
-
-  if(Serial.find(TIME_HEADER)) {
-     pctime = Serial.parseInt();
-     if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
-       setTime(pctime); // Sync Arduino clock to the time received on the serial port
-     }
-  }
-}
-
-time_t requestSync()
-{
-  Serial.write(TIME_REQUEST);
-  return 0; // the time will be sent later in response to serial message
-}


deep sleep testingg

deep sleep testingg

--- LORA_Water_Sensor/LORA_Water_Sensor.ino
+++ LORA_Water_Sensor/LORA_Water_Sensor.ino
@@ -14,6 +14,7 @@
 #include <LoRa.h>
 #include <Wire.h>
 #include "SSD1306.h"
+#include "esp_deep_sleep.h"

 #define echoPin 12 // Echo Pin
 #define trigPin 13 // Trigger Pin
@@ -33,7 +34,6 @@
 #define LORA_CRC        true  //Default: false
 /////////////////////////////////////////////////////////////

-SSD1306 display(0x3c, 4, 15);
 String rssi = "RSSI --";
 String packSize = "--";
 String packet ;
@@ -44,14 +44,12 @@
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);

-  digitalWrite(16, LOW);    // set GPIO16 low to reset OLED
-  delay(50);
-  digitalWrite(16, HIGH); // while OLED is running, must set GPIO16 in high
+  //digitalWrite(16, LOW);    // set GPIO16 low to reset OLED
+  //delay(50);
+  //digitalWrite(16, HIGH); // while OLED is running, must set GPIO16 in high

-  Serial.begin(9600);
+  Serial.begin(115200);
   while (!Serial);
-  Serial.println();
-  Serial.println("LoRa Sender Test");

   SPI.begin(SCK,MISO,MOSI,SS);
   LoRa.setPins(SS,RST,DI0);
@@ -66,12 +64,8 @@
   LoRa.setPreambleLength(LORA_PRELENGTH);
   if (LORA_CRC)
     LoRa.enableCrc();
-
-  Serial.println("init ok");
-  display.init();
-  display.flipScreenVertically();
-  display.setFont(ArialMT_Plain_10);
-  delay(1500);
+
+  delay(1000);
 }

 void loop() {
@@ -79,18 +73,29 @@
   Serial.println(distance);
   sendPacket("W:" + String(distance));

-  delay(10000);
+  //delay(10000);
+  // Deep Sleep Instead:
+  LoRa.end();
+  LoRa.sleep();
+  pinMode(19, INPUT);
+  pinMode(18, INPUT);
+  pinMode(5,  INPUT);
+  pinMode(15, INPUT);
+  pinMode(2,  INPUT);
+  pinMode(4,  INPUT);
+  pinMode(16, INPUT);
+  pinMode(26, INPUT);
+  pinMode(27, INPUT);
+  pinMode(14, INPUT);
+  delay(100);
+  esp_deep_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF);
+  esp_deep_sleep_pd_config(ESP_PD_DOMAIN_RTC_SLOW_MEM, ESP_PD_OPTION_OFF);
+  esp_deep_sleep_pd_config(ESP_PD_DOMAIN_RTC_FAST_MEM, ESP_PD_OPTION_OFF);
+  esp_sleep_enable_timer_wakeup(10000000);
+  esp_deep_sleep_start();
 }

 void sendPacket(String contents) {
-  display.clear();
-  display.setTextAlignment(TEXT_ALIGN_LEFT);
-  display.setFont(ArialMT_Plain_10);
-
-  display.drawString(0, 0, "Sending packet: ");
-  display.drawString(90, 0, contents);
-  display.display();
-
   // send packet
   LoRa.beginPacket();
   String packet = (contents);


Make a nice demo for new users

Make a nice demo for new users

--- chessclock/chessclock.ino
+++ chessclock/chessclock.ino
@@ -6,6 +6,7 @@
 #include "fds132text.h"

 fdsScreen mainScreen;
+fdsString *changeThisString;

 void setup() {

@@ -21,12 +22,18 @@
     SPI.begin();  // start the SPI library
     SPI.setBitOrder(MSBFIRST);  //Code was written for this
     initialiseLetters() ; // I haven't figured out the smart way to set all the letter variables to the value I want yet.
-    mainScreen.addString("Dat was lekker eten",0);
-    mainScreen.addString("Yeah! Echt Lekker",252);
+    mainScreen.addString("I love the arduino",0);
+    changeThisString = mainScreen.addString("a lot",90);
+    mainScreen.addString("-- Bart",225);
     mainScreen.update();
 }
 void loop()
 {
     mainScreen.display();
+    if (millis()>10000){
+        changeThisString -> set("More then ever");
+        mainScreen.update();
+
+    }
 }


encoder now calculates correct angular velocity

--- encoder.ino
+++ encoder.ino
@@ -1,3 +1,7 @@
+#include "Time.h"
+#include "math.h"
+
+
 /* Rotary encoder read example */
 #define ENC_A 14
 #define ENC_B 15
@@ -14,24 +18,49 @@
   Serial.println("Start");
 }

+time_t time_start = micros();
+time_t time_end = 0;
+
 void loop()
 {
- static uint8_t counter = 0;      //this variable will be changed by encoder input
- int8_t tmpdata;
+ static uint16_t counter = 0;      //this variable will be changed by encoder input
+ int16_t tmpdata;
+ const float pi = 3.141593;
  /**/
   tmpdata = read_encoder();
+
+  float omega = (2*pi * pow(10,6)) / (time_end - time_start);   //angular velocity rad/mus
+
+
+
   if( tmpdata ) {
-    Serial.print("Counter value: ");
-    Serial.println(counter, DEC);
+    if( !(counter % 50)){
+      Serial.print("Counter value: ");
+      Serial.println(counter, DEC);
+    }
     counter += tmpdata;
+    counter = counter % 4092;
+    if( !(counter) ) {
+      time_end = micros();
+      omega = (2*pi * pow(10,6)) / (time_end - time_start);
+      Serial.print("angular velocity: ");
+      Serial.println(omega, 5);
+      time_start = micros();
+    }
   }
 }

 /* returns change in encoder state (-1,0,1) */
-int8_t read_encoder()
+int16_t read_encoder()
 {
-  static int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
-  static uint8_t old_AB = 0;
+  static int16_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
+  static uint16_t old_AB = 0;
+}
+
+
+
+
+
   /**/
   old_AB <<= 2;                   //remember previous state
   old_AB |= ( ENC_PORT & 0x03 );  //add current state


No longer duplicating call to led(), which fixes #1.

--- LED/Array_Blink/Array_Blink.ino
+++ LED/Array_Blink/Array_Blink.ino
@@ -1,4 +1,4 @@
-const int BLINK_MILLIS = 50;
+const unsigned long BLINK_MILLIS = 100;
 const int NUM_LEDS = 6;
 const int LEDS[NUM_LEDS] = {13, 12, 11, 10, 9, 8};

@@ -9,9 +9,10 @@

 void blink(int ledNumber, int millisOn)
 {
-  digitalWrite(led(ledNumber), HIGH);
+  int pin = led(ledNumber);
+  digitalWrite(pin, HIGH);
   delay(millisOn);
-  digitalWrite(led(ledNumber), LOW);
+  digitalWrite(pin, LOW);
 }

 void setup(void)
@@ -26,11 +27,11 @@
 {
   for(int i = 0; i < NUM_LEDS; i++)
   {
-    blink(led(i), BLINK_MILLIS);
+    blink(i, BLINK_MILLIS);
     delay(BLINK_MILLIS);
-    blink(led(i), BLINK_MILLIS);
+    blink(i, BLINK_MILLIS);
     delay(BLINK_MILLIS);
-    blink(led(i), BLINK_MILLIS);
+    blink(i, BLINK_MILLIS);

     delay(1000);
   }


Minor refactoring

Minor refactoring

--- src/src.ino
+++ src/src.ino
@@ -2,6 +2,7 @@
 #include <Adafruit_GPS.h>
 extern "C" {
   #include "lcd.h"
+  #include "haversine.h"
 }

 #define GPSSerial Serial1
@@ -81,33 +82,3 @@
   lcd_print_float(GPS.longitude) ;
 }

-double calc_dist_coord(double lat_a, double lng_a, double lat_b, double lng_b)
-{
-  double a, c, del_lat, del_lng ;
-  double lat_a_radians = GPPGA_to_radians(lat_a) ;
-  double lng_a_radians = GPPGA_to_radians(lng_a) ;
-  double lat_b_radians = GPPGA_to_radians(lat_b) ;
-  double lng_b_radians = GPPGA_to_radians(lng_b) ;
-
-  /* use haversine formula */
-  del_lat = fabs(lat_a_radians - lat_b_radians) ;
-  del_lng = fabs(lng_a_radians - lng_b_radians) ;
-
-  a = 2*asin(sqrt(square(sin(del_lat/2))
-        + cos(lat_a)*cos(lat_b)*square(sin(del_lng/2)))) ;
-
-  /* alternative form */
-  /*
-  a = square(sin(del_lat/2)) + cos(lat_a)*cos(lat_b)*square(sin(del_lng/2)) ;
-  c = 2.0*atan2(sqrt(a), sqrt(1.0 - a)) ;
-  */
-
-  return a*MEAN_EARTH_RADIUS ;
-}
-
-double GPPGA_to_radians(double degrees)
-{
-  double integral, fractional ;
-  fractional = modf(degrees/100.0, &integral) ;
-  return (integral + fractional*100.0/60.0)*2*M_PI/360.0 ;
-}


Removed testing blocks

Removed testing blocks

--- RadioReceiver/RadioReceiver.ino
+++ RadioReceiver/RadioReceiver.ino
@@ -16,7 +16,7 @@
 {
   Serial.begin(9600);	// Debugging only
   Serial.println("setup");
-
+
   // Initialise the IO and ISR
   vw_set_rx_pin(receive_pin);
   vw_set_ptt_inverted(true); // Required for DR3100
@@ -25,11 +25,10 @@
   vw_rx_start();       // Start the receiver PLL running
 }

+
+
 void loop()
 {
-  char sz[] = "";
-  char *p = sz;
-  char *str;

   uint8_t buf[VW_MAX_MESSAGE_LEN];
   uint8_t buflen = VW_MAX_MESSAGE_LEN;
@@ -38,25 +37,10 @@
     int i;
     for (int i=0;i<buflen;i++)
     {
-      if (buf[i] == '#')
-      {
-        //Serial.print(" DINGDINGDING ");
-      }
-
       Serial.write(buf[i]);
       Serial.print("");
     }

-    ///TESTING BLOCK
-    Serial.println("");
-    Serial.println("***");
-    while ((str = strtok_r(p, "#", &p)) != NULL) // delimiter is the semicolon
-    {
-      Serial.println(str);
-    }
-    Serial.println("****");
-    /// END TEST BLOCk
-
     Serial.println("");
   }
 }


always read all analog sensors

always read all analog sensors


updated example

updated example

--- wifi-lib-interface-test/wifi-lib-interface-test.ino
+++ wifi-lib-interface-test/wifi-lib-interface-test.ino
@@ -5,6 +5,8 @@
   ECRY,
   ECRY_idx,
   MAC_ADDR,
+  DISCONNECT,
+  STATUS
 };

 unsigned long _startMillis;
@@ -85,6 +87,21 @@
        Serial1.write(0xFF);
        Serial1.write(0xEE);
        break;
+     case 6:   //get MacAddress
+       Serial1.write(0xE0);
+       Serial1.write(0x30);
+       Serial1.write(1);
+       Serial1.write(1);
+       Serial1.write(0xFF);
+       Serial1.write(0xEE);
+       break;
+     case 7:   //get Status
+       Serial1.write(0xE0);
+       Serial1.write(0x20);
+       Serial1.write(0);
+       Serial1.write(0xFF);
+       Serial1.write(0xEE);
+       break;
        }

   }
@@ -103,11 +120,16 @@
        //command(SSID);
        //command(RSSI_idx);
        //command(MAC_ADDR);
-
+       //command(DISCONNECT);
+       //command(STATUS);
+
        String prova = readStringUntil(0xEE);
        Serial.print("cmd: ");
-       for(int x=0;x<prova.length();x++)
+       for(int x=0;x<prova.length();x++){
           Serial.print((uint8_t)prova[x],HEX);
+       }
+       //uint8_t status = (prova[prova.length()-1]);
+       //Serial.print(status);
        Serial.println();


Added cooling option

Added cooling option

--- incuino/incuino.ino
+++ incuino/incuino.ino
@@ -1,4 +1,7 @@
 /*
+
+PID controller for controlling temperature by either using a heater or a cooler
+
  # Temperature
  OneWire DS18S20, DS18B20, DS1822 Temperature Example

@@ -15,10 +18,10 @@
 */

 #include <OneWire.h>
-#include <PID_v1.h>
-#include <Thread.h>
-#include <ThreadController.h>
-#include <TimerOne.h>
+#include <PID_v1.h> // https://github.com/br3ttb/Arduino-PID-Library
+#include <Thread.h> // https://github.com/ivanseidel/ArduinoThread
+#include <ThreadController.h> // https://github.com/ivanseidel/ArduinoThread
+#include <TimerOne.h> // https://github.com/PaulStoffregen/TimerOne
 #include <DallasTemperature.h>

 #define RELAY_PIN 8   // Connect Digital Pin 8 on Arduino to ? on Relay Module
@@ -29,6 +32,9 @@
 #define ERROR_CRC_IS_NOT_VALID -3000
 #define ERROR_FAILED_TO_RESET -4000

+const unsigned long COOLER = 1;
+const unsigned long HEATER = 0;
+const unsigned long TYPE = COOLER;
 const unsigned long WINDOW_SIZE = 100;
 const unsigned long PID_INTERVAL = 60000;

@@ -134,11 +140,11 @@
   Log.infoD("Input: ", _input);
   Log.infoD("Output: ", _output);

-  Log.infoL("Heat ON: ", runtime);
-  digitalWrite(RELAY_PIN, LOW);
+  Log.infoL("runtime ", runtime);
+  digitalWrite(RELAY_PIN, TYPE == HEATER ? LOW : HIGH);
+  Log.infoL("PID_INTERVAL - runtime ", PID_INTERVAL - runtime);
   while (millis() - _windowStartTime < runtime);
+  digitalWrite(RELAY_PIN, TYPE == HEATER ? HIGH : LOW);

-  Log.infoL("Heat OFF ", PID_INTERVAL - runtime);
-  digitalWrite(RELAY_PIN, HIGH);
   while (millis() - _windowStartTime < PID_INTERVAL);
 }


-Use transaction API to draw buttons.

-Use transaction API to draw buttons.

--- tfttask.ino
+++ tfttask.ino
@@ -284,11 +284,9 @@
   snprintf( TFT_NETWORK_AREA.text, sizeof( TFT_NETWORK_AREA.text ), "%s", ip4addr_ntoa( &ip_info.ip ) );
   drawButton( TFT_NETWORK_AREA, 0, 0 );

-
-  if ( touch.touched() )
-  {
-    TS_Point p = touch.getPoint();
-    if ( buttonPressed( MENU_BUTTON , p ) )
+  if ( touch.tirqTouched() )
+  {
+    if ( buttonPressed( MENU_BUTTON , touch.getPoint() ) )
     {
       tftState = menu;
       tftClearScreen = true;
@@ -300,14 +298,24 @@
 {
   tft.setTextSize( 2 );
   tft.setTextColor( ILI9341_YELLOW, color );
-  if ( color )
-  {
-    tft.fillRect( button.x, button.y, button.w, button.h, color );
-  }
-  if ( bordercolor )
-  {
-    tft.drawRect( button.x, button.y, button.w, button.h, bordercolor );
-  }
+
+  if ( color || bordercolor )
+  {
+    tft.startWrite();
+    if ( color )
+    {
+      tft.writeFillRect( button.x, button.y, button.w, button.h, color );
+    }
+    if ( bordercolor )
+    {
+      tft.writeFastHLine( button.x, button.y, button.w, bordercolor );
+      tft.writeFastHLine( button.x, button.y + button.h, button.w, bordercolor );
+      tft.writeFastVLine( button.x, button.y, button.h, bordercolor );
+      tft.writeFastVLine( button.x + button.w, button.y, button.h, bordercolor );
+    }
+    tft.endWrite();
+  }
+
   int16_t x, y;
   uint16_t w, h;
   tft.getTextBounds( button.text, 0, 0, &x, &y, &w, &h);
@@ -357,7 +365,6 @@
   tft.writeFillRect( sliderArea.x, sliderArea.y, sliderArea.w, sliderArea.h, ILI9341_BLACK);
   tft.writeFillRect( SLIDER_XPOS - 2, SLIDER_YPOS, 4, SLIDER_HEIGHT, ILI9341_YELLOW );
   tft.endWrite();
-//  tft.drawRect( SLIDER_XPOS - 2, SLIDER_YPOS, 4, SLIDER_HEIGHT, ILI9341_YELLOW );

   //drawButton( sliderArea, 0, ILI9341_GREEN ); //debug


Compass offset applied so x-axis of sensor is pointing forward

--- Arduino/Sailbot/Sailbot.ino
+++ Arduino/Sailbot/Sailbot.ino
@@ -43,7 +43,7 @@
 float heading;
 float rudder;
 float sheet;
-
+float compassOffset;

 Servo tillerServo;
 Servo sheetServo;
@@ -53,6 +53,7 @@
   Wire.begin();
   remoteState = SBTSailbotModelStateManualControl;
   windDirection = -1.0;
+  compassOffset = M_PI;
   calibratedWind = false;
   imu = RTIMU::createIMU(&settings);                        // create the imu object

@@ -113,12 +114,18 @@
     if (state != SBTSailbotModelStateCalibratingIMU && state != SBTSailbotModelStateNoIMU) {
       const RTVector3& vec = fusion.getFusionPose();
       float rawHeading = vec.z();
+      // Convert range to 0 to 2 * M_PI
       if (rawHeading < 0)
         heading = rawHeading + 2 * M_PI;
       else
         heading = rawHeading;
+      // Apply compass offset
+      if (heading > compassOffset)
+        heading -= compassOffset;
+      else
+        heading += compassOffset;
     }
-    char buffer[18];
+    char buffer[10];
     buffer[0] = SBTSailbotModelHeaderBoatState;
     buffer[1] = state;
     memcpy(&buffer[2], &heading, sizeof(heading));
@@ -154,15 +161,15 @@
       }
     case SBTSailbotModelHeaderManualControl: {
         remoteState = SBTSailbotModelStateManualControl;
-
+
         int remoteRudder;
         memcpy(&remoteRudder, &data[1], sizeof(remoteRudder));
         rudder = (float)remoteRudder;
-
+
         int remoteSheet;
         memcpy(&remoteSheet, &data[1 + 4], sizeof(remoteSheet));
         sheet = (float)remoteSheet;
-
+
         tillerServo.write(((rudder / 10.0) + M_PI / 2.0) * 180.0 / M_PI);
         sheetServo.write((sheet / 10.0) * 60 + 90);
         Serial.print("Manual control: "); Serial.println(rudder);


Easier debugging autoconnect

Easier debugging autoconnect

--- examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino
+++ examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino
@@ -70,8 +70,9 @@
 WiFiManager wm;

 // OPTION FLAGS
-bool TEST_CP  = true; // always start the configportal, even if ap found
+bool TEST_CP  = false; // always start the configportal, even if ap found
 bool TEST_NET = true; // do a network test after connect, (gets ntp time)
+bool AUTOSTARTCP = false; // automatically start config portal is no wifi found

 // char ssid[] = "*************";  //  your network SSID (name)
 // char pass[] = "********";       // your network password
@@ -199,7 +200,7 @@
   // wm.setShowPassword(true);

   // set configrportal timeout
-  wm.setConfigPortalTimeout(120);
+  wm.setConfigPortalTimeout(40);
   // wm.startConfigPortal("AutoConnectAP", "password");

   // wm.setBreakAfterConfig(true);
@@ -210,7 +211,7 @@
   //and goes into a blocking loop awaiting configuration

   print_oled(F("Connecting..."),2);
-  if(!wm.autoConnect("WM_AutoConnectAP")) {
+  if(!AUTOSTARTCP || !wm.autoConnect("WM_AutoConnectAP")) {
     Serial.println("failed to connect and hit timeout");
     print_oled("Not Connected",2);
   }
@@ -234,6 +235,8 @@
 }

 void loop() {
+
+  Serial.println((String)analogRead(A0));

   #ifdef USEOTA
   ArduinoOTA.handle();


Put filename strings into progmem

Put filename strings into progmem

--- invaders.ino
+++ invaders.ino
@@ -65,44 +65,58 @@
   uint16_t max_size;      // Size checking to avoid overflow.
 };

+// Filenames.  To avoid cumbersome declarations of multiple strings, these are
+// combined into one long string, delimited by null terminators.
+const char kFilenames[] PROGMEM =
+  "ship.raw\0"
+  "alien1.raw\0"
+  "alien2.raw\0"
+  "alien3.raw\0"
+  "bonus.raw\0"
+  "bonus_sm.raw\0"
+  "shot.raw\0"
+  "shield.raw\0"
+  "explode.raw\0"
+  "palette.pal\0"
+;
+
 // Image, palette, and tilemap data.
 const File kFiles[] PROGMEM = {
   // Image data.
-  { "ship.raw", &g_vram_offsets[GAME_ENTITY_PLAYER], 0, 0, VRAM_BANK_SIZE },
-  { "alien1.raw", &g_vram_offsets[GAME_ENTITY_ALIEN], 0, 0, VRAM_BANK_SIZE },
-  { "alien2.raw", &g_vram_offsets[GAME_ENTITY_ALIEN2], 0, 0, VRAM_BANK_SIZE },
-  { "alien3.raw", &g_vram_offsets[GAME_ENTITY_ALIEN3], 0, 0, VRAM_BANK_SIZE },
-  { "bonus.raw", &g_vram_offsets[GAME_ENTITY_BONUS_SHIP], 0, 0,
-    VRAM_BANK_SIZE },
-  { "bonus_sm.raw", &g_vram_offsets[GAME_ENTITY_SMALL_BONUS_SHIP], 0, 0,
-    VRAM_BANK_SIZE },
-  { "shot.raw", &g_vram_offsets[GAME_ENTITY_SHOT], 0, 0, VRAM_BANK_SIZE },
-  { "shield.raw", &g_vram_offsets[GAME_ENTITY_SHIELD_PIECE], 0, 0,
-    VRAM_BANK_SIZE },
-  { "explode.raw", &g_vram_offsets[GAME_ENTITY_EXPLOSION], 0, 0,
-    VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_PLAYER], 0, 0, VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_ALIEN], 0, 0, VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_ALIEN2], 0, 0, VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_ALIEN3], 0, 0, VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_BONUS_SHIP], 0, 0, VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_SMALL_BONUS_SHIP], 0, 0, VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_SHOT], 0, 0, VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_SHIELD_PIECE], 0, 0, VRAM_BANK_SIZE },
+  { NULL, &g_vram_offsets[GAME_ENTITY_EXPLOSION], 0, 0, VRAM_BANK_SIZE },

   // Palette data.
-  { "palette.pal", NULL, PALETTE(BASE_PALETTE_INDEX), 0, PALETTE_SIZE },
+  { NULL, NULL, PALETTE(BASE_PALETTE_INDEX), 0, PALETTE_SIZE },
 };
-

 // Load image, palette, and tilemap data from file system.
 void loadResources() {
+  uint16_t string_offset = 0;
   uint16_t vram_offset = 0;
   for (int i = 0; i < sizeof(kFiles) / sizeof(kFiles[0]); ++i) {
-    //const File& file = kFiles[i];
-
-    union {
-      File file;
-      uint8_t file_bytes[0];
-    };
-    for (int offset = 0; offset < sizeof(file); ++offset) {
-      file_bytes[offset] =
-          pgm_read_byte(((const uint8_t*)(&kFiles[i])) + offset);
-    }
+    // Read file info from program memory.
+    File file;
+    memcpy_P(&file, kFiles + i, sizeof(file));
+
     char filename[256];
-    sprintf(filename, "%s/%s", kFilePath, file.filename);
+    sprintf(filename, "%s/", kFilePath);
+    size_t len = strlen(filename);
+    // Append the filename from program memory.
+    size_t filename_len = strlen_P(kFilenames + string_offset);
+    if (filename_len + len + 1 > sizeof(filename)) {
+      printf("Filename is too long.\n");
+      continue;
+    }
+    memcpy_P(filename + len, kFilenames + string_offset, filename_len + 1);
+    string_offset += filename_len + 1;    // Update offset to next filename.

     // Open the file.
     uint16_t handle = DC.File.open(filename, FILE_READ_ONLY);


More comment and code style refactoring, braces on same line

--- Wild_Thumper_Controller.ino
+++ Wild_Thumper_Controller.ino
@@ -19,16 +19,22 @@
 int Rightspeed=0;
 int Speed;
 int Steer;
+
 // 0=Flat battery  1=Charged battery
 byte Charged=1;
+
 // 0=reverse, 1=brake, 2=forward
 int Leftmode=1;
+
 // 0=reverse, 1=brake, 2=forward
 int Rightmode=1;
+
 // PWM value for left  motor speed / brake
 int LeftPWM;
+
 // PWM value for right motor speed / brake
 int RightPWM;
+
 int data;
 int servo[7];

@@ -77,8 +83,7 @@
   // Disable current regulator to charge battery
   digitalWrite(Charger, 1);

-  if (Cmode==1)
-  {
+  if (Cmode==1) {
     // enable serial communications if Cmode=1
     Serial.begin(Brate);

@@ -91,6 +96,7 @@
   }

   Serial.print("Wild Thumper started in ");
+
   switch(Cmode) {
     case 0:
       Serial.print("RC");
@@ -102,13 +108,13 @@
       Serial.print("I2C");
       break;
   }
+
   Serial.println(" mode");
   logBatteryVoltage();
 }

-void loop()
-{
+void loop() {
   //
   // Check battery voltage and current draw of motors
   //
@@ -126,8 +132,7 @@
   //Serial.print("    ");
   //Serial.println(RightAmps);

-  if (LeftAmps>Leftmaxamps)                                   // is motor current draw exceeding safe limit
-  {
+  if (LeftAmps>Leftmaxamps) { // is motor current draw exceeding safe limit
     // Turn off motors
     analogWrite (LmotorA,0);
     analogWrite (LmotorB,0);
@@ -136,8 +141,7 @@
     leftoverload=millis();
   }

-  if (RightAmps>Rightmaxamps)                                 // is motor current draw exceeding safe limit
-  {
+  if (RightAmps>Rightmaxamps) { // is motor current draw exceeding safe limit
     // Turn off motors
     analogWrite (RmotorA,0);
     analogWrite (RmotorB,0);
@@ -146,9 +150,7 @@
     rightoverload=millis();
   }

-  if ((Volts<lowvolt) && (Charged==1))                        // check condition of the battery
-  {                                                           // change battery status from charged to flat
-
+  if ((Volts<lowvolt) && (Charged==1)) { // check condition of the battery                                                           // change battery status from charged to flat
     //
     // FLAT BATTERY speed controller shuts down until battery is recharged
     //
@@ -177,14 +179,14 @@
     digitalWrite(Charger,0);
   }

-  //
-  // CHARGE BATTERY
-  //
-
-  if ((Charged==0) && (Volts-startVolts>67))                  // if battery is flat and charger has been connected (voltage has increased by at least 1V)
-  {
-    if (Volts>highVolts)                                      // has battery voltage increased?
-    {
+  if ((Charged==0) && (Volts-startVolts>67)) {
+    //
+    // CHARGE BATTERY
+    //
+    // if battery is flat and charger has been connected (voltage has increased by at least 1V)
+
+    // has battery voltage increased?
+    if (Volts>highVolts) {
       // record the highest voltage. Used to detect peak charging.
       highVolts=Volts;

@@ -197,10 +199,10 @@
       reportTimer=millis();
     }

-    if (Volts>batvolt)                                        // battery voltage must be higher than this before peak charging can occur.
-    {
-      if ((highVolts-Volts)>5 || (millis()-chargeTimer)>chargetimeout) // has voltage begun to drop or levelled out?
-      {
+    // battery voltage must be higher than this before peak charging can occur.
+    if (Volts>batvolt) {
+      // has voltage begun to drop or levelled out?
+      if ((highVolts-Volts)>5 || (millis()-chargeTimer)>chargetimeout) {
         // battery voltage has peaked
         Charged=1;

@@ -222,9 +224,7 @@
     //
     // GOOD BATTERY speed controller opperates normally
     //
-
-    switch(Cmode)
-    {
+    switch(Cmode) {
       // RC mode via D0 and D1
       case 0:
         RCmode();
@@ -245,50 +245,46 @@
     // Code to drive dual "H" bridges
     //

-    if (Charged==1)                                           // Only power motors if battery voltage is good
-    {
-      if ((millis()-leftoverload)>overloadtime)
-      {
-        switch (Leftmode)                                     // if left motor has not overloaded recently
-        {
-        case 2:                                               // left motor forward
-          analogWrite(LmotorA,0);
-          analogWrite(LmotorB,LeftPWM);
-          break;
-
-        case 1:                                               // left motor brake
-          analogWrite(LmotorA,LeftPWM);
-          analogWrite(LmotorB,LeftPWM);
-          break;
-
-        case 0:                                               // left motor reverse
-          analogWrite(LmotorA,LeftPWM);
-          analogWrite(LmotorB,0);
-          break;
+    if (Charged==1) { // Only power motors if battery voltage is good
+      if ((millis()-leftoverload)>overloadtime) {
+        switch (Leftmode) { // if left motor has not overloaded recently
+          case 2:                                               // left motor forward
+            analogWrite(LmotorA,0);
+            analogWrite(LmotorB,LeftPWM);
+            break;
+
+          case 1:                                               // left motor brake
+            analogWrite(LmotorA,LeftPWM);
+            analogWrite(LmotorB,LeftPWM);
+            break;
+
+          case 0:                                               // left motor reverse
+            analogWrite(LmotorA,LeftPWM);
+            analogWrite(LmotorB,0);
+            break;
         }
       }
-      if ((millis()-rightoverload)>overloadtime)
-      {
-        switch (Rightmode)                                    // if right motor has not overloaded recently
-        {
-        case 2:                                               // right motor forward
-          analogWrite(RmotorA,0);
-          analogWrite(RmotorB,RightPWM);
-          break;
-
-        case 1:                                               // right motor brake
-          analogWrite(RmotorA,RightPWM);
-          analogWrite(RmotorB,RightPWM);
-          break;
-
-        case 0:                                               // right motor reverse
-          analogWrite(RmotorA,RightPWM);
-          analogWrite(RmotorB,0);
-          break;
+
+      if ((millis()-rightoverload)>overloadtime) {
+        switch (Rightmode) { // if right motor has not overloaded recently
+          case 2:                                               // right motor forward
+            analogWrite(RmotorA,0);
+            analogWrite(RmotorB,RightPWM);
+            break;
+
+          case 1:                                               // right motor brake
+            analogWrite(RmotorA,RightPWM);
+            analogWrite(RmotorB,RightPWM);
+            break;
+
+          case 0:                                               // right motor reverse
+            analogWrite(RmotorA,RightPWM);
+            analogWrite(RmotorB,0);
+            break;
         }
       }
     }
-    else {
+    else {
       // Battery is flat
       // Turn off motors
       analogWrite(LmotorA,0);
@@ -300,12 +296,10 @@
 }

-void RCmode()
-{
-  //
-  // Code for RC inputs
-  //
-
+//
+// Code for RC inputs
+//
+void RCmode() {
   // read throttle/left stick
   Speed=pulseIn(RCleft,HIGH,25000);

@@ -324,15 +318,13 @@
   // if Steer input is within deadband set to 1500 (1500uS=center position for most servos)
   if (abs(Steer-1500)<RCdeadband) Steer=1500;

-  if (Mix==1)
-  {
+  if (Mix==1) {
     // Mixes speed and steering signals
     Steer=Steer-1500;
     Leftspeed=Speed-Steer;
     Rightspeed=Speed+Steer;
   }
-  else
-  {
+  else {
     // Individual stick control
     Leftspeed=Speed;
     Rightspeed=Steer;
@@ -347,22 +339,26 @@

   Leftmode=2;
   Rightmode=2;
-
+
   // if left input is forward then set left mode to forward
-  if (Leftspeed>(Leftcenter+RCdeadband)) Leftmode=0;
-
+  if (Leftspeed>(Leftcenter+RCdeadband)) {
+    Leftmode=0;
+  }
+
   // if right input is forward then set right mode to forward
-  if (Rightspeed>(Rightcenter+RCdeadband)) Rightmode=0;
+  if (Rightspeed>(Rightcenter+RCdeadband)) {
+    Rightmode=0;
+  }

   // scale 1000-2000uS to 0-255
   LeftPWM=abs(Leftspeed-Leftcenter)*10/scale;
-
+
   // set maximum limit 255
   LeftPWM=min(LeftPWM,255);

   // scale 1000-2000uS to 0-255
   RightPWM=abs(Rightspeed-Rightcenter)*10/scale;
-
+
   // set maximum limit 255
   RightPWM=min(RightPWM,255);
 }
@@ -379,49 +375,49 @@
 //      right motor mode 0-2
 //      right motor PWM  0-255
 void SCmode() {
-  if (Serial.available()>1)
-  {
+  if (Serial.available()>1) {
     int A=Serial.read();
     int B=Serial.read();
     int command=A*256+B;
-    switch (command)
-    {
-      case ST: // Stop
+    switch (command) {
+      // Stop
+      case ST:
          Leftmode=1;
          LeftPWM=0;
          Rightmode=1;
          RightPWM=0;
          break;

-      case BT: // Battery level
+      // Check battery level
+      case BT:
         logBatteryVoltage();
         break;

-      case FL:                                                // FL
-        // flush buffer
+      // Flush buffer
+      case FL:
         Serial.flush();
         break;

-      case AN:                                                // AN - return values of analog inputs 1-5
+      // AN - return values of analog inputs 1-5
+      case AN:
         Serial.println('Reporting analog input values');
-        for (int i=1;i<6;i++)                                 // index analog inputs 1-5
-        {
+        // index analog inputs 1-5
+        for (int i=1;i<6;i++) {
           // read 10bit analog input
           data=analogRead(i);
-
+
           // transmit high byte
           Serial.write(highByte(data));
-
+
           // transmit low byte
           Serial.write(lowByte(data));
         }
         break;

         // SV - receive postion information for servos 0-6
-       case SV:
-         // read 14 bytes of data
-         for (int i=0;i<15;i++)
-         {
+       case SV:
+         // read 14 bytes of data
+         for (int i=0;i<15;i++) {
            Serialread();
            servo[i]=data;
          }
@@ -435,8 +431,8 @@
          Servo6.writeMicroseconds(servo[12]*256+servo[13]);
          break;

-       // HB - mode and PWM data for left and right motors
-       case HB:
+       // Set mode and PWM data for left and right motors
+       case HB:
          Serialread();
          Leftmode=data;
          Serialread();
@@ -446,6 +442,7 @@
          Serialread();
          RightPWM=data;

+         /*
          Serial.print("Leftmode = ");
          Serial.print(Leftmode);
          Serial.print(" at ");
@@ -454,11 +451,12 @@
          Serial.print(Rightmode);
          Serial.print(" at ");
          Serial.println(RightPWM);
+         */

          break;

        // invalid command
-       default:
+       default:
          Serial.flush();
     }
   }
@@ -467,22 +465,15 @@
 //
 // Read serial port until data has been received
 //
-void Serialread()
-{
-  do
-  {
+void Serialread() {
+  do {
     data=Serial.read();
   } while (data<0);
 }

-
-void I2Cmode()
-{
-//
-// Your code goes here
-//
-}
-
+void I2Cmode() {
+  // Your code goes here
+}

 void logBatteryVoltage() {
   int units = analogRead(Battery);
@@ -493,4 +484,3 @@
   Serial.print(units);
   Serial.println(" units)");
 }
-


Update setupFunctions.ino

Update setupFunctions.ino

--- arduino/setupFunctions.ino
+++ arduino/setupFunctions.ino
@@ -1,9 +1,10 @@
-void startPins(){
-
+void startPins() {
+  pinMode(PAN_PIN, OUTPUT);
+  pinMode(LED_BUILTIN, OUTPUT);
 }

-void initialize(){
-	//panServo.attach(panPin);
-	//panServo.attach(tiltPin);
-	mpuSetup();
+void initialize() {
+  panServo.attach(PAN_PIN);
+  //panServo.attach(tiltPin);
+  mpuSetup();
 }


Tracking local non-updates.

Tracking local non-updates.

--- Wetteranzeige/Wetteranzeige.ino
+++ Wetteranzeige/Wetteranzeige.ino
@@ -32,7 +32,7 @@
 bool displayUpdated = false;
 unsigned long systemStart = 0;

-unsigned long tempUpdateThreshold = 6000L;
+uint8_t cyclesWithoutUpdateThreshold = 5;

 #include "CrcableData.h"

@@ -40,6 +40,7 @@
 public:
   float displayedInternalTemperature = -100;
   float displayedInternalHumidity = -100;
+  uint8_t cyclesWithoutShow = 0;
   bool externalDataValid = false;
   float lastExternalTemperature = 0;
   float lastExternalHumidity = 0;
@@ -50,7 +51,7 @@
 SystemState systemState;
 TH localData;

-ADC_MODE(ADC_VCC);
+//ADC_MODE(ADC_VCC);

 void setup()
 {
@@ -164,20 +165,25 @@
     boolean internalIsToBeShown = systemState.displayedInternalTemperature == -100;

     if (!internalIsToBeShown) {
-      TH lastInternalData;
-      lastInternalData.temperature = systemState.displayedInternalTemperature;
-      lastInternalData.humidity = systemState.displayedInternalHumidity;
-      updateVaporPressure(&lastInternalData);
-
-      if (abs(systemState.displayedInternalTemperature - localData.temperature) > 0.21
-          || abs(lastInternalData.vaporPressure - localData.vaporPressure) > 0.29) {
-          internalIsToBeShown = true;
-
-          Serial.print("Updating because of difference ");
-          Serial.println(abs(systemState.displayedInternalTemperature - localData.temperature));
+      if (systemState.cyclesWithoutShow > cyclesWithoutUpdateThreshold) {
+        Serial.println("Update after no shows");
+        internalIsToBeShown = true;
       } else {
-        Serial.println("No update. No external data and no internal change.");
-        // NOTE the "update at least every X tries" is handled indirectly by the external source
+        TH lastInternalData;
+        lastInternalData.temperature = systemState.displayedInternalTemperature;
+        lastInternalData.humidity = systemState.displayedInternalHumidity;
+        updateVaporPressure(&lastInternalData);
+
+        if (abs(systemState.displayedInternalTemperature - localData.temperature) > 0.21
+            || abs(lastInternalData.vaporPressure - localData.vaporPressure) > 0.29) {
+            internalIsToBeShown = true;
+
+            Serial.print("Updating because of difference ");
+            Serial.println(abs(systemState.displayedInternalTemperature - localData.temperature));
+        } else {
+          Serial.println("No update. No external data and no internal change.");
+          // NOTE the "update at least every X tries" is handled indirectly by the external source
+        }
       }
     }

@@ -190,6 +196,8 @@
       }

       updateDisplay(&localData, &externalData);
+    } else {
+      systemState.cyclesWithoutShow++;
     }
   }

@@ -240,6 +248,7 @@

   display.updatePartOrFull();
   displayUpdated = true;
+  systemState.cyclesWithoutShow = 0;
 }

 void updateVaporPressure(TH *th)


moved to "Old_Arduino_Code"

moved to "Old_Arduino_Code"

--- STAB_1_code/STAB_1_code.ino
+++ STAB_1_code/STAB_1_code.ino
@@ -1,172 +0,0 @@
-#include <SD.h> //Load the SD library
-#include <SPI.h> //Load the SPI comm library
-
-int chipSelect=4; //Set chipselct = 4
-File mySensorData; //Variable for working with our file object
-
-#include "Wire.h"    // imports the wire library for talking over I2C
-#include "Adafruit_BMP085.h"  // import the Pressure Sensor Library
-Adafruit_BMP085 mySensor;  // create sensor object called mySensor
-
-float tempC;  // Variable for holding temp in C
-float tempF;  // Variable for holding temp in F
-float pressure; //Variable for holding pressure reading
-
-#include "I2Cdev.h" // import I2Cdev library required for MPU6050 library
-#include "MPU6050.h" // import MPU6050 accel/gyro 6DOF sensor library
-MPU6050 accelgyro; //create sensor object called accelgyro
-int16_t ax, ay, az; //Variables for accel x-dir, y-dir, and z-dir
-int16_t gx, gy, gz; //Variables for gyro x-dir, y-dir, and z-dir
-#define OUTPUT_READABLE_ACCELGYRO //Output data as readable data
-
-#include <HMC5883L.h> //import library for HMC5883L magnetometer (NEEDS 'Wire' library)
-HMC5883L compass; //create sensor object called compass
-
-#include <Servo.h> //import Servo library
-Servo myservo; //create servo object called myservo
-
-unsigned long time; //include time variable
-
-void setup(){
-pinMode(8, OUTPUT);
-digitalWrite(8, HIGH);
-
-//Serial.begin(9600); //turn on serial monitor (Uncomment when not testing)
-mySensor.begin();   //initialize mySensor
-
-#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE // join I2C bus (I2Cdev library doesn't do this automatically)
-Wire.begin();
-#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
-Fastwire::setup(400, true);
-#endif
-accelgyro.initialize();
-
-compass.begin(); // Initialize Initialize HMC5883L
-compass.setRange(HMC5883L_RANGE_1_3GA); // Set measurement range
-compass.setMeasurementMode(HMC5883L_CONTINOUS); // Set measurement mode
-compass.setDataRate(HMC5883L_DATARATE_30HZ); // Set data rate
-compass.setSamples(HMC5883L_SAMPLES_8); // Set number of samples averaged
-compass.setOffset(0, 0); // Set calibration offset. See HMC5883L_calibration.ino
-
-myservo.attach(9); //Pin 9 for servo 1 and 2 (share same output angles)
-
-pinMode(10, OUTPUT); //Reserve 10 as an output (SD LIBRAY REQUIREMENT)
-SD.begin (chipSelect); //Initialize the SD card with chipSelect connected to pin 4
-
-pinMode(2, OUTPUT); //Loop check LED
-}
-
-void loop() {
-time = millis(); // find current time since program began
-
-//Temperature and Pressure
-tempC = mySensor.readTemperature(); //  Read Temperature
-tempF = tempC*1.8 + 32.; // Convert degrees C to F
-pressure=mySensor.readPressure(); //Read Pressure
-
-//Accel and Gyro
-accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); //read accel/gyro data
-
-//Compass
-Vector norm = compass.readNormalize();
-float heading = atan2(norm.YAxis, norm.XAxis); // Calculate heading
-// Set declination angle on your location and fix heading
-// You can find your declination on: http://magnetic-declination.com/
-// (+) Positive or (-) for negative
-// For Bytom / Poland declination angle is 4'26E (positive)
-// Formula: (deg + (min / 60.0)) / (180 / M_PI);
-float declinationAngle = (4.0 + (26.0 / 60.0)) / (180 / M_PI);
-heading += declinationAngle;
-if (heading < 0) // Correct for heading < 0deg and heading > 360deg
-{
-heading += 2 * PI;
-}
-if (heading > 2 * PI)
-{
-heading -= 2 * PI;
-}
-float headingDegrees = heading * 180/M_PI; // Convert to degrees
-
-// Servo
-float a = 60; //max angle of attack
-float d = 90;
-float x = headingDegrees; //floored headingDegrees
-//float b = x % 180; //new range of repeated values from 0 to 179. (alpha(theta=0) = aplha(theta=180))
-float b = x; //adjusted heading
-if (x > 180 && x <= 360){
-  b = x - 180;
-}
-float c; //output angle of attack
-if (b >= 15 && b <= 90){
-  c = -a*sin((PI/150)*x-PI/10) + d;
-}
-else if (b > 90 && b <= 165){
-  c = a*cos((PI/150)*x-3*PI/5) + d;
-}
-//else if (b >= 95 && b <= 130){
-//  c = a*sin((PI/70)*x-19*PI/14) + d;
-//}
-//else if (b >= 140 && b <= 175){
-//  c = -a*cos((PI/70)*x) + d;
-//}
-else{
-c = d;
-}
-myservo.write(c); //write to servo 1 and 2
-
-mySensorData= SD.open("Data2.txt", FILE_WRITE); //Open PTData.txt on the SD card as a file to write.
-
-if (mySensorData) { //Only do these things if data file opened successfully
-/*
-Serial.print("The Temp is: "); //Print Your results of BMP180 data (Uncomment when not testing)
-Serial.print(tempF); //(Uncomment when not testing)
-Serial.println(" degrees F"); //(Uncomment when not testing)
-Serial.print("The Pressure is: "); //(Uncomment when not testing)
-Serial.print(pressure); //(Uncomment when not testing)
-Serial.println(" Pa."); //(Uncomment when not testing)
-Serial.println("");  //(Uncomment when not testing)
-
-Serial.print("a/g:\t");  //Print results of MPU6050 data (Uncomment when not testing)
-Serial.print(ax); Serial.print("\t");  //(Uncomment when not testing)
-Serial.print(ay); Serial.print("\t");  //(Uncomment when not testing)
-Serial.print(az); Serial.print("\t");  //(Uncomment when not testing)
-Serial.print(gx); Serial.print("\t");  //(Uncomment when not testing)
-Serial.print(gy); Serial.print("\t");  //(Uncomment when not testing)
-Serial.println(gz);  //(Uncomment when not testing)
-Serial.println("");  //(Uncomment when not testing)
-
-Serial.print(" Heading = ");  //Print results of HMC5883L data (Uncomment when not testing)
-Serial.print(heading);  //(Uncomment when not testing)
-Serial.print(" Degress = ");  //(Uncomment when not testing)
-Serial.print(headingDegrees);  //(Uncomment when not testing)
-Serial.println("");  //(Uncomment when not testing)
-*/
-
-digitalWrite(2, HIGH); //Loop check LED on
-delay(100); //Pause between readings.
-digitalWrite(2, LOW); //Loop check LED off
-
-mySensorData.print(time); //Write tempF to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(tempF); //Write tempF to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(pressure); //Write pressure data
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(ax); //Write ax to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(ay); //Write ay to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(az); //Write az to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(gx); //Write gx to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(gy); //Write gy to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(gz); //Write gz to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.print(heading); //Write heading to the SD card
-mySensorData.print(","); //Write comma to the line
-mySensorData.println(headingDegrees); //Write headingDegrees to the SD card and go to next line
-mySensorData.close(); //Close the file
-}
-}


a basic example of using the driver

a basic example of using the driver


Charger: corner cases

Charger: corner cases

Signed-off-by: Robert Nelson <d6c41255011d14bfa93d8562b946ca186cfa0c7b@gmail.com>

--- BatteryCharger/BatteryCharger.ino
+++ BatteryCharger/BatteryCharger.ino
@@ -65,6 +65,22 @@
 	relay_mode=RELAY_A1_ON;
 }

+void turnon(){
+	pinMode(A0, OUTPUT);
+	digitalWrite(A0, HIGH);
+	delay(10);
+	digitalWrite(A0, LOW);
+	relay_mode = RELAY_A0_ON;
+}
+
+void turnoff(){
+	pinMode(A1, OUTPUT);
+	digitalWrite(A1, HIGH);
+	delay(10);
+	digitalWrite(A1, LOW);
+	relay_mode = RELAY_A1_ON;
+}
+
 void loop () {
 	//Print readings every second
 	if (millis() - lastSecond >= 7000)
@@ -114,23 +130,21 @@

 		//Turn on
 		if ( relay_mode == RELAY_A1_ON ) {
-			if (( busvoltage_A > 12.6 ) && ( current_mA_B > 400 )) {
-				pinMode(A0, OUTPUT);
-				digitalWrite(A0, HIGH);
-				delay(10);
-				digitalWrite(A0, LOW);
-				relay_mode = RELAY_A0_ON;
+			if ( busvoltage_A > 13 ) {
+				turnon;
+			}
+			else if (( busvoltage_A > 12.6 ) && ( current_mA_B > 400 )) {
+				turnon;
 			}
 		}

 		//Turn off
 		if ( relay_mode == RELAY_A0_ON ) {
-			if ( busvoltage_A < 12.3 ) {
-				pinMode(A1, OUTPUT);
-				digitalWrite(A1, HIGH);
-				delay(10);
-				digitalWrite(A1, LOW);
-				relay_mode = RELAY_A1_ON;
+			if ( busvoltage_A < 12.1 ) {
+				turnoff;
+			}
+			else if (( current_mA_A > 100 ) && ( current_mA_A < 200 )) {
+				turnon;
 			}
 		}


Patch error where a battery could stop prematurely

--- Battery_Tester/Battery_Tester.ino
+++ Battery_Tester/Battery_Tester.ino
@@ -324,8 +324,8 @@
 void startInStationMode(){
 		WiFi.mode(WIFI_STA);
 		delay(1);
-        char  ssid[33]  = "AP_Name";
-        char  password[64]  = "AP_Password";
+        char  ssid[33]  = "AP_Name";
+        char  password[64]  = "AP_Password";
         struct  station_config  stationConf;
         stationConf.bssid_set = 0;            //need  not check MAC address of  AP
         os_memcpy(&stationConf.ssid,  ssid, 33);
@@ -357,8 +357,13 @@
 			for (int a=0;a<MAX_BATTERIES;a++){
 				int nextComma = dataString.indexOf(",");
 				String theData = dataString.substring(0,nextComma);
-				batteryinfo[a].currentVoltage = (long(theData.toFloat()*100000.0) / 100000.0); // round back to 5 dp
-				if (batteryinfo[a].currentVoltage > 0){
+				batteryinfo[a].currentVoltage = (long(theData.toFloat()*100000.0) / 100000.0); // round back to 5 dp (long(theData.toFloat()*100000.0) / 100000.0);
+				if (batteryinfo[a].currentVoltage > 1 && batteryinfo[a].stopTime > 0){ 			// recieved false stop
+					batteryinfo[a].stopTime = -1;	// reset and continue
+					batteryinfo[a].capacity = -1;
+					batteriesStopped--;
+				}
+				if (batteryinfo[a].currentVoltage > 0 && batteryinfo[a].stopTime < 0){
 					batteryinfo[a].currentVoltage += 0.00001; // TODO: complete fix for rounding error
 					batteryinfo[a].currentCurrent = (batteryinfo[a].currentVoltage - mosfetVoltageDrop) / batteryinfo[a].resistorValue;
 					batteryinfo[a].totalCurrent +=  batteryinfo[a].currentCurrent / 3600.0; // at one sample per second


Fix return type in step seq line() func

Fix return type in step seq line() func

--- OONTZ_Step_Seq/OONTZ_Step_Seq.ino
+++ OONTZ_Step_Seq/OONTZ_Step_Seq.ino
@@ -71,7 +71,7 @@
 }

 // Turn on (or off) one column of the display
-uint8_t line(uint8_t x, boolean set) {
+void line(uint8_t x, boolean set) {
   uint8_t mask = pgm_read_byte(&bitmask[x]);
   for(uint8_t y=0; y<8; y++) {
     uint8_t i = pgm_read_byte(&xy2i[x][y]);


distanceSensor.ino includes set to general

--- src/distanceSensor.ino
+++ src/distanceSensor.ino
@@ -10,8 +10,8 @@

 // INCLUDES -------------------------------------------------------------
 #include <LiquidCrystal.h>
-#include <C:\Users\Jaime\Documents\Arduino\test\distanceSensor\Ultrasonic.h>
-#include <C:\Users\Jaime\Documents\Arduino\test\distanceSensor\signalFunction.h>
+#include "Ultrasonic.h"
+#include "signalFunction.h"


Toupie 2 \o/

Toupie 2 \o/

--- pug.ino
+++ pug.ino
@@ -29,7 +29,8 @@
 #define ULTRASOUND true // Disable ultrason if false

 // Goodies mode
-#define TOUPIE true
+#define TOUPIE false
+#define TOUPIE_2 false

 IntervalTimer ultraTimer;
 IntervalTimer motorTimer;
@@ -188,6 +189,7 @@
 boolean hasCalibrate = false;
 void loop() {
   if (DEBUG) return;
+
   if (TOUPIE) {
     while (!digitalRead(JUMPER_PIN));
     while (digitalRead(JUMPER_PIN));
@@ -197,6 +199,20 @@
     stopMotors();
   }

+  if(TOUPIE_2) {
+    while (!digitalRead(JUMPER_PIN));
+    while (digitalRead(JUMPER_PIN));
+    setLeftSpeed(100);
+    setRightSpeed(100);
+    delay(500);
+    setLeftSpeed(-100);
+    setRightSpeed(-100);
+    delay(200);
+    setRightSpeed(100);
+    delay(1000);
+    stopMotors();
+  }
+
   if (!hasCalibrate) {
     // Turn for calibrate with potard rotation before the match
     Serial.println(getRotateDelay());
@@ -223,7 +239,7 @@
   //  stopMotors();

   // Tempo before start.
-  //delay(START_TIMER);
+  delay(START_TIMER);

   // Forward
   goForward(30, 950); // 900 before morning calibration ;)