Added bluetoothSerial

Added bluetoothSerial

Added bluetooth Serial output
Added Arduino OTA (does not seem to properly work yet)
Some small fixes.

--- esp32LightServerRGB.ino
+++ esp32LightServerRGB.ino
@@ -1,17 +1,23 @@
 #include <WiFi.h>
 #include <ESPmDNS.h>
+#include <WiFiUdp.h>
 #include <DNSServer.h>
 #include <WebServer.h>
 #include <WiFiManager.h>
 #include <WiFiMulti.h>
 #include <HTTPClient.h>
 #include <Preferences.h>
+#include <ArduinoOTA.h>
+#include "BluetoothSerial.h"
+
 Preferences preferences;

+BluetoothSerial SerialBT;
+
 // led pins
-const uint8_t pinRouge = 12;
-const uint8_t pinVerte = 14;
-const uint8_t pinBleu = 13;
+const uint8_t pinRouge = 14;
+const uint8_t pinVerte = 13;
+const uint8_t pinBleu = 12;
 //end of led pins

 // sensors stuff
@@ -37,9 +43,9 @@
 String liens = "";
 String derncoul = "";
 WebServer server(80);
-long r = 0;
-long g = 0;
-long b = 0;
+int r = 0;
+int g = 0;
+int b = 0;
 int rouge = 0;
 int vert = 0;
 int bleu = 0;
@@ -63,6 +69,8 @@
 String dernd = "0";
 int usesenseurdallas = 0;
 int usesenseurdht = 0;
+int errdallas = 0;
+int errdht = 0;
 // end of internally used vars

 // stylesheet for web pages
@@ -132,6 +140,20 @@
   }
 }

+
+//Serial output (BT+SERIAL)
+void logeur(String mess){
+  SerialBT.print(mess);
+  delay(20);
+  Serial.print(mess);
+}
+
+void logeurln(String mess){
+  SerialBT.println(mess);
+  delay(20);
+  Serial.println(mess);
+}
+
 // used to flash leds
 void flashfunk() {
   if (flashrendu <= flashfois) {
@@ -163,7 +185,7 @@
     g = vert;
     flashoufade = 0;
     flashrendu = 0;
-    Serial.println("Flash fini");
+    logeur("Flash finished");
   }
 }

@@ -211,7 +233,7 @@
 // web page to handle flashing of leds (color/delay/number of flashes)
 void handleLog() {
   if (!server.authenticate(www_username, string2char(resetpass))) {
-    Serial.println("pas/mauvais password");
+    logeurln("no/bad password");
     return server.requestAuthentication();
   }
   String addy = server.client().remoteIP().toString();
@@ -223,9 +245,7 @@
     }
   }
   server.send(200, "text/plain", contenu);
-  //Serial.println("");
-  //Serial.println(addy);
-  Serial.print(".");
+  logeur(".");
   videCoeur();
 }

@@ -238,14 +258,16 @@
   String flashnombre = server.arg("FOIS");
   flashfois = flashnombre.toInt();
   flashfois = flashfois * 2;
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("Flash");
-  Serial.println(testteu);
-  Serial.print("Delais - ");
-  Serial.println(attendF);
-  Serial.print("Fois - ");
-  Serial.println(flashfois / 2);
+  logeurln("");
+  logeurln(addy);
+  logeurln("Flash");
+  logeurln(testteu);
+  String sortie = "Delay - ";
+  sortie += attend;
+  logeurln(sortie);
+  sortie = "Times - ";
+  sortie += flashnombre;
+  logeurln(sortie);
   if (attendF == 0) {
     flashfois = 0;
   }
@@ -259,12 +281,15 @@
     preferences.putUInt("r", r);
     preferences.putUInt("g", g);
     preferences.putUInt("b", b);
-    Serial.print("Rouge = ");
-    Serial.println(r);
-    Serial.print("Vert = ");
-    Serial.println(g);
-    Serial.print("Bleu = ");
-    Serial.println(b);
+    sortie = "Red = ";
+    sortie += r;
+    logeurln(sortie);
+    sortie = "Green = ";
+    sortie += g;
+    logeurln(sortie);
+    sortie = "Blue = ";
+    sortie += b;
+    logeurln(sortie);
     dernadd = addy;
     flashoufade = 1;
     flashrendu = 0;
@@ -297,14 +322,14 @@
 // web page for flash mode
 void handlePitoune() {
   String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("Page de logs");
+  logeurln("");
+  logeurln(addy);
+  logeurln("Logs page");
   logtourne();
   logs[1] = addy;
   logs[1] += " : Page logs";
   if (!server.authenticate(www_username, string2char(resetpass))) {
-    Serial.println("pas/mauvais password");
+    logeurln("no/bad password");
     return server.requestAuthentication();
   }
   String contenu = "<!DOCTYPE html>\n\n\n";
@@ -387,21 +412,57 @@
              "</script>\n"
              "
\n";
   server.send(200, "text/html", contenu);
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("Page flash");
+  logeurln("");
+  logeurln(addy);
+  logeurln("Flashing page");
   logtourne();
   logs[1] = addy;
   logs[1] += " : Page Flash";
 }

+// web page to see # of sensor errors
+void handleDebug() {
+  String addy = server.client().remoteIP().toString();
+  logeurln("");
+  logeurln(addy);
+  logeurln("Debug");
+  logeur("#ErrDallas : ");
+  logeur(String(errdallas));
+  logeur(" - #ErrDht : ");
+  logeurln(String(errdht));
+  String contenu = "<!DOCTYPE html>\n\n\n";
+  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere Debug</title>\n"
+             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
+  contenu += css;
+  contenu += "\n\n"
+             "
\n"
+             "
Debug des senseurs
\n"
+             "Nombres d'erreurs du senseur Dallas : ";
+  contenu += errdallas;
+  contenu += "
\n"
+             "Nombres d'erreurs du senseur DHT : ";
+  contenu += errdht;
+  contenu += "

\n";
+  contenu += liens;
+  contenu += "
\n"
+             "\n";
+  server.send(200, "text/html", contenu);
+  logtourne();
+  logs[1] = addy;
+  logs[1] += " : ErrDalas=";
+  logs[1] += errdallas;
+  logs[1] += " : ErrDHT=";
+  logs[1] += errdht;
+  logs[1].replace("<", "</"); //prevent html tags in logs so hackers cant code in log page lol
+}
+
 // web page to handle leds fading
 void handleLeds() {
   String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
+  logeurln("");
+  logeurln(addy);
   String testteu = server.arg("COULEUR");
-  Serial.println(testteu);
+  logeurln(testteu);
   if (testteu != 0) {
     derncoul = testteu;
     long number = strtol( &testteu[1], NULL, 16);
@@ -410,22 +471,25 @@
     b = number & 0xFF;
     preferences.putString("derncoul", derncoul);
     if (r != rouge) {
-      Serial.print("Rouge = ");
-      Serial.println(r);
+      String sortie = "Red = ";
+      sortie += r;
+      logeurln(sortie);
       dernadd = addy;
       flashoufade = 0;
       preferences.putUInt("r", r);
     }
     if (g != vert) {
-      Serial.print("Vert = ");
-      Serial.println(g);
+      String sortie = "Green = ";
+      sortie += g;
+      logeurln(sortie);
       dernadd = addy;
       flashoufade = 0;
       preferences.putUInt("g", g);
     }
     if (b != bleu) {
-      Serial.print("Bleu = ");
-      Serial.println(b);
+      String sortie = "Blue = ";
+      sortie += b;
+      logeurln(sortie);
       dernadd = addy;
       flashoufade = 0;
       preferences.putUInt("b", b);
@@ -450,11 +514,11 @@
 void handleRoot() {
   String addy = server.client().remoteIP().toString();
   String header;
-  String userAgent;
-  if (server.hasHeader("User-Agent")) {
-    userAgent = server.header("User-Agent");
+  String referer;
+  if (server.hasHeader("Referer")) {
+    referer = server.header("Referer");
   } else {
-    userAgent = "Pas de userAgent ?";
+    referer = "Direct ?";
   }
   String contenu = "<!DOCTYPE html>\n\n\n";
   contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere soit</title>\n"
@@ -506,24 +570,24 @@
              "</script>\n"
              "
\n";
   server.send(200, "text/html", contenu);
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println(userAgent);
-  Serial.println("Page acceuil");
+  logeurln("");
+  logeurln(addy);
+  logeurln(referer);
+  logeurln("Home page");
   logtourne();
   logs[1] = addy;
   logs[1] += " : Acceuil";
-  logs[1] += " : userAgent :";
-  logs[1] += userAgent;
+  logs[1] += " : referer :";
+  logs[1] += referer;
 }

 //reset page
 void handleReset() {
   int ouireset = 0;
   String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("!!! PAGE DE RESET !!!");
+  logeurln("");
+  logeurln(addy);
+  logeurln("!!! RESET PAGE !!!");
   String testteu = server.arg("RESET");
   String passme = server.arg("PASSMOI");
   logtourne();
@@ -532,7 +596,7 @@
   logs[1] += passme;
   logs[1].replace("<", "</"); //prevent html tags in logs so hackers cant code in log page lol
   if (!server.authenticate(www_username, string2char(resetpass))) {
-    Serial.println("pas/mauvais password");
+    logeurln("no/bad password");
     return server.requestAuthentication();
   }
   if (testteu == "OUI") {
@@ -563,8 +627,8 @@
                "
!!! MAUVAIS PASSWORD !!!

\n"
                "<input type=\"submit\" class=\"button1\" value=\"Reset Wifi Network\">\n"
                "</form>\n";
-    Serial.print("MAUVAIS PASSWORD : ");
-    Serial.println(passme);
+    logeur("BAD PASSWORD : ");
+    logeurln(passme);
   } else if (ouireset == 1) {
     contenu += "
Reset Dans 10 Secondes
\n";
   }
@@ -575,12 +639,12 @@
   contenu += "\n

\n";
   server.send(200, "text/html", contenu);
   if (ouireset == 1) {
-    Serial.println("Reset dans 10 secondes");
+    logeurln("Reset in 10 seconds");
     delay(10000);
     preferences.clear();
     WiFiManager wifiManager;
     wifiManager.resetSettings();
-    Serial.println("Bip Bip... Mémoire effacée !");
+    logeurln("Bip Bip... Memory erased, what is my purpose ?");
     ESP.restart();
   }
 }
@@ -588,15 +652,15 @@
 //setup page
 void handleSetup() {
   String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("!!! PAGE DE SETUP !!!");
+  logeurln("");
+  logeurln(addy);
+  logeurln("!!! SETUP PAGE !!!");
   logtourne();
   logs[1] = addy;
   logs[1] += " : Settings !";
   logs[1].replace("<", "</"); //prevent html tags in logs so hackers cant code in log page lol
   if (!server.authenticate(www_username, string2char(resetpass))) {
-    Serial.println("pas/mauvais password");
+    logeurln("no/bad password");
     logs[1] += " Not logged in !";
     return server.requestAuthentication();
   }
@@ -628,39 +692,39 @@
     }
   }
   if (ouireset == 1) {
-    Serial.println("Réglages changé");
+    logeurln("Settings changed");
     if (noupass != resetpass) {
       preferences.putString("resetpass", noupass);
       resetpass = noupass;
-      Serial.print("NOUVEAU Password : ");
-      Serial.println(resetpass);
+      logeur("NEW Password : ");
+      logeurln(resetpass);
     }
     if (lakey != thingkey) {
       preferences.putString("thingkey", lakey);
       thingkey = lakey;
-      Serial.print("NOUVEL API KEY : ");
-      Serial.println(thingkey);
+      logeur("NEW API KEY : ");
+      logeurln(thingkey);
     }
     if (leusedallas != usesenseurdallas) {
       preferences.putUInt("usesenseurdal", leusedallas);
       usesenseurdallas = leusedallas;
       lesliens();
-      Serial.print("NOUVEAU use dallas : ");
-      Serial.println(usesenseurdallas);
+      logeur("NEW dallas setting : ");
+      logeurln(String(usesenseurdallas));
     }
     if (leusedht != usesenseurdht) {
       preferences.putUInt("usesenseurdht", leusedht);
       usesenseurdht = leusedht;
       lesliens();
-      Serial.print("NOUVEAU use dht : ");
-      Serial.println(usesenseurdht);
+      logeur("NEW dht setting : ");
+      logeurln(String(usesenseurdht));
     }
     if (lechan != thingchanel) {
       preferences.putString("thingchanel", lechan);
       thingchanel = lechan;
       lesliens();
-      Serial.print("NOUVEAU channel : ");
-      Serial.println(thingchanel);
+      logeur("NEW channel : ");
+      logeurln(thingchanel);
     }
   }
   String contenu = "<!DOCTYPE html>\n\n\n";
@@ -723,7 +787,7 @@
                "<input type=\"submit\" class=\"button1\" value=\"Changer\">\n"
                "</form>\n";
     if (ouireset == 3) {
-      Serial.println("CHAMP VIDE");
+      logeurln("EMPTY FIELD");
     }
   } else if (ouireset == 1) {
     contenu += "
Réglages changés !
\n";
@@ -752,15 +816,15 @@
 void handleNotFound() {
   String header;
   String addy = server.client().remoteIP().toString();
-  Serial.println("");
+  logeurln("");
   String userAgent;
-  Serial.println(addy);
+  logeurln(addy);
   if (server.hasHeader("User-Agent")) {
     userAgent = server.header("User-Agent");
   } else {
     userAgent = "Pas de userAgent ?";
   }
-  Serial.println(userAgent);
+  logeurln(userAgent);
   String htmlmessage = "<!DOCTYPE html>\n\n\n";
   htmlmessage += "<meta charset=\"UTF-8\" />\n<title>404 Not found</title>\n"
                  "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
@@ -797,7 +861,7 @@
     argsL += ": " + server.argName(i) + "=" + server.arg(i) + " ";
     message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
   }
-  Serial.print(message);
+  logeur(message);
   logtourne();
   logs[1] = addy;
   logs[1] += " : 404 : URI=";
@@ -817,8 +881,8 @@
     HTTPClient http;
     String webadd = "http://api.thingspeak.com/update?key=";
     webadd += thingkey;
-    Serial.println("");
-    Serial.print("Envoi de température et humidité: ");
+    logeurln("");
+    logeur("Sending temp and humidity readings: ");
     int enweille = 0;
     if (usesenseurdallas == 1) {
       //dallas
@@ -826,42 +890,44 @@
       float thetemp = sensors.getTempCByIndex(0);
       char buffer[10];
       String tempC = dtostrf(thetemp, 5, 2, buffer);
-      delay(400);
+      //      delay(400);
       if (tempC != "-127.00") {
         if (tempC != "85.00") {
-          Serial.print(tempC);
+          logeur(tempC);
           if (usesenseurdht == 1) {
-            Serial.print(" - ");
+            logeur(" - ");
           }
           webadd += "&field1=";
           webadd += tempC;
           enweille = 1;
           dernd = tempC;
         } else {
-          Serial.println("Erreure du senseur dallas 85 !");
+          logeurln("Dallas sensor error 85 !");
+          errdallas++;
           if (dernd != "0") {
             tempC = dernd;
             webadd += "&field1=";
             webadd += tempC;
             enweille = 1;
-            Serial.print(tempC);
+            logeur(tempC);
             if (usesenseurdht == 1) {
-              Serial.print(" - ");
+              logeur(" - ");
             }
           } else {
             enweille = 0;
           }
         }
       } else {
-        Serial.println("Erreure du senseur dallas -127 !");
+        logeurln("Dallas sensor error -127 !");
+        errdallas++;
         if (dernd != "0") {
           tempC = dernd;
           webadd += "&field1=";
           webadd += tempC;
           enweille = 1;
-          Serial.print(tempC);
+          logeur(tempC);
           if (usesenseurdht == 1) {
-            Serial.print(" - ");
+            logeur(" - ");
           }
         } else {
           enweille = 0;
@@ -874,19 +940,20 @@
       float h = 0;
       int err = SimpleDHTErrSuccess;
       if ((err = dht22.read2(pinDHT22, &t, &h, NULL)) != SimpleDHTErrSuccess) {
-        Serial.println("");
-        Serial.print("Erreure de lecture DHT, err=");
-        Serial.println(err);
+        errdht++;
+        logeurln("");
+        logeur("DHT sensor error, err=");
+        logeurln(String(err));
         if (dernh != 0) {
           h = dernh;
           t = dernt;
           webadd += "&field2=";
           webadd += h;
-          Serial.print(h);
+          logeur(String(h));
           webadd += "&field3=";
           webadd += t;
-          Serial.print(" - ");
-          Serial.print(t);
+          logeur(" - ");
+          logeur(String(t));
           enweille = 1;
           dernt = t;
           dernh = h;
@@ -894,47 +961,49 @@
       } else {
         webadd += "&field2=";
         webadd += h;
-        Serial.print(h);
+        String sortie;
+        sortie += h;
         webadd += "&field3=";
         webadd += t;
-        Serial.print(" - ");
-        Serial.print(t);
+        sortie += " - ";
+        sortie += t;
+        logeur(sortie);
         enweille = 1;
         dernt = t;
         dernh = h;
       }
     }
     if (enweille == 1) {
-      Serial.println("");
+      logeurln("");
       http.begin(webadd);
       int httpCode = http.GET();
       if (httpCode > 0) {
-        Serial.println("Envoit réussit !");
+        logeurln("Sending successfull !");
         tstrouteur = 0;
       } else {
         if (tstrouteur == 10) {
-          Serial.println("10 Erreur envoit ! REBOOT !");
+          logeurln("10 errors while sending ! REBOOT !");
           ESP.restart();
         } else {
-          Serial.println("!!! Erreur envoit !!!");
+          logeurln("!!! Error while sending !!!");
           tstrouteur++;
         }
       }
       http.end();   //Close connection
     } else {
-      Serial.println("Envois pas car erreur de senseurs !");
+      logeurln("Not sending due to sensors error !");
     }
   } else {
-    Serial.println("Pas de API KEY donc pas d'envoi");
+    logeurln("Not sending since there is no API key set !");
   }
 }

 // web page for showing sensors data
 void handleTemp() {
   String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("Page température");
+  logeurln("");
+  logeurln(addy);
+  logeurln("Temperature page");
   float latemp;
   float t;
   float h;
@@ -948,26 +1017,28 @@
       if (tempC != "85.00") {
         dernd = tempC;
       } else {
-        Serial.println("Erreure du senseur dallas 85 !");
+        errdallas++;
+        logeurln("Dallas sensor error 85 !");
         if (dernd != "0") {
           tempC = dernd;
         }
       }
     } else {
-      Serial.println("Erreure du senseur dallas -127 !");
+      logeurln("Dallas sensor error -127 !");
+      errdallas++;
       if (dernd != "0") {
         tempC = dernd;
       }
     }
-    delay(250);
   }
   if (usesenseurdht == 1) {
     t = 0;
     h = 0;
     int err = SimpleDHTErrSuccess;
     if ((err = dht22.read2(pinDHT22, &t, &h, NULL)) != SimpleDHTErrSuccess) {
-      Serial.print("Erreure de lecture DHT, err=");
-      Serial.println(err);
+      errdht++;
+      logeur("DHT sensor error, err=");
+      logeurln(String(err));
       t = dernt;
       h = dernh;
     }
@@ -1023,14 +1094,20 @@
   contenu += "\n

\n";
   server.send(200, "text/html", contenu);
   if (usesenseurdallas == 1) {
-    Serial.print("Température : ");
-    Serial.println(latemp);
+    String sortie = "Temp : ";
+    sortie += latemp;
+    sortie += "C";
+    logeurln(sortie);
   }
   if (usesenseurdht == 1) {
-    Serial.print("Temp2 : ");
-    Serial.println(t);
-    Serial.print("Humidité : ");
-    Serial.println(h);
+    String sortie = "Temp2 : ";
+    sortie += t;
+    sortie += "C";
+    logeurln(sortie);
+    sortie = "Humidity : ";
+    sortie += h;
+    sortie += "%";
+    logeurln(sortie);
   }
   logtourne();
   logs[1] = addy;
@@ -1070,6 +1147,7 @@
     logs[i] = "♥ vide";
   }
 }
+
 void lumiereloop() {
   unsigned long currentMillis = millis();
   if (flashoufade == 1) {
@@ -1109,15 +1187,16 @@
   while (1) {
     if ( r != rouge || g != vert || b != bleu || flashoufade != 0 ) {
       lumiereloop();
-      vTaskDelay( 3 / portTICK_PERIOD_MS ); // wait / yield time to other tasks
+      vTaskDelay( 10 / portTICK_PERIOD_MS ); // wait / yield time to other tasks
     } else {
-      vTaskDelay( 50 / portTICK_PERIOD_MS ); // wait / yield time to other tasks
+      vTaskDelay( 100 / portTICK_PERIOD_MS ); // wait / yield time to other tasks
     }
   }
 }

 void setup() {
   Serial.begin(115200);
+  SerialBT.begin("lumiere"); //Bluetooth device name
   preferences.begin("lumiere", false);
   videCoeur();
   ledcAttachPin(pinRouge, 1);
@@ -1157,7 +1236,7 @@
     int marchetu = 1;
     do { // 5 retry
       ereur++;
-      Serial.print("Erreur senseur 0 essai #");
+      Serial.print("Sensor error try #");
       Serial.println(ereur);
       delay(200);
       if (sensors.getAddress(insideThermometer, 0)) {
@@ -1166,10 +1245,10 @@
       }
     } while (ereur < 5);
     if (marchetu != 0) {
-      Serial.println("Erreure senseurs 0 non fonctionnel !");
-    }
-  }
-  sensors.setResolution(insideThermometer, 12);// 9 ou 12 9 plus rapide mais moin préçis
+      Serial.println("Error ! Sensor not working !");
+    }
+  }
+  sensors.setResolution(insideThermometer, 12);// 9 ou 12 9 plus rapide mais moin prÃ©Ã§is
   MDNS.begin("lumiere");
   server.on("/", handleRoot);
   server.on("/setup", handleSetup);
@@ -1179,10 +1258,11 @@
   server.on("/logs", handleLog);
   server.on("/log", handlePitoune);
   server.on("/temp", handleTemp);
+  server.on("/debug", handleDebug);
   server.on("/party", handleClignote);
   server.on("/version", []() {
     String addy = server.client().remoteIP().toString();
-    server.send(200, "text/html", "V2.9, Steve Olmstead sansillusion@gmail.com\n\n

"
+    server.send(200, "text/html", "V3.0, Steve Olmstead sansillusion@gmail.com\n\n

"
                 "Added fader function\nRemoved connection watchdog (better have good signal)\n
"
                 "Removed mDns (did not work anyway)\n\n

"
                 "Added smoother fading\n\n

"
@@ -1216,25 +1296,54 @@
                 "Added User-Agernt information in logging and serial output of / and 404 not found page\n
"
                 "Fixed Bonjour service support you can now use ( http://lumiere.local ) if you have Bonjour V3 installed\n

"
                 "Moved fading to it's own core and loop
\n"
-                "Cleaned CSS and changed color selector to match buttons
\n" + liens);
-    Serial.println("");
-    Serial.println(addy);
-    Serial.println("Page de Version");
+                "Cleaned CSS and changed color selector to match buttons
\n\n"
+                "Added ArduinoOTA support for easy updates
\n" + liens);
+    logeurln("");
+    logeurln(addy);
+    logeurln("Version page");
     logtourne();
     logs[1] = addy;
     logs[1] += " : Page de version";
   });
   server.onNotFound(handleNotFound);
-  const char * headerkeys[] = {"User-Agent"} ;//peut ajouter autres si besoin eg {"User-Agent", "Cookie"}
+  const char * headerkeys[] = {"User-Agent", "Referer"} ;//peut ajouter autres si besoin eg {"User-Agent", "Cookie"}
   size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*);
   server.collectHeaders(headerkeys, headerkeyssize );
   server.begin();
-  Serial.println("Serveur web démaré");
+  Serial.println("Web server started visit http://lumiere.local");
   MDNS.addService("_http", "_tcp", 80);
+  ArduinoOTA.setHostname("lumiere");
+  ArduinoOTA.setPasswordHash("password");
+  ArduinoOTA
+  .onStart([]() {
+    String type;
+    if (ArduinoOTA.getCommand() == U_FLASH)
+      type = "sketch";
+    else // U_SPIFFS
+      type = "filesystem";
+
+    // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
+    Serial.println("Start updating " + type);
+  })
+  .onEnd([]() {
+    Serial.println("\nEnd");
+  })
+  .onProgress([](unsigned int progress, unsigned int total) {
+    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
+  })
+  .onError([](ota_error_t error) {
+    Serial.printf("Error[%u]: ", error);
+    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
+    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
+    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
+    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
+    else if (error == OTA_END_ERROR) Serial.println("End Failed");
+  });
+  ArduinoOTA.begin();
+  delay(100);
 }

 void loop() {
-  server.handleClient();
   unsigned long currentMillis = millis();
   if (currentMillis - previousMillis >= interval) {
     previousMillis = currentMillis;
@@ -1249,4 +1358,8 @@
       latemp();
     }
   }
-}
+  ArduinoOTA.handle();
+  vTaskDelay( 100 / portTICK_PERIOD_MS ); // wait / yield time to other tasks
+  server.handleClient();
+}
+


Added some more configuration options

Added some more configuration options

I added configuration option for smoothing transition of colors and for brighten green and purple colors.

--- esp8266/cheerlights.ino
+++ esp8266/cheerlights.ino
@@ -41,6 +41,9 @@
 // Min and max update frequency
 #define MIN_UPDATE_FREQUENCY    5
 #define MAX_UPDATE_FREQUENCY 7200
+
+// Configuration color intensity (to 255)
+#define CONFIG_COLOR_INTENSITY 50

 // EEPROM config structure
@@ -54,6 +57,7 @@
   unsigned long tsChannel;
   int tsField;
   bool smoothUpdate;
+  bool brightenColors;
 };

 // Pixel color
@@ -97,7 +101,7 @@

   // Setup FastLED
   FastLED.addLeds<NEOPIXEL, LED_PIN> (&led, 1).setCorrection (TypicalSMD5050);
-  setColor (100, 0, 0);
+  setColor (CONFIG_COLOR_INTENSITY, 0, 0);

   // Read config
   EEPROM.begin (sizeof (ClConfiguration));
@@ -113,6 +117,7 @@
     config.tsChannel = DEFAULT_TS_CHANNEL;
     config.tsField = DEFAULT_TS_FIELD;
     config.smoothUpdate = true;
+    config.brightenColors = false;
   }

   // Run configuration AP
@@ -132,7 +137,7 @@
   lastInteractionTime = millis();

   delay (500);
-  setColor (0, 100, 0);
+  setColor (0, CONFIG_COLOR_INTENSITY, 0);
 }

 /**
@@ -172,6 +177,7 @@
   resp += "
AP Password:	<input type=\"password\" name=\"password\" value=\"" + String(config.password) + "\" maxlength=\"48\">
";
   resp += "
Update frequency:	<input type=\"text\" name=\"sampleFrequency\" value=\"" + String(config.updateFrequency) + "\">
";
   resp += "
Smooth update:	<input type=\"checkbox\" name=\"smoothUpdate\" " + (config.smoothUpdate ? String("checked") : String("")) + ">
";
+  resp += "
Brighten colors:	<input type=\"checkbox\" name=\"brightenColors\" " + (config.brightenColors ? String("checked") : String("")) + ">
";
   resp += "
ThingSpeak host:	<input type=\"text\" name=\"tsHost\" value=\"" + String(config.tsHost) + "\" maxlength=\"40\">
";
   resp += "
ThingSpeak port:	<input type=\"text\" name=\"tsPort\" value=\"" + String(config.tsPort) + "\">
";
   resp += "
ThingSpeak channel:	<input type=\"text\" name=\"tsChannel\" value=\"" + String(config.tsChannel) + "\">
";
@@ -212,7 +218,8 @@
   unsigned int tsPort = atoi (server->arg ("tsPort").c_str());
   unsigned long tsChannel = atol (server->arg ("tsChannel").c_str());
   int tsField = atoi (server->arg ("tsField").c_str());
-  bool smoothUpdate = server->arg ("smoothUpdate") == String("1");
+  bool smoothUpdate = server->arg ("smoothUpdate") == String("on");
+  bool brightenColors = server->arg ("brightenColors") == String("on");

   if (apName.length() > 1) {
     updateConfigKey (config.apName, 24, apName);
@@ -223,6 +230,7 @@
     config.tsChannel = tsChannel;
     config.tsField = tsField;
     config.smoothUpdate = smoothUpdate;
+    config.brightenColors = brightenColors;

     // store configuration
     EEPROM.begin (sizeof (ClConfiguration));
@@ -265,13 +273,13 @@
   delay (5000);
   while (WiFi.status() != WL_CONNECTED) {
     yield();
-    setColor (100, 0, 100);
+    setColor (CONFIG_COLOR_INTENSITY, 0, CONFIG_COLOR_INTENSITY);
     delay(500);
-    setColor (100, 0, 0);
+    setColor (CONFIG_COLOR_INTENSITY, 0, 0);
     delay (500);
     Serial.print (".");
   }
-  setColor (0, 100, 0);
+  setColor (0, CONFIG_COLOR_INTENSITY, 0);
   delay (500);
   Serial.println();
   Serial.println ("WiFi connected...");
@@ -303,6 +311,28 @@
 }

 /**
+ * Method brighten color.
+ *
+ * @param color original color.
+ * @return unsigned long new color.
+*/
+unsigned long brightenColor (unsigned long color) {
+  unsigned long result = color;
+
+  switch (color) {
+    case 0x008000 :
+      result = 0x00FF00UL;
+    break;
+    case 0x800080 :
+      result = 0xFF00FFUL;
+    break;
+    default : break;
+  }
+
+  return result;
+}
+
+/**
  * Main loop.
 */
 void thingSpeakLoop() {
@@ -356,7 +386,11 @@

               Serial.print ("Readed color: ");
               Serial.println (color, HEX);
-
+
+              if (config.brightenColors) {
+                color = brightenColor (color);
+              }
+
               reqPixelColor.red =   (color & 0xFF0000) >> 16;
               reqPixelColor.green = (color & 0x00FF00) >>  8;
               reqPixelColor.blue =  (color & 0x0000FF);
@@ -418,9 +452,9 @@
         state = !state;

         if (state) {
-          setColor (100, 100, 0);
+          setColor (CONFIG_COLOR_INTENSITY, CONFIG_COLOR_INTENSITY, 0);
         } else {
-          setColor (0, 100, 100);
+          setColor (0, CONFIG_COLOR_INTENSITY, CONFIG_COLOR_INTENSITY);
         }

         lastUpdate = curMillis;


complie infos on setup

complie infos on setup

--- esp8266_time_analog.ino
+++ esp8266_time_analog.ino
@@ -42,10 +42,7 @@
   Serial.begin(115200);
 #endif

-  DebugPrintln(" ");
-  DebugPrint(__DATE__);
-  DebugPrint(__TIME__);
-  DebugPrintln(__FILE__);
+  DebugPrintln("\n" + String(__DATE__) + ", " + String(__TIME__) + " " + String(__FILE__));

   ClockA.init();


[MCP23017]: Use class to blink LED's and scan a button

--- Mcp23017/mcp23017/mcp23017.ino
+++ Mcp23017/mcp23017/mcp23017.ino
@@ -1,4 +1,5 @@
 #include <Wire.h>
+

 #define PCA9548ADDR 0x70

@@ -11,13 +12,75 @@
 #define I2C_CHANNEL_SDSC6 0x40
 #define I2C_CHANNEL_SDSC7 0x80

-int ledState = 0;
-int result = 0;
+byte result = 0;
+byte state = 0;
+byte oldbutton = 0;

+class Flasher {
+private:
+  long OnTime;
+  long OffTime;
+  int ledState;
+  unsigned long previousMillis;
+  int channel;
+  int ledPin;
+
+public:
+  static int mask;
+
+
+  Flasher(int ledPin, long on, long off, int channel) {
+    this->ledPin = ledPin;
+    this->OnTime = on;
+    this->OffTime = off;
+    this->ledState = LOW;
+    this->previousMillis = 0;
+    this->channel = channel;
+  }
+
+  void Update() {
+    unsigned long currentMillis = millis();
+
+    selectI2cChannels(channel);
+    Wire.beginTransmission(0x20);
+
+    if ((ledState == HIGH) && (currentMillis - previousMillis) >= OnTime) {
+      previousMillis = currentMillis;
+      ledState = LOW;
+      mask = mask & ~ledPin;
+      Wire.write(0x13);
+      Wire.write(mask);
+    } else if ((ledState == LOW) && (currentMillis - previousMillis) >= OffTime) {
+      previousMillis = currentMillis;
+      ledState = HIGH;
+      mask = mask | ledPin;
+      Wire.write(0x13);
+      Wire.write(mask);
+    }
+
+    Wire.endTransmission();
+  }
+
+private:
+  void selectI2cChannels(int channels)
+  {
+    Wire.beginTransmission(PCA9548ADDR);
+    Wire.write(channels);
+    Wire.endTransmission();
+  }
+};
+
+Flasher led1(0x01, 1000, 4000, I2C_CHANNEL_SDSC3);
+Flasher led2(0x02, 350, 350, I2C_CHANNEL_SDSC3);
+Flasher led3(0x04, 100, 1000, I2C_CHANNEL_SDSC3);
+Flasher led4(0x08, 30, 300, I2C_CHANNEL_SDSC3);
+
+int Flasher::mask = 0x00;

 void setup() {
   // put your setup code here, to run once:
   delay(2000);
+

   Wire.begin();

@@ -33,11 +96,6 @@
   Wire.write(0x01);
   Wire.write(0x00);
   Wire.endTransmission();
-//  Wire.beginTransmission(0x20);
-//  //Write '1' to GPB0-GPB3
-//  Wire.write(0x13);
-//  Wire.write(0x0f);
-//  Wire.endTransmission();

   //select SDA0 / SCL0
   selectI2cChannels(I2C_CHANNEL_SDSC0);
@@ -51,125 +109,35 @@
   Wire.write(0x01);
   Wire.write(0xFE);
   Wire.endTransmission();
-  Wire.beginTransmission(0x20);
-  Wire.write(0x13);
-  Wire.write(0x01);
-  Wire.endTransmission();
 }

 void loop() {
   // put your main code here, to run repeatedly:
-  selectI2cChannels(I2C_CHANNEL_SDSC3);
-  Wire.beginTransmission(0x20);
-  Wire.write(0x13);
-  Wire.write(0x00);
-  Wire.endTransmission();
-  delay(100);
-
+  led1.Update();
+  led2.Update();
+  led3.Update();
+  led4.Update();
+
   selectI2cChannels(I2C_CHANNEL_SDSC0);
   Wire.beginTransmission(0x20);
   Wire.write(0x13);
   Wire.endTransmission();
   Wire.requestFrom(0x20, 1);
-  result = Wire.read();
-  if (result & 0x02) {
+  result = (Wire.read() & 0x02);
+  if (result && !oldbutton) {
+    if (state == 0) {
+      state = 1;
+    } else {
+      state = 0;
+    }
+    oldbutton = 1;
     Wire.beginTransmission(0x20);
     Wire.write(0x13);
-    Wire.write(0x00);
+    Wire.write(state);
     Wire.endTransmission();
-  } else {
-    Wire.beginTransmission(0x20);
-    Wire.write(0x13);
-    Wire.write(0x01);
-    Wire.endTransmission();
-    delay(100);
-    Wire.beginTransmission(0x20);
-    Wire.write(0x13);
-    Wire.write(0x00);
-    Wire.endTransmission();
+  } else if (!result && oldbutton) {
+    oldbutton = 0;
   }
-
-//  Wire.beginTransmission(0x20);
-//  Wire.write(0x13);
-//  if (ledState == 0x01) {
-//    ledState = 0x00;
-//  } else {
-//    ledState = 0x01;
-//  }
-//  Wire.write(ledState);
-//  Wire.endTransmission();
-//
-  selectI2cChannels(I2C_CHANNEL_SDSC3);
-  Wire.beginTransmission(0x20);
-  Wire.write(0x13);
-  Wire.write(0x01);
-  Wire.endTransmission();
-  delay(100);
-
-//  selectI2cChannels(I2C_CHANNEL_SDSC0);
-//  Wire.beginTransmission(0x20);
-//  Wire.write(0x13);
-//  if (ledState == 0x01) {
-//    ledState = 0x00;
-//  } else {
-//    ledState = 0x01;
-//  }
-//  Wire.write(ledState);
-//  Wire.endTransmission();
-
-  selectI2cChannels(I2C_CHANNEL_SDSC3);
-  Wire.beginTransmission(0x20);
-  Wire.write(0x13);
-  Wire.write(0x02);
-  Wire.endTransmission();
-  delay(100);
-
-//  selectI2cChannels(I2C_CHANNEL_SDSC0);
-//  Wire.beginTransmission(0x20);
-//  Wire.write(0x13);
-//  if (ledState == 0x01) {
-//    ledState = 0x00;
-//  } else {
-//    ledState = 0x01;
-//  }
-//  Wire.write(ledState);
-//  Wire.endTransmission();
-//
-  selectI2cChannels(I2C_CHANNEL_SDSC3);
-  Wire.beginTransmission(0x20);
-  Wire.write(0x13);
-  Wire.write(0x04);
-  Wire.endTransmission();
-  delay(100);
-
-//  selectI2cChannels(I2C_CHANNEL_SDSC0);
-//  Wire.beginTransmission(0x20);
-//  Wire.write(0x13);
-//  if (ledState == 0x01) {
-//    ledState = 0x00;
-//  } else {
-//    ledState = 0x01;
-//  }
-//  Wire.write(ledState);
-//  Wire.endTransmission();
-//
-  selectI2cChannels(I2C_CHANNEL_SDSC3);
-  Wire.beginTransmission(0x20);
-  Wire.write(0x13);
-  Wire.write(0x08);
-  Wire.endTransmission();
-  delay(100);
-
-//  selectI2cChannels(I2C_CHANNEL_SDSC0);
-//  Wire.beginTransmission(0x20);
-//  Wire.write(0x13);
-//  if (ledState == 0x01) {
-//    ledState = 0x00;
-//  } else {
-//    ledState = 0x01;
-//  }
-//  Wire.write(ledState);
-//  Wire.endTransmission();
 }

 void selectI2cChannels(int channels)


Add files via upload

Add files via upload

iDON"T_basic_webserver either has the AC power connected to the doorbell or disconnected via a relay on pin 16. While it meets the basic goal, it does not have any features.


Add RTC - DS3231

Add RTC - DS3231

--- meteo_lcd/meteo_lcd.ino
+++ meteo_lcd/meteo_lcd.ino
@@ -7,6 +7,7 @@
 #include <Adafruit_BMP085.h> // Pressure
 #include <meteo_common.h> // Common function for meteo
 #include <LiquidCrystal_I2C.h> // LCD display
+#include <DS3231.h>

 /*
 Used Arduino ports:
@@ -44,7 +45,7 @@
 |Out:-20.5°C  100% RH|
 |Pressure:    Err hPa|
 |Pressure: 1013.9 hPa|
-|12:34:56  12.12.2017|
+|17:34:59  31.12.2017|
 +--------------------+
  */

@@ -71,14 +72,81 @@
 LiquidCrystal_I2C lcd(0x27, 20, 4);  // set the LCD address to 0x27 for a 20 chars and 4 line display

-// TODO: Add RTC
+// Real-time clock
+DS3231 rtc;

 // Delay
 const int32_t sleep_time = 1000; // 1000ms

-
 // Error value
 const int32_t err_val = 200000;
+
+
+/* returns time-date string via param from rtc.
+ * rtc should be at least 21 bytes long.
+ */
+void print_time_string(unsigned row)
+{
+    bool tmp1 = false;
+    bool tmp2 = false;
+
+    char str[21];
+    byte ret;
+
+    /*
+     * 01234567890123456789
+     * 17:34:59  31.12.2017
+     */
+
+    // hour
+    ret = rtc.getHour(tmp1, tmp2);
+    str[0] = ret / 10;
+    str[1] = ret % 10;
+
+    str[2] = ':';
+
+    // minute
+    ret = rtc.getMinute();
+    str[3] = ret / 10;
+    str[4] = ret % 10;
+
+    str[5] = ':';
+
+    // second
+    ret = rtc.getSecond();
+    str[6] = ret / 10;
+    str[7] = ret % 10;
+
+    str[8] = ' ';
+    str[9] = ' ';
+
+    // day
+    ret = rtc.getDate();
+    str[10] = ret / 10;
+    str[11] = ret % 10;
+
+    str[12] = '.';
+
+    // month
+    ret = rtc.getMonth(tmp1);
+    str[13] = ret / 10;
+    str[14] = ret % 10;
+
+    str[15] = '.';
+
+    // year - only last two digits
+    ret = rtc.getYear();
+    str[16] = '2';
+    str[17] = '0';
+    str[18] = ret / 10;
+    str[19] = ret % 10;
+
+    // end of string
+    str[20] = '\0';
+
+    lcd.setCursor(0, row);
+    lcd.print(str);
+}

 void setup ()
 {
@@ -87,6 +155,13 @@
     Serial.begin(9600);
     LOGLN("Setup begin");
     #endif
+
+    // Configure RTC
+    rtc.enableOscillator(true /* ON */,
+                        false /* disabled if batery-only powered */,
+                        0 /* freq: 1Hz */);
+    rtc.enable32kHz(false);
+    rtc.setClockMode(false); /* set to 24-hour mode */

     // LCD
     lcd.init();
@@ -154,7 +229,7 @@
 |Out:-20.5°C  100% RH|
 |Pressure:    Err hPa|
 |Pressure: 1013.9 hPa|
-|12:34:56  12.12.2017|
+|17:34:59  31.12.2017|
 +--------------------+
  */

@@ -261,6 +336,7 @@

     draw_template();
     fill_data(temp_in, temp_out, humid_in, humid_out, pressure);
+    print_time_string(3 /* 4th row */);

     LOG("delay "); LOGLN(sleep_time);


change some constants names

change some constants names

--- first_one/first_one.ino
+++ first_one/first_one.ino
@@ -33,37 +33,40 @@
 bool SYS_DEBUG = true;

 #define MORSE_UNIT_TIME SLEEP_250MS
-#define NUM_LEDS 9
-#define LDR_PIN A0
-
-unsigned long arTime = millis();
-unsigned long reset = millis();
+#define NUM_LEDS        9
+#define LDR_PIN         A0
+#define NUM_CYCLES      9
+#define MIN_VOLTAGE     3200
+#define MAX_VOLTAGE     4500
+#define LDR_MIDNIGHT    60
+#define MAX_BIN_COUNT   512
+
+
+unsigned long arTime         = millis();
+unsigned long reset          = millis();
 unsigned int TIME_MULTIPLIER = 1; // x1
-unsigned int WAIT = 150*TIME_MULTIPLIER;
-unsigned int waitLynch = 33*TIME_MULTIPLIER;
-unsigned int actualPin = 2;
-
-int LDR = 0;
-long voltage = 0;
-unsigned int minVoltage = 3200;
-unsigned int ldrMinLight = 60;
+unsigned int WAIT            = 150*TIME_MULTIPLIER;
+unsigned int waitLynch       = 33*TIME_MULTIPLIER;
+unsigned int actualPin       = 2;
+
+int LDR            = 0;
+long voltage       = 0;
 bool weAreTheNight = false;

-unsigned int binaryCounter = 0; // 9 bits, 0 - 512
-unsigned int morseCounter = 1;  // 1 - 9
-unsigned int lynchCounter = 1;  // 1 - 18
+unsigned int binaryCounter  = 0; // 9 bits, 0 - 512
+unsigned int morseCounter   = 1;  // 1 - 9
+unsigned int lynchCounter   = 1;  // 1 - 18
 unsigned int batteryCounter = 1;  // 1 - 9
-unsigned int cycles = 9;
-unsigned int actualCycle = 1;
-unsigned int actualStep = 1;  // 1 - 5
-bool endCycle = false;
-bool lynchON = false;
-unsigned int lynchFlicks[] = { 33,66,99,101,106,109,123,132,161 };
-
-String message = encode( "PWNED " );
-
-unsigned int ledPins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
-unsigned int ledPinsRAND[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+unsigned int actualCycle    = 1;
+unsigned int actualStep     = 1;  // 1 - 5
+bool endCycle               = false;
+bool lynchON                = false;
+unsigned int lynchFlicks[]  = { 33,66,99,101,106,109,123,132,161 };
+
+String message              = encode( "PWNED " );
+
+unsigned int ledPins[]      = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+unsigned int ledPinsRAND[]  = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 /////////////////////////////////////////////////////////
@@ -100,7 +103,7 @@

     if(HW_DEBUG){
       // Hardware Check
-      if(voltage < minVoltage){
+      if(voltage < MIN_VOLTAGE){
         if(DEBUG){
           Serial.println("Low battery");
         }
@@ -114,7 +117,7 @@
         }
       }
     }else{
-      if(voltage >= minVoltage && weAreTheNight){
+      if(voltage >= MIN_VOLTAGE && weAreTheNight){
         // We're ON
         runCycle();
       }else{
@@ -145,7 +148,7 @@
   if(endCycle){
     endCycle = false;
     randomSeed(analogRead(1));
-    if(actualCycle < cycles){
+    if(actualCycle < NUM_CYCLES){
       actualCycle++;
     }else{
       actualCycle = 1;
@@ -207,7 +210,7 @@
  */
 void batteryMeter(){
   // min 3200, max 4500
-  int bl = map((int)voltage,minVoltage,4500,0,8);
+  int bl = map((int)voltage,MIN_VOLTAGE,MAX_VOLTAGE,0,NUM_LEDS);
   if(DEBUG){
     Serial.println(bl);
   }
@@ -221,7 +224,7 @@

   if(arTime-reset > WAIT){
     reset = millis();
-    if(batteryCounter < cycles){
+    if(batteryCounter < NUM_CYCLES){
       batteryCounter++;
     }else{
       endCycle = true;
@@ -261,7 +264,7 @@

   if(arTime-reset > WAIT){
     reset = millis();
-    if(binaryCounter < 512){
+    if(binaryCounter < MAX_BIN_COUNT){
       binaryCounter++;
     }else{
       endCycle = true;
@@ -316,7 +319,7 @@
   if(arTime-reset > waitLynch){
     reset = millis();
     lynchON = !lynchON;
-    if(lynchCounter < cycles*2){
+    if(lynchCounter < NUM_CYCLES*2){
       lynchCounter++;
     }else{
       endCycle = true;
@@ -356,7 +359,7 @@
     }
   }

-  if(morseCounter < cycles){
+  if(morseCounter < NUM_CYCLES){
     morseCounter++;
   }else{
     endCycle = true;
@@ -374,7 +377,7 @@
 void readLDR(){
   LDR = analogRead(LDR_PIN);

-  if(LDR < ldrMinLight){
+  if(LDR < LDR_MIDNIGHT){
     weAreTheNight = true;
   }else{
     weAreTheNight = false;


Shorten registration/refresh sound lenght

--- frontdesk/frontdesk.ino
+++ frontdesk/frontdesk.ino
@@ -90,7 +90,7 @@
 		// If tag is removed, go back to scan state
 		if (!isValidResponse) {
 			pollCounter++;
-			if (pollCounter == pollTimeout) {
+			if (pollCounter == 3) {
 				pollCounter = 0;
 				state = 0;
 			}
@@ -215,7 +215,7 @@
 }

 void playUnderground() {
-	int notes[] = { 131, 262, 110, 220, 117, 233 };
+	int notes[] = { 131, 262 };
 	int numNotes = sizeof(notes) / sizeof(notes[0]);

 	for (int i = 0; i < numNotes; i++) {
@@ -235,20 +235,6 @@
 		noTone(speakerPin);
 		delay(150);
 	}
-}
-
-void redBeat(int minimumLevel, int peak) {
-	currentLevel >= 2*peak - minimumLevel ? currentLevel = minimumLevel : currentLevel += 2;
-
-	for (int i = 0; i < LED.numPixels(); i++) {
-		if (currentLevel < peak) {
-			LED.setPixelColor(i, LED.Color(currentLevel, 0, 0));
-		}
-		else {
-			LED.setPixelColor(i, LED.Color(2*peak - currentLevel, 0, 0));
-		}
-	}
-	LED.show();
 }

 void green() {


added send and receive function

added send and receive function

--- client/client.ino
+++ client/client.ino
@@ -20,14 +20,18 @@
 #include <MirfHardwareSpiDriver.h>

 struct Message {
-  uint8_t id;
+  byte id;
   //uint8_t destination;
   //uint8_t source;
-  uint8_t data;
-  uint8_t checksum[2];
+  byte data;
+  byte checksum[2];
 };

-Message message;
+Message tx_message;
+Message rx_message;
+/* Initialy our recieving status is 0 and finished is false */
+uint8_t rx_stat = 0;
+volatile bool rx_finished = false;

 void setup() {
   Serial.begin( 9600 );
@@ -79,41 +83,53 @@
   return 0;
 }

-int sendPacket() {
-  /* Timeout for receiving */
-  long time = millis();
+int receivePacket() {
+  /* when nothing was received */
+  if ( !Mirf.dataReady() ) return 1;
+  byte b;
+  Mirf.getData( (byte *) b );
+  /* according to our status we save the received byte and go to next state */
+  switch ( rx_stat ) {
+    case 0: rx_message.id = b; rx_stat = 1; break;
+    case 1: rx_message.data = b; rx_stat = 2; break;
+    case 2: rx_message.checksum[0] = b; rx_stat = 3; break;
+    case 3: rx_message.checksum[1] = b; rx_finished = true; rx_stat = 0; break;
+    default: Serial.println( "Receiving status was changed illegaly!" ); break;
+  }
+  return 0;
+}
+
+int transmitPacket() {
+  /* Send the data packet */
+  Mirf.send( (byte *) tx_message.id );
+  Mirf.send( (byte *) tx_message.data );
+  Mirf.send( (byte *) tx_message.checksum[0] );
+  Mirf.send( (byte *) tx_message.checksum[1] );

-  /* Send the data packet */
-  Mirf.send( (byte *) message.id );
-  Mirf.send( (byte *) message.data );
-  Mirf.send( (byte *) message.checksum[0] );
-  Mirf.send( (byte *) message.checksum[1] );
-
-  /* While data is still transmitted */
+  /* Wait for data to be transmitted */
   while ( Mirf.isSending() );
   Serial.println( "Finished sending" );
   delay( 10 );
+}
+
+void g() {
+  /* transmit the datapacket */
+  transmitPacket();

-  /* While we are receiving the data packet */
-  while ( !Mirf.dataReady() );
-
-  Serial.print( "received: " );
-  /* Get the byte from the tranceiver */
-  Mirf.getData( (byte *) message.data );
-  /* TODO: do something useful */
-  int i;
-  for ( i = 0; i < Mirf.payload; ) {
-    Serial.println( (char) message.data );
-  }
-
-  /* Timeout when data packet was not received within 1 second */
-  if ( ( millis() - time ) > 1000 ) {
-    Serial.println("Timeout on response from server!");
-    return 1;
+  /* timeout for receiving */
+  long time = millis();
+  while ( !rx_finished ) {
+    /* if we received successfuly, refresh timeout */
+    if( receivePacket() == 0 ) time = millis();
+
+    /* Timeout when data packet was not received within 1 second */
+    if ( ( millis() - time ) > 1000 ) {
+      Serial.println( "Timeout on response from server!" );
+      //return 1;
+    }
   }

   /* When transmission was successful */
-  return 0;
 }

 void loop() {
@@ -122,5 +138,9 @@
     digitalWrite( 9, HIGH );
     Serial.println( "Finished sending!" );
   }
+
+
+  /* don't freeze the MCU */
+  delay( 100 );
 }


Add first LDR sensor to sketch

Add first LDR sensor to sketch

Initialize the first sensor on the Arduino

--- arduinoApp/gardenSketch/gardenSketch.ino
+++ arduinoApp/gardenSketch/gardenSketch.ino
@@ -0,0 +1,29 @@
+/*
+Arduino based self regulating kitchen garden
+
+ */
+
+// light related setup
+int lightSensorPin = 3; // Set to whereever light sensor is connected
+int lampRelay = 4; // Set to whereever relay for lamp is connected
+
+// activity led setup
+int ledPin = 13; // this is just for checking activity
+
+// Initialize settings
+void setup() {
+  // Initialize output pins.
+  pinMode(ledPin, OUTPUT);
+
+  // Initialize input pins.
+  pinMode(lightSensorPin, INPUT);
+
+}
+
+// Main loop
+void loop() {
+  // Read sensor values
+  analogRead(lightSensorPin);
+
+
+}


Misc. firmware changes for the Typeatron, including simplified 'modes' and more control over visual and haptic cues

--- typeatron/src/main/arduino/typeatron/typeatron.ino
+++ typeatron/src/main/arduino/typeatron/typeatron.ino
@@ -25,10 +25,11 @@
  */

 // OSC addresses
+const char *EXO_TT_ERROR         = "/exo/tt/error";
+const char *EXO_TT_INFO         = "/exo/tt/info";
 const char *EXO_TT_KEYS          = "/exo/tt/keys";
 const char *EXO_TT_LASER_EVENT   = "/exo/tt/laser/event";
 const char *EXO_TT_LASER_TRIGGER = "/exo/tt/laser/trigger";
-const char *EXO_TT_MODE          = "/exo/tt/mode";
 const char *EXO_TT_MORSE         = "/exo/tt/morse";
 const char *EXO_TT_PHOTO_DATA    = "/exo/tt/photo/data";
 const char *EXO_TT_PHOTO_GET     = "/exo/tt/photo/get";
@@ -36,6 +37,7 @@
 const char *EXO_TT_PING_REPLY    = "/exo/tt/ping/reply";
 const char *EXO_TT_RGB_SET       = "/exo/tt/rgb/set";
 const char *EXO_TT_VIBRO         = "/exo/tt/vibro";
+const char *EXO_TT_WARNING       = "/exo/tt/warning";

 // these are global so that we can read from setup() as well as loop()
 unsigned int keys[5];
@@ -43,6 +45,13 @@
 unsigned int totalKeysPressed;
 unsigned int lastKeyState = 0;

+const unsigned long infoCueHapticDurationMs = 100;
+const unsigned long infoCueVisualDurationMs = 200;
+const unsigned long errorCueHapticDurationMs = 100;
+const unsigned long errorCueVisualDurationMs = 200;
+const unsigned long warningCueHapticDurationMs = 100;
+const unsigned long warningCueVisualDurationMs = 200;
+

 ////////////////////////////////////////////////////////////////////////////////

@@ -54,6 +63,7 @@
 OSCBundle *bundleIn;

 void sendError(const char *message) {
+   errorCue();
    osc.sendError(message);
 }

@@ -99,21 +109,32 @@

 RGBLED rgbled(redPin, greenPin, bluePin, sendError);

-int colorToggle = 0;
-
-void colorDebug() {
-    if (keyState) {
-        long modeColor = getModeColor();
-        rgbled.replaceColor(modeColor);
-    } else {
-        rgbled.replaceColor(RGB_BLACK);
-    }
-}
-
-void rgbForDuration(unsigned long color, unsigned long ms) {
-    rgbled.pushColor(color);
-    delay(ms);
-    rgbled.popColor();
+unsigned long ledCueLength = 0;
+unsigned long ledCueSince = 0;
+
+void infoCue() {
+    rgbled.replaceColor(RGB_BLUE);
+    ledCueLength = infoCueVisualDurationMs;
+    ledCueSince = millis();
+}
+
+void warningCue() {
+    rgbled.replaceColor(RGB_YELLOW);
+    ledCueLength = warningCueVisualDurationMs;
+    ledCueSince = millis();
+}
+
+void errorCue() {
+    rgbled.replaceColor(RGB_RED);
+    ledCueLength = errorCueVisualDurationMs;
+    ledCueSince = millis();
+}
+
+void checkLedStatus(unsigned long now) {
+    if (ledCueSince > 0 && now - ledCueSince > ledCueLength) {
+        rgbled.replaceColor(0);
+        ledCueSince = 0;
+    }
 }

@@ -151,51 +172,16 @@

 ////////////////////////////////////////////////////////////////////////////////

-const int totalModes = 6;
-
 typedef enum {
-    Text = 0,
+    Normal = 0,
     LaserTrigger,
-    LaserPointer,
-    Mash
+    LaserPointer
 } Mode;
-
-const char *modeNames[] = {
-    "Text",
-    "LaserTrigger",
-    "LaserPointer",
-    "Mash"
-};
-
-const unsigned long modeColors[] = {
-    RGB_BLUE,   // Text
-    RGB_BLACK,  // LaserTrigger
-    RGB_RED,    // LaserPointer
-    RGB_WHITE   // Mash
-};

 Mode mode;

 void setMode(int m) {
     mode = (Mode) m;
-}
-
-unsigned long getModeColor() {
-    return modeColors[mode];
-}
-
-int modeValueOf(const char *name) {
-    int i;
-    for (i = 0; i < totalModes; i++) {
-        if (!strcmp(name, modeNames[i])) {
-            osc.sendInfo("identified mode as %d", i);
-            return i;
-        }
-    }
-
-    osc.sendError("no such mode: %s", name);
-
-    return Text;
 }

@@ -273,8 +259,6 @@
     osc.beginSerial();
     droidspeak.speakSerialOpenPhrase();

-    //setMode(LowercaseText);
-
     bundleIn = new OSCBundle();

     //morse.playMorseString("foo");
@@ -286,43 +270,43 @@

 void handleOSCBundle(class OSCBundle &bundle) {
     if (bundle.hasError()) {
+        errorCue();
         osc.sendOSCBundleError(bundle);
     } else if (!(0
+        || bundle.dispatch(EXO_TT_ERROR, handleErrorMessage)
+        || bundle.dispatch(EXO_TT_INFO, handleInfoMessage)
         || bundle.dispatch(EXO_TT_LASER_TRIGGER, handleLaserTriggerMessage)
-        || bundle.dispatch(EXO_TT_MODE, handleModeMessage)
         || bundle.dispatch(EXO_TT_MORSE, handleMorseMessage)
         || bundle.dispatch(EXO_TT_PHOTO_GET, handlePhotoGetMessage)
         || bundle.dispatch(EXO_TT_PING, handlePingMessage)
         || bundle.dispatch(EXO_TT_RGB_SET, handleRGBSetMessage)
         || bundle.dispatch(EXO_TT_VIBRO, handleVibroMessage)
+        || bundle.dispatch(EXO_TT_WARNING, handleWarningMessage)
         )) {
           for (int i = 0; i < bundle.size(); i++) {
               OSCMessage *m = bundle.getOSCMessage(i);
               char address[256];
               m->getAddress(address);
+              errorCue();
               osc.sendError("no handler for address %s", address);
           }
     }
 }

+void handleErrorMessage(class OSCMessage &m) {
+    errorCue();
+    vibrateForDuration(errorCueHapticDurationMs);
+}
+
+void handleInfoMessage(class OSCMessage &m) {
+    infoCue();
+    vibrateForDuration(infoCueHapticDurationMs);
+}
+
 void handleLaserTriggerMessage(class OSCMessage &m) {
     setMode(LaserTrigger);
 }

-void handleModeMessage(class OSCMessage &m) {
-    if (!osc.validArgs(m, 1)) return;
-
-    if (m.isString(0)) {
-        int length = m.getDataLength(0);
-        char buffer[length+1];
-        m.getString(0, buffer, length+1);
-
-        setMode(modeValueOf(buffer));
-    } else {
-        osc.sendError("expected string-valued mode name");
-    }
-}
-
 const int morseBufferLength = 32;
 char morseBuffer[morseBufferLength];

@@ -331,6 +315,7 @@

     int length = m.getDataLength(0);
     if (length >= morseBufferLength) {
+        errorCue();
         osc.sendError("Morse message is too long");
         return;
     } else {
@@ -362,6 +347,7 @@
     int32_t color = m.getInt(0);

     if (color < 0 || color > 0xffffff) {
+        errorCue();
         osc.sendError("color out of range: %d", (long) color);
     } else {
         rgbled.replaceColor(color);
@@ -374,13 +360,23 @@
     int32_t d = m.getInt(0);

     if (d <= 0) {
+        errorCue();
         osc.sendError("duration must be a positive number");
     } else if (d > 60000) {
+        errorCue();
         osc.sendError("duration too long");
     } else {
         vibrateForDuration((unsigned long) d);
     }
 }
+
+void handleWarningMessage(class OSCMessage &m) {
+    warningCue();
+    vibrateForDuration(warningCueHapticDurationMs);
+}
+
+
+////////////////////////////////////////////////////////////////////////////////

 void sendAnalogObservation(class AnalogSampler &s, const char* address) {
     OSCMessage m(address);
@@ -432,11 +428,12 @@
         bundleIn = new OSCBundle();
     }

+    unsigned long now = millis();
+    checkLedStatus(now);
+
     // keying action
     readKeys();
     if (keyState != lastKeyState) {
-        colorDebug();
-
         if (LaserTrigger == mode) {
             if (keyState) {
                 laserOn();
@@ -445,7 +442,7 @@
             }
         } else if (LaserPointer == mode) {
             if (!keyState) {
-                setMode(Text);
+                setMode(Normal);
                 laserOff();
             }
         } else {
@@ -467,10 +464,6 @@
         }
     }
     lastKeyState = keyState;
-
-    //int l = analogRead(A3);
-    //System.out.print("light level: ");
-    //System.out.println(l);
-}
-
-
+}
+
+


including temperature from BMP085

including temperature from BMP085

--- ctd/ctd.ino
+++ ctd/ctd.ino
@@ -2,20 +2,26 @@
 #include <SD.h>
 #include <Wire.h>                  // BMP085
 #include <Adafruit_BMP085.h>       // BMP085
+// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
+// Connect GND to Ground
+// Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
+// Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
+
 // Base name must be six characters or less for short file names.
 #define FILE_BASE_NAME "Data"

-const uint8_t CS_PIN = 10; // ChipSelect (MKRZero SD: SDCARD_SS_PIN)
-const int gLed =  11;      //
-const int rLed = 8;        //
-const int LM35 = A0;       // Temperature sensor
+const uint8_t CS_PIN = 10;        // ChipSelect (MKRZero SD: SDCARD_SS_PIN)
+const int gLed =  11;            //
+const int rLed = 8;              //
+const int LM35 = A0;             // Temperature sensor
 Adafruit_BMP085 bmp;
+//SoftwareSerial gpsSerial(2, 3); // TX, RX - GPS

 File dataFile;
 unsigned long int ttime;
 float temp;
-float time;
+long lat,lon;

 const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
 char fileName[] = FILE_BASE_NAME "00.csv";
@@ -29,7 +35,7 @@
   if (!SD.begin(CS_PIN) and !bmp.begin()) {
     Serial.println(F("begin failed"));
     digitalWrite(rLed, HIGH);
-    delay(2000);
+    delay(4000);
     digitalWrite(rLed, LOW);
     return;
   }
@@ -116,12 +122,28 @@
   File dataFile = SD.open(fileName, FILE_WRITE);
   dataFile.print(ttime);
   dataFile.print(",");
+  // Record GPS data
+  // dataFile.print(",");
   dataFile.print(temp);
+  dataFile.print(",");
+  dataFile.print(bmp.readTemperature());
+  dataFile.print(",");
+  dataFile.print(bmp.readPressure());
+  dataFile.print(",");
+  dataFile.print(bmp.readSealevelPressure());
+  dataFile.print(",");
+  dataFile.print(bmp.readAltitude(101500));
+  // if the current sea level pressure is known, it will
+  // vary with weather and such. If it is 1015 millibars
+  // that is equal to 101500 Pascals.
+  // Altitude is in meters
+  dataFile.print(",");
+
   dataFile.close();

   Serial.print("The Temp is: ");
   Serial.println(temp);
   Serial.print("The time is: ");
-  Serial.println(time);
+  Serial.println(ttime);
   Serial.println("");
 }


Update Time example

Update Time example

--- examples/GSMSim_Time/GSMSim_Time.ino
+++ examples/GSMSim_Time/GSMSim_Time.ino
@@ -29,25 +29,25 @@
   // Get module date time
   Serial.print("Module DateTime: ");
   Serial.println(gsm.timeGetRaw());
-
+
   Serial.print("Connect to Internet: ");
   // For setting time from ntp servers, we must connect to internet!
   Serial.println(gsm.gprsConnectBearer());

   Serial.print("Set timezone to +3: ");
   Serial.println(gsm.timeSetServer(3)); // time server is: 202.120.2.101 (Shanghai Jiaotong University - China)
-  //Serial.println(gsm.timeSetServer("202.120.2.101", 3)); // you can set server too :)
+  //Serial.println(gsm.timeSetServer(3, "202.120.2.101")); // you can set server too :)

   Serial.print("Sync from server. Server response: ");
   Serial.println(gsm.timeSyncFromServer());

   Serial.print("Module DateTime after sync: ");
   Serial.println(gsm.timeGetRaw());
-
+
   // Close internet connection
   Serial.print("Close Internet: ");
   Serial.println(gsm.gprsCloseConn());
-
+
 }

 void loop() {


Modify feedback led

Modify feedback led

--- Sensors/GpsDataToSerial/GpsDataToSerial.ino
+++ Sensors/GpsDataToSerial/GpsDataToSerial.ino
@@ -26,11 +26,18 @@
 int count=0;
 boolean routeStarted = false;

-unsigned long interval = 1000; // the time we need to wait
+unsigned long ledInterval = 300;
+unsigned long tphInterval = 1000;
+unsigned long gpsInterval = 1000;
+unsigned long previousMillisLED = 0;
 unsigned long previousMillisTPHv2 = 0;
 unsigned long previousMillisGPS = 0;

 boolean previousButtonState = false;
+boolean bLed1State = false;
+boolean bLed1 = false;
+boolean bLed2State = false;
+boolean bLed2 = false;

 Adafruit_BME280 bme;

@@ -40,6 +47,12 @@

 void setup()
 {
+  pinMode(LED1, OUTPUT);
+  digitalWrite(LED1, LOW);
+  bLed1 = true;
+  pinMode(LED2, OUTPUT);
+  digitalWrite(LED2, LOW);
+
   bme.begin();
   SoftSerial.begin(9600);
   Serial.begin(9600);
@@ -50,19 +63,20 @@
 {
   checkButton();

-  unsigned long currentMillis = millis(); // grab current time
-
-  // check if "interval" time has passed (1000 milliseconds)
-  if ((unsigned long)(currentMillis - previousMillisTPHv2) >= 200) {
+  unsigned long currentMillis = millis();
+
+  if ((unsigned long)(currentMillis - previousMillisLED) >= ledInterval) {
+    setLed(2);
+    previousMillisLED = millis();
+  }
+
+  if ((unsigned long)(currentMillis - previousMillisTPHv2) >= tphInterval) {
     checkTPHv2();
-    // save the "current" time
     previousMillisTPHv2 = millis();
   }

-  // check if "interval" time has passed (1000 milliseconds)
-  if ((unsigned long)(currentMillis - previousMillisGPS) >= interval) {
+  if ((unsigned long)(currentMillis - previousMillisGPS) >= gpsInterval) {
     checkGPS();
-    // save the "current" time
     previousMillisGPS = millis();
   }
 }
@@ -79,6 +93,35 @@
   }

   previousButtonState = currentButtonState;
+}
+
+void setLed(int led)
+{
+  if(led == 1 && bLed1)
+  {
+      bLed1State = !bLed1State;
+      if(bLed1State)
+        digitalWrite(LED1, HIGH);
+      else
+        digitalWrite(LED1, LOW);
+  }
+  else
+  {
+    digitalWrite(LED1, LOW);
+  }
+
+  if(led == 2 && bLed2)
+  {
+      bLed2State = !bLed2State;
+      if(bLed2State)
+        digitalWrite(LED2, HIGH);
+      else
+        digitalWrite(LED2, LOW);
+  }
+  else
+  {
+    digitalWrite(LED2, LOW);
+  }
 }

 void checkTPHv2()
@@ -119,11 +162,6 @@
             value += current;
           }

-          //String sLat = getValue(value,',',2);
-          //float fLat = (sLat.substring(0,2)).toFloat() + (sLat.substring(2,4)).toFloat() / 60.0f + (sLat.substring(4,9)).toFloat() / 60.0f;
-          //String sLong = getValue(value,',',4);
-          //float fLong = (sLong.substring(0,2)).toFloat() + (sLong.substring(2,4)).toFloat() / 60.0f + (sLong.substring(4,9)).toFloat() / 60.0f;
-
           String sLat = getValue(value,',',2);
           if(sLat == "")
             sLat = "0";
@@ -138,14 +176,27 @@
           if(sAlt == "")
             sAlt = "0";

+          if(sLat == "0" || sLong == "0")
+          {
+            bLed1 = true;
+            setLed(1);
+            bLed1State = false;
+            bLed2 = false;
+          }
+          else
+          {
+            bLed1 = false;
+            bLed2 = true;
+          }
+
           String data = "{\"latitude\":\"" + sLat + "\",\"latd\":\"" + sLatd + "\",\"longitude\":\"" + sLong + "\",\"longd\":\"" + sLongd + "\",\"altitude\":\"" + sAlt + "\",\"T\":\"" + currentTemperature + "\",\"P\":\"" + currentPressure + "\",\"H\":\"" + currentHumidity + "\"}";

           Serial.println("#");
-          delay(50);
+          delay(25);
           Serial.println(data);
-          delay(50);
+          delay(100);
           Serial.println("#");
-          delay(50);
+          delay(25);
         }
       }
     }


slide show via sdcard

slide show via sdcard

--- PixelViews/Goomba/Goomba.ino
+++ PixelViews/Goomba/Goomba.ino
@@ -1,22 +1,20 @@
 #include <FastLED.h>
 #include <EEPROM.h>
 #include <SPI.h>
+#include <SD.h>

 #define LED_PIN     5
 #define COLOR_ORDER GRB
 #define CHIPSET     WS2811

 #define PIN_BRIGHTNESS A0
-#define PIN_MODE 4
+#define PIN_MODE 3
 #define PIN_LED A1

-int currentMode = 4;
-#define MAXMODE 5
+#define DEFAULTMODE 5;
+#define MAXMODE 6
+int currentMode = DEFAULTMODE;
 int eeprom_addr = 0;
-
-long lastMillis = millis();
-long currentMillis = millis();
-long pauseMillis = 10 * 1000;

 const uint8_t kMatrixWidth = 20;
 const uint8_t kMatrixHeight = 10;
@@ -29,15 +27,23 @@
 int buttonState;
 int lastButtonState = LOW;
 unsigned long lastDebounceTime = 0;
-unsigned long debounceDelay = 75;
+unsigned long debounceDelay = 10;
 byte ledvalues[200*3] = {0};
+bool initFailed = false;

 void setup()
-{
+{
   pinMode(PIN_BRIGHTNESS, INPUT);
   pinMode(PIN_MODE, INPUT);
   pinMode(PIN_LED, OUTPUT);

+  Serial.begin(9600);
+
+  if (!SD.begin(4)) {
+    initFailed = true;
+  }
+
+  currentMode = 5;
   currentMode = EEPROM.read(eeprom_addr);

   // LEDColorCorrection { TypicalSMD5050 =0xFFB0F0, TypicalLEDStrip =0xFFB0F0, Typical8mmPixel =0xFFE08C, TypicalPixelString =0xFFE08C, UncorrectedColor =0xFFFFFF }
@@ -96,29 +102,70 @@
   return XY(x, y);
 }

+int pressCount = 0;
+
+char curFileName[12] = "";
+File myFile;
+long previousMillis = 0;
+long interval = 1000;
+int currentFileIndex = 0;
+
 void loop()
 {
+  if(initFailed)
+    ShowError(2);
+
   int brightness = analogRead(PIN_BRIGHTNESS);
   int newBrightness = map(brightness, 0, 1023, 0, 255);
-
+
+  EEPROM.write(eeprom_addr, currentMode);
+
   bool r = isButtonPressed();
   if(r)
+    pressCount++;
+  else
+    pressCount = 0;
+
+  if(r && pressCount <= 1)
+  {
     currentMode++;

+    previousMillis = millis();
+
+    FastLED.clear();
+
+    Serial.print("Mode: ");
+    Serial.println(currentMode);
+  }
+
   if(currentMode >= MAXMODE)
     currentMode = 0;

-  EEPROM.write(eeprom_addr, currentMode);
-
-  FastLED.clear();
-
   switch(currentMode)
   {
-    case 0: Test(); break;
-    case 1: ShowPotValue(); break;
-    case 2: RainbowA(); break;
-    case 3: ShowGoomba(); break;
-    case 4: ShowMario(); break;
+    case 0:
+      FastLED.clear();
+      Test();
+      break;
+    case 1:
+      FastLED.clear();
+      ShowPotValue();
+      break;
+    case 2:
+      FastLED.clear();
+      RainbowA();
+      break;
+    case 3:
+      FastLED.clear();
+      ShowGoomba();
+      break;
+    case 4:
+      FastLED.clear();
+      ShowMario();
+      break;
+    case 5:
+      ShowFiles();
+      break;
   }

   FastLED.show();
@@ -128,6 +175,21 @@
 void set_led_rgb(int x, int y, int r, int g, int b)
 {
   leds[ XY(x, y) ] = CRGB( r, g, b );
+}
+
+void ShowError(int errorNr)
+{
+  if(errorNr <= 0 || errorNr >= 200)
+    return;
+
+  Serial.print("Error: ");
+  Serial.println(errorNr);
+
+  FastLED.clear();
+  for(int led = 0; led < errorNr; led++) {
+    leds[led] = CRGB::Red;
+  }
+  FastLED.show();
 }

 void RainbowA()
@@ -159,16 +221,87 @@
   set_led_rgb(2, 1, 0, 0, 255);
 }

+int lastNumLedsToLight = 0;
+
 void ShowPotValue()
 {
   int val = analogRead(PIN_BRIGHTNESS);
   int numLedsToLight = map(val, 0, 1023, 0, 200);
+
+  if(numLedsToLight != lastNumLedsToLight)
+  {
+    lastNumLedsToLight = numLedsToLight;
+    Serial.print("Pot: ");
+    Serial.println(lastNumLedsToLight);
+  }

   FastLED.clear();
     for(int led = 0; led < numLedsToLight; led++) {
       leds[led] = CRGB::Blue;
     }
   FastLED.show();
+}
+
+bool shown = false;
+
+int ShowFiles()
+{
+  unsigned long currentMillis = millis();
+  long delta = currentMillis - previousMillis;
+  if(delta < interval)
+    return;
+  previousMillis = currentMillis;
+  currentFileIndex++;
+
+  FastLED.clear();
+
+  sprintf(curFileName, "%02d.txt", currentFileIndex);
+  myFile = SD.open(curFileName, FILE_READ);
+  if(!myFile)
+  {
+    currentFileIndex = 1;
+    sprintf(curFileName, "%02d.txt", currentFileIndex);
+    myFile = SD.open(curFileName, FILE_READ);
+  }
+
+  if(!myFile)
+  {
+    ShowError(1);
+    return;
+  }
+
+  Serial.println(curFileName);
+
+  String line = "";
+  while(myFile.available())
+  {
+    char c = (char) myFile.read();
+
+    line += c;
+
+    if(c == '\n')
+    {
+      int val[5];
+      char *pch;
+      pch = strtok (line.c_str(), ",");
+      for(byte i = 0; i < 5; ++i)
+      {
+        if(pch == NULL)
+          break;
+        String s(pch);
+        val[i] = s.toInt();
+        pch = strtok (NULL, ",");
+      }
+
+      set_led_rgb(val[0], val[1], val[2], val[3], val[4]);
+
+      line = "";
+    }
+  }
+
+  myFile.close();
+
+  return 0;
 }

 void ShowGoomba()


Изменена программа для Arduino

Изменена программа для Arduino

--- Arduino/Bluetooth-car.ino
+++ Arduino/Bluetooth-car.ino
@@ -1,138 +1,50 @@
-#include "MotorShield.h"
-#include <SoftwareSerial.h>
-
-SoftwareSerial mySerial(10, 11);  //RX модуля 11 пин TX модуля 10 пин
-
-//���������� � ���������:
-
-const int	MAX_TRIG_POS_Y = 500;	//Максимальная позиция для тригерного состояния поворота на месте
-const int	MIN_TRIG_POS_X = 3000;	//Минимальная позиция для тригерного состояния поворота на месте
-
-int speedLeft, speedRight;			//Скорости левого и равого моторов
-const int SPEED_TRIG = 255;			//Скорость в тригерном состоянии
-
-const int INTERVAL = 30;
-long long int prevMillis;
-
-float MAXPOS = 32640;			//Максимальная позиция стиков геймпада(по модулю)
-
-float buffPosX=0;         //Переменные для хранения позиции
-float buffPosY=0;
-
-//Функции:
-void SerialTakeMessage(float *buffX, float *buffY)	//Функция считывания команды
-{
-	int lenMes;									//Переменная для хранения длинны сообщения
-
-	if (mySerial.available()>=3)
-	{
-		while (mySerial.read() != 'S');		      	//Переменная для хранения длинны сообщения
-      //Serial.print("S");
-		lenMes = mySerial.parseInt();				      //Считываем длинну сообщения
-      //Serial.print(lenMes);
-      //Serial.print(";");
-		mySerial.read();							            //Пропускаем разделяющий символ
-		while(mySerial.available() < lenMes);			//Ждём пока придёт всё сообщение
-			//Считываем координаты:
-			*buffX = mySerial.parseFloat();
-           //Serial.print(*buffX);
-			mySerial.read();
-			*buffY = mySerial.parseFloat();
-            //Serial.print(";");
-            //Serial.print(*buffY);
-            //Serial.print("\n");
-			mySerial.read();
-			mySerial.read();
-	}
-}
-
-void debugInf(float pX, float pY, int s1, int s2, int ds) //Отладочная информация
-{
-	Serial.print("px: ");
-	Serial.print(pX,12);
-	Serial.print("py: ");
-	Serial.print(pY,12);
-	Serial.print(";");
-	Serial.print(" s1: ");
-	Serial.print(s1);
-	Serial.print(" s2: ");
-	Serial.print(s2);
-	Serial.print(" ds: ");
-	Serial.print(ds);
-	Serial.print(";\n");
-}
-
-void setup()
-{
-	//Serial.begin(9600);
-  mySerial.begin(9600);
-	initMotorShield();
-}
-
-void loop()
-{
-
-	SerialTakeMessage(&buffPosX, &buffPosY);	//Считываем команду с координатами
-
-	//Приводим значения координат к промежутку от 0 до 1(по модулю) для работы с единичной окружностью
-	float posX = fabs(buffPosX / MAXPOS);
-	float posY = fabs(buffPosY / MAXPOS);
-
-  //Этот блок нужнен для моего джойстика:
- if(fabs(buffPosX)<129)posX=0;
- if(fabs(buffPosY)<129)posY=0;
-
-  /*Если позиция по оси X меньше нуля, это значит мы поворачиваем вправо, поэтому ведущий
-  мотор, которому соответствует скорость пропрциональная положению по оси Y, если позиция
-  по оси X больше или равна нулю, то верно обратное*/
-
-  float coefSpeedDif; //Коэффициент разности скоростей
-
-  if (buffPosX<0) {
-    speedRight = 255 * sqrt(2 * posY - pow(posY, 2));  //Скорость правого мотора
-    coefSpeedDif = sqrt(1 - pow(posX, 2));             //Коэффициент разности скоростей между моторами
-    speedLeft = speedRight*coefSpeedDif;               //Скорость левого мотора
-  }
-  else {
-
-    speedLeft = 255 * sqrt(2 * posY - pow(posY, 2));   //Скорость левого мотора
-    coefSpeedDif = sqrt(1 - pow(posX, 2));             //Коэффициент разности скоростей между моторами
-    speedRight = speedLeft*coefSpeedDif;               //Скорость правого мотора
-  }
-
-  //Проверка на тригерное состояние поворота на месте:
-  if ((fabs(buffPosY) <= MAX_TRIG_POS_Y) && (fabs(buffPosX) >= MIN_TRIG_POS_X)) {
-    if (buffPosX<0) {
-      if (millis() - prevMillis >= INTERVAL) {
-        prevMillis = millis();
-        motorsGo(BCKWRD, FRWRD, SPEED_TRIG, SPEED_TRIG);  //Поворот на месте вправо
-      }
-    }
-    else {
-      if (millis() - prevMillis >= INTERVAL) {
-        prevMillis = millis();
-        motorsGo(FRWRD, BCKWRD, SPEED_TRIG, SPEED_TRIG);  //Поворот на месте влево
-      }
-    }
-  }
-  else {
-    /*Если позиция по оси Y меньше нуля то мы едем назад, если положительна, то мы
-    едем вперёд*/
-    if (buffPosY<0) {
-      if (millis() - prevMillis >= INTERVAL) {
-        prevMillis = millis();
-        motorsGo(BCKWRD, BCKWRD, speedLeft, speedRight);
-        }
-        //Serial.println("BKWRD");
-    }
-    else if(buffPosY>0){
-      if (millis() - prevMillis >= INTERVAL) {
-        prevMillis = millis();
-        motorsGo(FRWRD, FRWRD, speedLeft, speedRight);
-        //Serial.println("FWRD");
-      }
-    }
-  }
-
-  //debugInf(posX, posY, speedLeft, speedRight, coefSpeedDif);
+#include "MotorShield.h"
+#include <SoftwareSerial.h>
+
+SoftwareSerial mySerial(10, 11);  //RX модуля 11 пин TX модуля 10 пин
+
+
+const int MESSAGE_HEADER = 42;
+const int MESSAGE_END = 0;
+const int WATCH_DOG_INTERVAL = 400;
+
+void SerialTakeMessage(bool *dirLM, bool *dirRM, int *speedLM, int *speedRM, bool *flg)
+{
+  if (mySerial.available() >= 6)
+  {
+    while (mySerial.read() != MESSAGE_HEADER);
+     *dirLM = mySerial.read();
+     *dirRM = mySerial.read();
+     *speedLM = mySerial.read();
+     *speedRM = mySerial.read();
+     *flg = true;
+  }
 }
+void setup() {
+	mySerial.begin(9600);
+	initMotorShield();
+}
+
+bool dirLM =0;
+bool dirRM =0;
+int speedLM=0;
+int speedRM=0;
+
+unsigned long long int prevMillis=0;
+
+void loop() {
+	bool flg=false;
+ 	SerialTakeMessage(&dirLM, &dirRM, &speedLM, &speedRM, &flg);
+ 	motorsGo(dirLM, dirRM, speedLM, speedRM);
+
+	if(flg)
+		prevMillis = millis();
+
+	if((millis() - prevMillis)>WATCH_DOG_INTERVAL)
+	{
+	 dirLM =0;
+	 dirRM =0;
+	 speedLM=0;
+      	 speedRM=0;
+	}
+}


Fixed malformed JSON.

Fixed malformed JSON.

--- libraries/ATT_IOT/examples/iot_demo/iot_demo.ino
+++ libraries/ATT_IOT/examples/iot_demo/iot_demo.ino
@@ -60,7 +60,7 @@

   if(Device.Connect(&ethClient, httpServer))                //connect the device with the IOT platform.
   {
-    Device.AddAsset(knobPin, "knob", "rotary switch",false, "{'type': 'integer', 'minimum': 0, 'maximum': 1023");
+    Device.AddAsset(knobPin, "knob", "rotary switch",false, "{\"type\": \"integer\", \"minimum\": 0, \"maximum\": 1023}");
     Device.AddAsset(ledPin, "led", "light emitting diode", true, "boolean");
     Device.Subscribe(pubSub);                               // make certain that we can receive message from the iot platform (activate mqtt)
   }


adjusted too low temp to 23.5 degrees

adjusted too low temp to 23.5 degrees

--- QmoteRHTlogger_w_Daikin/QmoteRHTlogger_w_Daikin.ino
+++ QmoteRHTlogger_w_Daikin/QmoteRHTlogger_w_Daikin.ino
@@ -35,7 +35,7 @@
 #define HEAT_INDEX_TOO_HIGH   30          // use Heat Index to check if the ambient condition needs to be changed, if so, KEEP_OFF_TIMER will be ignored
 #define TEMP_HIGH             26.5        // Highheat index may be caused by Rh, set High limitation to determine cooling or dehumidifier
 #define TEMP_LOW              25          // stop cooling or switch to humidifier if temerature reaches this measurement
-#define TEMP_TOO_LOW          23          // if temperature reaches this value means humidifier goes too much, turn off everything
+#define TEMP_TOO_LOW          23.5        // if temperature reaches this value means humidifier goes too much, turn off everything
 #define RH_HIGH               69          // restart humidifier if Rh reaches to this measurement
 #define RH_LOW                60          // stop humidifier if Rh reaches to this measurement


Updated FSK example

Updated FSK example

--- examples/FSKModem/FSKModem.ino
+++ examples/FSKModem/FSKModem.ino
@@ -2,6 +2,8 @@
    LoRaLib FSK Modem Example

    This example shows how to use FSK modem in SX127x chips.
+   NOTE: The code below is just a guide, do not attempt
+         to run it!

    For more detailed information, see the LoRaLib Wiki
    https://github.com/jgromes/LoRaLib/wiki
@@ -140,9 +142,6 @@
   if (state != ERR_NONE) {
     Serial.println(F("Unable to start direct mode, code "));
   }
-  // NOTE: you will not be able to send or receive packets
-  // while direct mode is active! to deactivate it, call method
-  // fsk.packetMode()

   // using the direct mode, it is possible to transmit
   // FM notes with Arduino tone() function
@@ -153,4 +152,27 @@
   // transmit FM note at 500 Hz for 1 second
   tone(4, 500);
   delay(1000);
+
+  // NOTE: you will not be able to send or receive packets
+  // while direct mode is active! to deactivate it, call method
+  // fsk.packetMode()
+
+  // "directMode()" method also has an override that allows
+  // you to set raw frequency as 24-bit number
+  // this allows you to send RTTY data
+
+  // set frequency deviation to 0 (required for RTTY)
+  fsk.setFrequencyDeviation(0);
+  // start baud rate timer
+  unsigned long start = micros();
+  // send space (low; 0x6C9999 * 61 Hz = 434.149 749 MHz)
+  fsk.directMode(0x6C9999)
+  // wait for baud rate 45
+  while(micros() - start < 22222);
+  // restart baud rate timer
+  start = micros();
+  // send mark (high; 0x6C999C * 61 Hz = 434.149 932 MHz; 183 Hz shift)
+  fsk.directMode(0x6C9999)
+  // wait for baud rate 45
+  while(micros() - start < 22222);
 }


small fix

small fix

--- examples/Odometer/Odometer.ino
+++ examples/Odometer/Odometer.ino
@@ -4,7 +4,6 @@
 unsigned long startTime;
 unsigned int timeOver = 20000; //20 seconds
 const int encoderPin = 19; //digital pin 19 (interrupt 4 on arduino mega)
-

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


Make all pins inputs with resistors to minimize power consumption

--- arduino/sender/sender.ino
+++ arduino/sender/sender.ino
@@ -131,6 +131,11 @@

 void setup()
 {
+
+    for (byte i=0; i<20; i++) {
+        pinMode(i, INPUT);        //make all pins input pins
+        digitalWrite(i, HIGH);    //with pullup resistors to minimize power consumption
+    }

     pinMode(DEBUG_LED_TX, OUTPUT);
     pinMode(DEBUG_LED_MOTION, OUTPUT);


Fixing pin configurations

Fixing pin configurations

--- core_app/core_app.ino
+++ core_app/core_app.ino
@@ -21,22 +21,23 @@
 #define ALARM_BUZZ 2

 /*================================ Analog pins =========================================*/
-const int buzzerPin = A2; // buzzer Pin connected to Analog 1
-const int x = A3; // X pin connected to Analog 3
-const int y = A4; // Y pin connected to Analog 4
-const int z = A5; // Z pin connected to Analog 5
+const int buzzerPin = A0; // buzzer Pin connected to Analog 1
+const int z = A2; // Z pin connected to Analog 2
+const int y = A3; // Y pin connected to Analog 3
+const int x = A4; // X pin connected to Analog 4

 /*================================ Digital pins ========================================*/
-const int start = 10;         // Alarm button enabletion connected to Digital 10
+const int start = 8;         // Alarm button enabletion connected to Digital 10
 const int interrupter = 9;   // Doors interrupters pin
-const int vibra = 8;         // checkVibrate sensor pin
-const int fuel = 6;          //fuel Control
+const int fuel = 10;          //fuel Control
+const int vibra = 13;         // checkVibrate sensor pin

 /*============================= controll variables =====================================*/
 int tolerance = 40;          // Sensitivity of the Alarm
 boolean calibrate = false;   // When accelerometer is calibrated - changes to true
 boolean shouldAlarm = false; // When motion is detected - changes to true
 int curState = ALARM_OFF;    // Alarm machine state
+boolean sendGpsData = false;     // need to send gps data

 /*============================ Accelerometer limits ====================================*/
 int xMin; //Minimum x Value
@@ -67,15 +68,8 @@

 void setup()
 {
-    //Setup pins
-    pinMode (start,INPUT);
-    pinMode(vibra, INPUT);
-    pinMode(interrupter, INPUT);
-    pinMode(fuel, OUTPUT);
-
+    setPins();
     delay(500);
-
-    setInputPins();
     setFuel(true);
     calibrateAccel();
     startModule();
@@ -147,6 +141,7 @@
         digitalWrite(fuel, LOW);
         mqttClient.publish(stsTopic,"0");
         calibrateAccel();
+        sendGpsData=false;
     }
 }

@@ -164,6 +159,7 @@
 void buzzAlarm()
 {
     curState = ALARM_BUZZ;
+    sendGpsData = true;
     mqttClient.publish(stsTopic,"2");
 }

@@ -183,7 +179,7 @@

 boolean checkDoors()
 {
-    return (analogRead(interrupter));
+    return digitalRead(interrupter);
 }

 void handleAlarmBuzz()
@@ -199,10 +195,13 @@

 void sendGps()
 {
-    tone(buzzerPin, 10);
-    mqttClient.publish(gpsTopic,simClient.getGPS());
-    noTone(buzzerPin);
-    delay(500);
+    if(sendGpsData) {
+      tone(buzzerPin, 100);
+      mqttClient.publish(gpsTopic,simClient.getGPS());
+      sendGpsData = false;
+      noTone(buzzerPin);
+      delay(500);
+    }
 }

 //Function used to detect motion. Tolerance variable adjusts the sensitivity of movement detected.
@@ -244,10 +243,22 @@
 }

 /*============================= Setup Functions ======================================*/
-void setInputPins()
-{
+void setPins()
+{
+  //Setup pins
+    pinMode (start,INPUT);
+    pinMode(vibra, INPUT);
+    pinMode(interrupter, INPUT);
+    pinMode(A1, OUTPUT);
+    pinMode(fuel, OUTPUT);
+    pinMode(11, OUTPUT);
+    pinMode(12, OUTPUT);
+
     //all input pins should be initialized here
     digitalWrite(interrupter,LOW);
+    digitalWrite(A1, LOW);
+    digitalWrite(11, HIGH);
+    digitalWrite(12, LOW);
 }

 void setFuel(boolean op)
@@ -294,7 +305,7 @@
         simClient.begin(9600);

         //starting GPS module
-        //simClient.startGPS();
+        simClient.startGPS();

         //attaching GPRS network and creating a web connection
         simClient.attach(apn,usr,psw);


Make each transmitter controlled by two pins.

By turning them on and off out of phase, we effectively get a voltage
range of +5V to -5V accross the transistor, quadrupling the power.

Unfortunately, the Arduino only can generate one square wave
automatically at a time, so to generate two square waves simulatneously
at high speed/timing accuracy requires low level port trickery.

--- arduino/test/tx_test/tx_test.ino
+++ arduino/test/tx_test/tx_test.ino
@@ -1,22 +1,63 @@
-// One Arduino controls transmitters on pins 3 and 11, alternately
-// sending out pings from the two of them, simulating two synchronized
+// One Arduino controls two transmitters, alternately sending
+// out pings from the two of them, simulating two synchronized
 // transmitter stations sending out pings in turn.

+#define TX_1_PORT PORTD
+#define TX_2_PORT PORTB
+
 enum {
-  TX_PIN_1 = 3,
-  TX_PIN_2 = 11,
+  TX_1_PIN_1 = 2,
+  TX_1_PIN_2 = 3,
+  TX_2_PIN_1 = 10,
+  TX_2_PIN_2 = 11,
   FREQ = 25000u,  // Hz
-  DURATION = 5u,  // ms
+  PERIOD = 1000000u / FREQ,  // μs
+  HALF_PERIOD = PERIOD / 2u,  // μs
+  DURATION = 5000u,  // μs
+  SPACING = 100000u,  // μs
+  CYCLE = 1000000u,  // μs
 };

 void setup() {
-  pinMode(TX_PIN_1, OUTPUT);
-  pinMode(TX_PIN_2, OUTPUT);
+  pinMode(TX_1_PIN_1, OUTPUT);
+  pinMode(TX_1_PIN_2, OUTPUT);
+  pinMode(TX_2_PIN_1, OUTPUT);
+  pinMode(TX_2_PIN_2, OUTPUT);
 }

 void loop() {
-  tone(TX_PIN_1, FREQ, DURATION);
-  delay(100u);
-  tone(TX_PIN_2, FREQ, DURATION);
-  delay(1000u);
+  unsigned long beginning = micros();
+
+  // Send out ping from transmitter 1
+  unsigned long time = micros() - beginning;
+  unsigned long next = time;
+  while (time < DURATION) {
+    TX_1_PORT = TX_1_PORT & (~(1 << (TX_1_PIN_2 % 8))) | (1 << (TX_1_PIN_1 % 8));
+    next += HALF_PERIOD;
+    while (micros() - beginning < next)
+      ;
+    TX_1_PORT = TX_1_PORT & (~(1 << (TX_1_PIN_1 % 8))) | (1 << (TX_1_PIN_2 % 8));
+    next += HALF_PERIOD;
+    while ((time = micros() - beginning) < next)
+      ;
+  }
+
+  // Send out a ping from transmitter 2
+  while ((time = micros() - beginning) < SPACING)
+    ;
+  next = time;
+  while (time < SPACING + DURATION) {
+    TX_2_PORT = TX_2_PORT & (~(1 << (TX_2_PIN_2 % 8))) | (1 << (TX_2_PIN_1 % 8));
+    next += HALF_PERIOD;
+    while (micros() - beginning < next)
+      ;
+    TX_2_PORT = TX_2_PORT & (~(1 << (TX_2_PIN_1 % 8))) | (1 << (TX_2_PIN_2 % 8));
+    next += HALF_PERIOD;
+    while ((time = micros() - beginning) < next)
+      ;
+  }
+
+  // Wait for end of cycle
+  while (micros() - beginning < CYCLE)
+    ;
 }


Check voltage; transmit voltage; switch to spi; force sensor sleep

--- Kleineswetter/Kleineswetter.ino
+++ Kleineswetter/Kleineswetter.ino
@@ -19,7 +19,7 @@
 #include <ESP8266WiFi.h>
 #include "CrcableData.h"

-Adafruit_BME280 bme;
+Adafruit_BME280 bme(0);
 bool bme_ok = false;

 class SystemState : public CrcableData {
@@ -43,6 +43,17 @@
   Serial.begin(115200);
   Serial.println("Beginning"); // More importantly: move cursor to the beginning of the line

+  float volts = analogRead(A0) / 1023.0;
+  float realVolts = volts * 4.975; // measured for 300k and 82k bridge; is somewhat tweaked...
+
+  if (realVolts < 3.2) {
+    Serial.print("Do not start with too low battery: ");
+    Serial.print(realVolts);
+    Serial.println();
+
+    ESP.deepSleep(45*60 * 1000000L); // sleep 45 minutes
+  }
+
   SystemState systemStateFromRtc;
   bool systemStateValid = systemStateFromRtc.readFromRtc(0, sizeof(SystemState));
   if (!systemStateValid) {
@@ -51,7 +62,7 @@
     systemState = systemStateFromRtc;
   }

-  if (!bme.begin(0x76)) {
+  if (!bme.begin()) { // i2c address here would be 0x76
     Serial.println("Could not start BME280.");
     ESP.deepSleep(6e6);

@@ -61,12 +72,12 @@
   }

   // TODO get rid of dummy values
-  randomSeed(analogRead(A0));
-  float t = 49.7 + random(7);
-  float h = 76.5 - random(5);
+  float t = 49.7;
+  float h = 76.5;

   if (bme_ok) {
-    delay(250);
+    // delay(250); // only for i2c
+
     t = bme.readTemperature() - 1;
     h = bme.readHumidity();

@@ -82,6 +93,8 @@
         ESP.deepSleep(3e6);
       }
     }
+
+    bme.setSampling(Adafruit_BME280::MODE_FORCED); // power off

     //*
     if (systemState.roundsWithoutTransmission < 5) {
@@ -207,10 +220,13 @@

   static char numBuffer1[10];
   static char numBuffer2[10];
+  static char numBuffer3[10];
   dtostrf(t, 4, 2, numBuffer1);
   dtostrf(h, 4, 2, numBuffer2);
-  static char outBuffer[22];
-  sprintf(outBuffer, "%s %s", numBuffer1, numBuffer2);
+  dtostrf(realVolts, 4, 2, numBuffer3);
+
+  static char outBuffer[26];
+  sprintf(outBuffer, "%s %s %s", numBuffer1, numBuffer2, numBuffer3);

   client.println(outBuffer);
   Serial.print("Sent ");


fixed ultra sound spiking to thousands issue

--- arduino_motor/mains/Eyes.ino
+++ arduino_motor/mains/Eyes.ino
@@ -46,6 +46,8 @@
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 int Eyes::output_reading_ultra(int index) {
   int dis = this->get_ultra_reading(index);
+
+  if(dis==-1) return -1; // avoid reading as 2590 issues

   dis -= Config::VIRTUAL_OFFSET;

@@ -122,6 +124,10 @@
 }

+/**
+ * avoid IR sensor spikes
+ * @type {boolean}
+ */
 bool Eyes::is_within_range(SharpIR* sensor, int index) {
   for(int i=0; i<5; i++) {
     int distance = sensor->distance();
@@ -132,6 +138,10 @@
   return true;
 }

+/**
+ * avoid ultra sensor spikes
+ * @type {boolean}
+ */
 bool Eyes::is_within_range(Ultrasound* sensor, int index) {
   for(int i=0; i<5; i++) {
     int distance = sensor->dist();


sniffles

sniffles

--- MTM_MASTER/MTM_MASTER.ino
+++ MTM_MASTER/MTM_MASTER.ino
@@ -1,12 +1,17 @@
 #define NUM_MODULES 2
 #define DATA_SIZE   4
+#define C_BLEED     0
+#define BLEED_TIME  1000

 byte modules[NUM_MODULES]={0,1};
+unsigned long previousMillis=0;

 int error();
 int send(byte addr, byte data[], int n);
 int init();
 int bleed();
+void startTimer();
+int maxTimer(unsigned long t);

 void setup() {
     delay(100);
@@ -44,7 +49,32 @@
     return -1;
 }

-int bleed() {
-    if()
+int bleed(byte addr) {
+    if(!send(addr, C_BLEED))
+        error();
+    startTimer();
+    while(massChange()<10 && !maxTimer(BLEED_TIME));
+    if(!send(addr, STOP))
+        error();
     return 0;
+}
+
+void startTimer() {
+    previousMillis=millis();
+}
+
+int maxTimer(unsigned long t) {
+    unsigned long currentMillis=millis();
+    if((unsigned long)(currentMillis-previousMillis)>=t) {
+        return -1;
+    }
+    return 0;
+}
+
+int massFSR() {
+    return -1;
+}
+
+int massChange() {
+    return -1;
 }


works

works


Fix the example's logging

Fix the example's logging

(cherry picked from commit 184d02d2645a1e1127ca6782316c825641c392b3)

--- examples/TeensyDMXRecv/TeensyDMXRecv.ino
+++ examples/TeensyDMXRecv/TeensyDMXRecv.ino
@@ -19,6 +19,7 @@
 TeensyDmx Dmx(Serial1, &rdmData, DMX_REDE);

 void setup() {
+  Serial.begin(9600);
   Dmx.setMode(TeensyDmx::DMX_IN);
 }


Commands now working fine

Commands now working fine

--- Sources/Shrimp/Shrimp.ino
+++ Sources/Shrimp/Shrimp.ino
@@ -31,7 +31,6 @@
 int travelTime; // Total travel time in s
 int maxLogs = 255;
 String msg;
-boolean msgComplete = false;
 boolean logData = true;

 struct MyRec {
@@ -50,50 +49,39 @@

   DHT11.attach(dht11Pin);
   Serial.begin(9600);
-  while (!Serial) { }
-  Serial.println("Type a command");

   db.create(TABLE, sizeof(myrec));
   db.open(TABLE);
 }

-void serialEvent() {
+void loop() {
+    // put your main code here, to run repeatedly:
     while (Serial.available()) {
-     char recieved = Serial.read();
-     msg += recieved;
-
-     if (recieved == '\n') msgComplete = true;
-
-     if (msgComplete) {
-         if (msg == "viewData") selectAll();
-         else if (msg == "stopLogging") {
-             Serial.println("Stopping with logging data");
-             logData = false;
-         } else if (msg == "setTravelTime") setTravelTime();
-     }
-   }
-}
+        boolean msgComplete = false;
+        char recieved = Serial.read();
+        if (recieved != '\n') msg += recieved;
+        else msgComplete = true;

-void loop() {
-   // put your main code here, to run repeatedly:
-//   while (Serial.available() > 0) {
-//     char recieved = Serial.read();
-//     msg += recieved;
-//
-//     if (msg == "viewData") selectAll();
-//     else if (msg == "stopLogging") {
-//         Serial.println("Stopping with logging data");
-//         logData = false;
-//     } else if (msg == "setTravelTime") setTravelTime();
-//   }
+        if (msgComplete) {
+            if (msg == "viewData") selectAll();
+            else if (msg == "stopLogging") {
+                Serial.println("Stopping with logging data");
+                logData = false;
+            } else if (msg == "setTravelTime") setTravelTime();
+
+            msg = "";
+            msgComplete = false;
+        }
+    }
+    //if (Serial.available() == 0) msg = "";

-   unsigned long currentMillis = millis();
+    unsigned long currentMillis = millis();

-   if(currentMillis - previousMillis >= logInterval && logData) {
-      previousMillis = currentMillis;
+    if(currentMillis - previousMillis >= logInterval && logData) {
+        previousMillis = currentMillis;

-      readDHT11();
-   }
+        readDHT11();
+    }
 }

 void selectAll() {
@@ -153,3 +141,16 @@
         avgHumidity = totalHumidity / cases;
     }
 }
+
+void calcAvgTemp() {
+    int totalTemp = 0;
+    int cases = 0;
+    if (db.nRecs()) {
+        for (int i = 1; i <= db.nRecs(); i++) {
+            db.read(i, DB_REC myrec);
+            totalTemp += myrec.temperature;
+            cases++;
+        }
+        avgTemp = totalTemp / cases;
+    }
+}


Fixed missleading documentation.

Fixed missleading documentation.

--- examples/Demo/CosaVWItermostat/CosaVWItermostat.ino
+++ examples/Demo/CosaVWItermostat/CosaVWItermostat.ino
@@ -116,12 +116,10 @@

 void loop()
 {
-  // Wait for a message
+  // Wait for a message with temperature and humidity reading
   msg_t msg;
   int8_t len = rx.recv(&msg, sizeof(msg));
   if (len != sizeof(msg)) return;
-
-  // Read temperature and humidity. Handle read errors
   int16_t humidity = msg.humidity;
   int16_t temperature = msg.temperature;


PS2 Keyboard : added missing return statements

--- arduino/software/ps2_keyboard_drum/PS2KEYSYNTH01/PS2KEYSYNTH01.ino
+++ arduino/software/ps2_keyboard_drum/PS2KEYSYNTH01/PS2KEYSYNTH01.ino
@@ -298,6 +298,7 @@
   if(key==' ')
    {
      midiwrite(0x99, _BASSDRUM_NOTE, 0x65);
+     return;
    }
   if(key==PS2_ENTER)
    {
@@ -307,6 +308,7 @@
   if(key=='0')
    {
      midiwrite(0x99,  _SNAREDRUM_NOTE, 0x65);
+     return;
    }
 }


Fix LEDs off by one problem in OctoWS2811Ext.cpp

--- TeensyStripController.ino
+++ TeensyStripController.ino
@@ -357,14 +357,15 @@
 */

 // Less intense colors for testing - assumes WS2812 color order of G, R, B
-#define RED    0x003F00
-#define GREEN  0x3F0000
-#define BLUE   0x00003F
-#define YELLOW 0x3F3F00
-#define PINK   0x043F22
-#define ORANGE 0x0B3F00
-#define WHITE  0x3F3F3F
+#define RED    0x001600
+#define GREEN  0x160000
+#define BLUE   0x000016
+#define YELLOW 0x141000
+#define PINK   0x001209
+#define ORANGE 0x041000
+#define WHITE  0x101010
 #define BLACK  0x000000
+

 void Test() {
   int microsec = 3000000;  // change them all in 3 seconds
@@ -380,7 +381,7 @@
 }

 void ColorWipe(int color, int wait)
-{
+{
   for (int i=0; i < leds.numPixels(); i++) {
     leds.setPixel(i, color);
   }


Roll forward after orienting

Roll forward after orienting

Robot rolls forward after it orients itself, until it detects a wall on the right. Function then ends

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -172,7 +172,11 @@
     turn(-90);
   }
   else{
-    continue;
+    int a=1;
+  }
+
+  while(rawRight>2){
+    moveForward();
   }
 }


Fixes to allow use of VCU without a computer

--- GEVCU.ino
+++ GEVCU.ino
@@ -247,11 +247,14 @@
   //if the first digital input is high we'll enable drive so we can go!
   if (getDigital(0)) {
     ((DMOC *)motorcontroller)->setGear(DMOC::DRIVE);
+    runThrottle = true;
+    ((DMOC *)motorcontroller)->setPowerMode(DMOC::MODE_TORQUE);
   }

   //but, if the second input is high we cancel the whole thing and disable the drive.
   if (getDigital(1)) {
     ((DMOC *)motorcontroller)->setOpState(DMOC::DISABLED);
+    runThrottle = false;
   }

   if (SerialUSB.available()) serialEvent(); //due doesnt have int driven serial yet


imu: fixes/improvements needed for TapDetect example

- Threshold was set incorrectly, leading to over-sensitive detection
- Default accelerometer range of 2g prevented detection of strong taps
- Added comments to explain the code in more detail

Signed-off-by: Dan O'Donovan <2591e5f46f28d303f9dc027d475a5c60d8dea17a@emutex.com>

--- libraries/CurieImu/examples/TapDetect/TapDetect.ino
+++ libraries/CurieImu/examples/TapDetect/TapDetect.ino
@@ -45,17 +45,23 @@
 void setup() {
     Serial.begin(115200);

-    /* Initialise the IMU */
+    // Initialise the IMU
     CurieImu.initialize();
     CurieImu.attachInterrupt(eventCallback);

-    /* Enable Double-Tap Detection */
+    // Increase Accelerometer range to allow detection of stronger taps (< 4g)
+    CurieImu.setFullScaleAccelRange(BMI160_ACCEL_RANGE_4G);

-    CurieImu.setTapDetectionThreshold(192); // 1.5g
-    CurieImu.setDoubleTapDetectionDuration(BMI160_DOUBLE_TAP_DURATION_500MS);
+    // Reduce threshold to allow detection of weaker taps (>= 750mg)
+    CurieImu.setTapDetectionThreshold(6); // (6 x 125mg)
+
+    // Set the time window for 2 taps to be registered as a double-tap (<= 250 milliseconds)
+    CurieImu.setDoubleTapDetectionDuration(BMI160_DOUBLE_TAP_DURATION_250MS);
+
+    // Enable Double-Tap detection
     CurieImu.setIntDoubleTapEnabled(true);

-    /* Enable Interrupts Notifications */
+    // Enable Interrupts Notifications
     CurieImu.setIntEnabled(true);

     Serial.println("IMU initialisation complete, waiting for events...");


tweak gprs enable in fona digital out example

--- arduino-fona/digital-out/digital-out.ino
+++ arduino-fona/digital-out/digital-out.ino
@@ -31,8 +31,13 @@
     while(1);
   }

-  // turn on GPRS
-  fona.enableGPRS(true);
+  fona.enableGPRS(false);
+  while(!fona.enableGPRS(true)) {
+    Serial.println(F("gprs init failed... trying again"));
+    delay(2000);
+  }
+
+  Serial.println(F("gprs enabled"));

 }


Delete beestation - Copy.ino

Delete beestation - Copy.ino

Delete unwanted cruft


correct typo

correct typo

--- udpEcho_151219/udpEcho_151219.ino
+++ udpEcho_151219/udpEcho_151219.ino
@@ -8,6 +8,8 @@
  */

 /*
+ * v0.2 2015 Dec. 25
+ *   - correct typo
  * v0.1 2015 Dec. 19
  *   can echo back
  *   - add loop()
@@ -42,7 +44,7 @@
   Serial.println(""); // to separate line
 }

-static void WiFi_printConectionInfo()
+static void WiFi_printConnectionInfo()
 {
   Serial.println("\nLocal IP=");
   Serial.println(WiFi.localIP());
@@ -53,7 +55,7 @@
 void setup() {
   Serial_setup();
   WiFi_setup();
-  WiFi_printConectionInfo();
+  WiFi_printConnectionInfo();
 }

 void loop()


AD7173-8.ino updated adc_data_mode

AD7173-8.ino updated adc_data_mode

--- AD7173-8.ino
+++ AD7173-8.ino
@@ -330,8 +330,8 @@
     }
     adc_data_mode = mode;
     /* write the specified value */
+    write_adc_register(ADCMODE_REG, adc_mode_value, 2);
     write_adc_register(IFMODE_REG, if_mode_value, 2);
-    write_adc_register(ADCMODE_REG, adc_mode_value, 2);
     /* return error code */
     return 0;
 }


as exhibited. Random travel after home. works on both eyes. As of commit, uploaded, running.

--- GooglyEyeArduino/GooglyEyeArduino.ino
+++ GooglyEyeArduino/GooglyEyeArduino.ino
@@ -53,8 +53,9 @@
   rotarySetup();
   rotaryHome();
   scream(1);
-  pickRoutine();
-  scream(2);
+  // pickRoutine();
+
+  // scream(2);
 }

 void pickRoutine(){
@@ -78,7 +79,7 @@
 void loop() {

-  // danceRandom(10000);
+  danceRandom(10000);
   // blockingGoHome();
   // delay(500);
   // // scream(4);
@@ -111,7 +112,7 @@

   while(millis()-start < duration) {
     if (gotThere) {
-      r = random(loLimitSteps,hiLimitSteps);
+      r = random(int(hiLimitSteps*0.2),hiLimitSteps);
       theta = random(0,8);
     }


Fixed big in camera trigger. GPIO inverted.

--- openlapse/openlapse.ino
+++ openlapse/openlapse.ino
@@ -3,7 +3,7 @@
  * Based on Sonoff-Tasmota by Theo Arends
 */

-#define VERSION                0x000100  // 0.1.0
+#define VERSION                0x000102  // 0.1.2

 enum log_t   {LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG_MORE, LOG_LEVEL_ALL};

@@ -435,7 +435,7 @@

 int pulse = 500;
-int pulse_d = 490;
+int pulse_d = 800;
 int interval = 500;
 int interval_d = 10;
 int frames = 20;
@@ -504,7 +504,7 @@
       sysCfg.timelapse_count++;
       Serial.printf("Shutter On %d\n", current);
       digitalWrite(LEDPIN, LOW);
-      digitalWrite(SHUTTERPIN, LOW);
+      digitalWrite(SHUTTERPIN, HIGH);
       if (sysCfg.timelapse_interval < (pulse_d + interval_d + sysCfg.timelapse_pulse))
         sysCfg.timelapse_interval = (pulse_d + interval_d + sysCfg.timelapse_pulse);
       next_state = current + sysCfg.timelapse_interval - (pulse_d + interval_d + sysCfg.timelapse_pulse);
@@ -514,7 +514,7 @@
     case SHUTTER_CLOSE:
       Serial.printf("Shutter Off %d\n", current);
       digitalWrite(LEDPIN, HIGH);
-      digitalWrite(SHUTTERPIN, HIGH);
+      digitalWrite(SHUTTERPIN, LOW);
       next_state = current + interval_d;
       break;


[tin_counter] little code tidy

[tin_counter] little code tidy


Sleep for longer

Sleep for longer

--- LoRa/LoRa_Garden_TX/LoRa_Garden_TX.ino
+++ LoRa/LoRa_Garden_TX/LoRa_Garden_TX.ino
@@ -33,7 +33,7 @@
 // Data wire is plugged into pin 6 on the Arduino
 #define ONE_WIRE_BUS 6

-#define WD_DO_STUFF 1 // How many watchdog interupts before doing real work.
+#define WD_DO_STUFF 2 // How many watchdog interupts before doing real work.

 // Singleton instance of the radio driver
 RH_RF95 rf95(RFM95_CS, RFM95_INT);
@@ -63,14 +63,14 @@
 ISR(WDT_vect) {
   wdt_disable();  // disable watchdog

-//  // Wake up by watchdog
-//  if (wd_isr == 0) {
-//      wd_isr = WD_DO_STUFF;
-//  } else {
-//      --wd_isr;
-//      // Go back to sleep.
-//      goToSleep();
-//  }
+  // Wake up by watchdog
+  if (wd_isr == 0) {
+      wd_isr = WD_DO_STUFF;
+  } else {
+      --wd_isr;
+      // Go back to sleep.
+      goToSleep();
+  }
 }

 void setup() {


removed iB now locally assigned

removed iB now locally assigned

--- cmdVsens/src/sketch.ino
+++ cmdVsens/src/sketch.ino
@@ -36,7 +36,6 @@
 unsigned long startTime;
 unsigned long elapsedTime;
 byte cmd = 0;
-byte iB = 0;

 void setup()
 {


Add LED functionality

Add LED functionality

--- iot/iot.ino
+++ iot/iot.ino
@@ -1,9 +1,12 @@
 #include <Servo.h>

-int LED_PIN = 13;
-int SERVO_PIN = 9;
-int BUTTON_PIN = 8;
-int SPEAKER_PIN = 6;
+const int LED_PIN = 13;
+const int SERVO_PIN = 9;
+const int BUTTON_PIN = 8;
+const int SPEAKER_PIN = 6;
+const int RED_LED_PIN = 12;
+const int GREEN_LED_PIN = 11;
+const int BLUE_LED_PIN = 10;

 Servo servo;
 int servo_pos = 90;
@@ -13,8 +16,11 @@
 void setup() {
   Serial.begin(9600);

-  // Initialize LED output
+  // Initialize LED outputs
   pinMode(LED_PIN, OUTPUT);
+  pinMode(RED_LED_PIN, OUTPUT);
+  pinMode(GREEN_LED_PIN, OUTPUT);
+  pinMode(BLUE_LED_PIN, OUTPUT);

   // Initialize button input
   pinMode(BUTTON_PIN, INPUT);
@@ -25,8 +31,12 @@
   // Initialize speaker
   pinMode(SPEAKER_PIN, OUTPUT);

+
+  rgbLED(255, 0, 0);
   beep(50);
+  rgbLED(0, 255, 0);
   beep(50);
+  rgbLED(0, 0, 255);
   beep(50);

   Serial.println("Setup complete");
@@ -90,18 +100,26 @@
     if (servo_state != 0) {
       Serial.println("Servo disabled");
       digitalWrite(LED_PIN, LOW);
+      rgbLED(255, 0, 0);
       beep(50);
       servo_state = 0;
     }
     else {
       Serial.println("Servo enabled");
       digitalWrite(LED_PIN, HIGH);
+      rgbLED(0, 255, 0);
       beep(50);
       servo_state = 1;
     }

     while (digitalRead(BUTTON_PIN) == HIGH);
   }
+}
+
+void rgbLED(int red, int green, int blue) {
+  analogWrite(RED_LED_PIN, red);
+  analogWrite(GREEN_LED_PIN, green);
+  analogWrite(BLUE_LED_PIN, blue);
 }

 void beep(unsigned char delayms) {
@@ -111,9 +129,3 @@
   delay(delayms);
 }

-
-
-
-
-
-