define定義名の干渉対策

define定義名の干渉対策

--- 2_example/example29u_dash/example29u_dash.ino
+++ 2_example/example29u_dash/example29u_dash.ino
@@ -70,13 +70,12 @@
 extern "C" {
 #include "user_interface.h"                 // ESP8266用の拡張IFライブラリ
 }
-#include <WiFiUdp.h>                        // UDP通信を行うライブラリ
 #include <FS.h>
 #define PIN_EN 13                           // IO 13 をLEDなどへ接続
 #define WAIT_A 10000                        // adash用の保持時間 10 秒
 #define WAIT_P 15000000                     // phone用の保持時間 4 時間 10分
 #define FILENAME "/adash.ini"               // 設定ファイル名
-#define SPIFFS                              // SPIFFS使用時に定義する
+#define SPIFFS_ON                           // SPIFFS使用時に定義する
 int PIN_HOLD=500;                           // 検出時の保持時間を設定(500ms)
 unsigned long reset_time;                   // LED消灯時刻
 char uart[33];                              // UART受信バッファ
@@ -180,7 +179,7 @@
     memset(phone,0,30);
     for(byte i=0;i<5;i++) adash_time[i]=0;
     for(byte i=0;i<5;i++) phone_time[i]=0;
-    #ifdef SPIFFS
+    #ifdef SPIFFS_ON
     while(!SPIFFS.begin()) delay(100);      // ファイルシステムの開始
     File file = SPIFFS.open(FILENAME,"r");  // 設定ファイルを開く
     if(!file){
@@ -328,7 +327,7 @@
                 }
             }
             if(!strncmp(uart,"save!",5)){   // 設定の保存
-                #ifdef SPIFFS
+                #ifdef SPIFFS_ON
                 File file = SPIFFS.open(FILENAME,"w");
                 if(file){
                     save(&file);


refactoring: move picking/running of letter/background patterns out into their own functions. blink less so patterns run more often.

--- CocaCola/CocaCola.ino
+++ CocaCola/CocaCola.ino
@@ -156,6 +156,7 @@
       delay(extended);
 		if (count + 1 != times || !endingWithLightsOn) {
 			backgroundOffInsideOut();
+	        delay(extended);
 		}
 	}
 }
@@ -172,10 +173,10 @@

 void insideOutOutsideInBackground() {
 	outsideInOnInsideOutOffBackground(random(2, 5), true);
-	delay(normal);
+	delay(ish);

 	insideOutOnOutsideInOffBackground(random(2, 5), false);
-	delay(normal);
+	delay(minimal);
 }

 void racingOnLeftToRightBackground() {
@@ -228,34 +229,56 @@
 	delay(normal);
 }

+// Randomness
+
+void runClassic() {
+    lettersOnLeftToRight();
+    classicBackground();
+}
+
+void runLetterPattern() {
+	// if new patterns are added, add a new case statement, and bump up the max random value by one
+	switch (random(0, 2)) {
+	case 0: { lettersOnLeftToRight(); break; }
+	case 1: { blinkLetters(random(5, 10)); break; }
+	default: { break; }
+	}
+}
+
+void runBackgroundPattern() {
+	switch(random(0, 4)) {
+	case 0: { classicBackground(); break; }
+	case 1: { insideOutOutsideInBackground(); break; }
+	case 2: { racingOnLeftToRightBackground(); break; }
+	case 3: { blinkBackground(random(5, 10)); backgroundAllOn(); break; }
+	}
+}
+
 // Arduino loop

 void loop() {
     allOff();

+	int blinkMax = 0;
 	int possibility = random(0, 100);
 	if (possibility < 70) {
-	    lettersOnLeftToRight();
-	    classicBackground();
+		runClassic();
+		blinkMax = 2;
 	} else if (possibility < 95) {
-		// if new patterns are added, add a new case statement, and bump up the max random value by one
-        switch (random(0, 2)) {
-       	case 0: { lettersOnLeftToRight(); break; }
-		case 1: { blinkLetters(random(5, 10)); break; }
-		default: { break; }
-		}
-
-		switch(random(0, 4)) {
-		case 0: { classicBackground(); break; }
-		case 1: { insideOutOutsideInBackground(); break; }
-		case 2: { racingOnLeftToRightBackground(); break; }
-		case 3: { blinkBackground(random(5, 10)); backgroundAllOn(); break; }
-		}
+		if (random(0, 10) == 0) {
+			runBackgroundPattern();
+			runLetterPattern();
+		} else {
+			runLetterPattern();
+			runBackgroundPattern();
+		}
+
+		blinkMax = 4
 	} else {
 		// super rare things
 	}

-   	blinkLetters(random(3, 7));
+   	blinkLetters(random(1, blinkMax));

    	lettersAllOff();


Fix heated grips parsing

Fix heated grips parsing

--- Event_Printer/Event_Printer.ino
+++ Event_Printer/Event_Printer.ino
@@ -182,9 +182,9 @@
     // HEATED GRIPS
     unsigned char hnibble8 = HI_NIBBLE(data[7]);
     Serial.print("Heated Grips: ");
-    if( hnibble8 == 0x0C ) Serial.print("OFF");
-    else if( hnibble8 == 0x0D ) Serial.print("LOW");
-    else if( hnibble8 == 0x0E ) Serial.print("HIGH");
+    if( hnibble8 == 0x0F ) Serial.print("OFF");
+    else if( hnibble8 == 0x0C ) Serial.print("LOW");
+    else if( hnibble8 == 0x0D ) Serial.print("HIGH");
     else Serial.print("ERROR-Other");
     Serial.println("");


Resolved #5 DTFM - sending commands in voice call

--- telephone/telephone.ino
+++ telephone/telephone.ino
@@ -99,7 +99,6 @@
       refreshButtons();
     }
     gsmVoiceCall.hangCall();
-    // ПРОВЕРИТЬ: когда трубку кладут "тут" и когда кладут "там".
     // ПРОВЕРИТЬ: когда занято.
   }
 }
@@ -111,7 +110,12 @@
   if (phoneNumber == "") {
     return;
   }
-  Serial.println("Sending digit: " + phoneNumber);
+
+  String atCommand = "AT+VTS=\"" + phoneNumber + "\"";
+  Serial.println("Sending digit: " + phoneNumber + " at command: " + atCommand);
+
+  theGSM3ShieldV1ModemCore.println(atCommand);
+
   phoneNumber = "";
 }


setNavThreshold() call fixed

setNavThreshold() call fixed

--- MtkGps/examples/gps_terminal/gps_terminal.ino
+++ MtkGps/examples/gps_terminal/gps_terminal.ino
@@ -90,7 +90,7 @@
 	gps.sendCommand(PMTK_SET_DGPS_MODE, PMTK_DGPS_WAAS);
 	if (nmea_echo) term.print("<%s\n", gps.cmd);
 	// set navigation speed threshold 0.2 m/s
-	gps.setNavThreshold(PMTK_NAV_THRESHOLD_OFF);
+	gps.setNavThreshold(PMTK_NAV_THRESHOLD_02);
 	if (nmea_echo) term.print("<%s\n", gps.cmd);
 	// request firmware release information
 	gps.sendCommand(PMTK_Q_RELEASE);


fix sd example returning bad json on empty folder

--- hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
+++ hardware/esp8266com/esp8266/libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
@@ -183,16 +183,15 @@
   server.setContentLength(CONTENT_LENGTH_UNKNOWN);
   server.send(200, "text/json", "");
   WiFiClient client = server.client();
-
+
+  server.sendContent("[");
   for (int cnt = 0; true; ++cnt) {
     File entry = dir.openNextFile();
     if (!entry)
     break;

     String output;
-    if (cnt == 0)
-      output = '[';
-    else
+    if (cnt > 0)
       output = ',';

     output += "{\"type\":\"";


added keydisplaydebug func

added keydisplaydebug func

--- Margoulineur2000.ino
+++ Margoulineur2000.ino
@@ -386,9 +386,12 @@
     Serial.println("Found an ISO14443A card");
     lcd.clear();
     lcd.print("I Found a card !");
-    Serial.print("  UID Length: ");Serial.print(nfc_handler.uidLength, DEC);Serial.println(" bytes");
+    Serial.print("  UID Length: ");
+    Serial.print(nfc_handler.uidLength, DEC);
+    Serial.println(" bytes");
     Serial.print("  UID Value: ");
-    for (uint8_t i = 0; i < nfc_handler.uidLength; i++) {
+    for (uint8_t i = 0; i < nfc_handler.uidLength; i++)
+    {
       Serial.print(nfc_handler.uid[i], HEX);
       Serial.print(' ');
     }
@@ -403,7 +406,8 @@
       for (nfc_handler.currentblock = 0; nfc_handler.currentblock < 64; nfc_handler.currentblock++)
       {
         // Check if this is a new block so that we can reauthenticate
-        if (nfc.mifareclassic_IsFirstBlock(nfc_handler.currentblock)) nfc_handler.authenticated = false;
+        if (nfc.mifareclassic_IsFirstBlock(nfc_handler.currentblock))
+            nfc_handler.authenticated = false;

         // If the sector hasn't been authenticated, do so first
         if (!nfc_handler.authenticated)
@@ -414,13 +418,11 @@

           if (nfc_handler.currentblock >= 5 * 4 && nfc_handler.currentblock <= 6 * 4)
           {
-            for (uint8_t i = 0; i < 6; i++)
-            {
-                Serial.print(" "); dormitory == 3 ?
-                Serial.print(nfc_handler.KeyA_D3_part2[i], HEX) :
-                Serial.print(nfc_handler.KeyA_D4[i], HEX);
-            }
-              nfc_handler.success = dormitory == 3 ?
+            //Key display debug
+            dormitory == 3 ?
+                displayKeyDebug(nfc_handler.KeyA_D3_part2) :
+                displayKeyDebug(nfc_handler.KeyA_D4);
+            nfc_handler.success = dormitory == 3 ?
               nfc.mifareclassic_AuthenticateBlock (nfc_handler.uid,
                 nfc_handler.uidLength,
                 nfc_handler.currentblock,
@@ -435,13 +437,11 @@
           }
           else
           {
-            for (uint8_t i = 0; i < 6; i++)
-            {
-                Serial.print(" "); dormitory == 3 ?
-                Serial.print(nfc_handler.KeyA_D3_part1[i], HEX) :
-                Serial.print(nfc_handler.KeyA_D4[i], HEX);
-            }
-              nfc_handler.success = dormitory == 3 ?
+            //Key display debug
+            dormitory == 3 ?
+                displayKeyDebug(nfc_handler.KeyA_D3_part1) :
+                displayKeyDebug(nfc_handler.KeyA_D4);
+            nfc_handler.success = dormitory == 3 ?
               nfc.mifareclassic_AuthenticateBlock (nfc_handler.uid,
                 nfc_handler.uidLength,
                 nfc_handler.currentblock,
@@ -524,6 +524,14 @@
   Serial.flush();
 }

+void            displayKeyDebug(byte *key)
+{
+    uint8_t     i = -1;
+
+    while (++i < 6)
+        Serial.print(key[i], HEX);
+}
+
 void wait4button()
 {
   while(digitalRead(encButton))


Update pubnub_linkit.ino

Update pubnub_linkit.ino

--- likitble/pubnub_linkit/pubnub_linkit.ino
+++ likitble/pubnub_linkit/pubnub_linkit.ino
@@ -1,210 +1,207 @@
-/*
- *SMART KITCHEN TRACKER                                        *
- */
-//Importing the BLE and Wifi Library for the Bluetooth and WiFi Communication
-#include <LGATT.h>
-#include <LWiFi.h>
-#include <LGATTUUID.h>
-#include <LGATTClient.h>
-#include <LWiFiClient.h>
-#include "SPI.h"
-#include "./PubNub.h"
-#include "settings.h"
-
-#define channel "kitchenDevice-resp"
-
-//Contant Variables to identify the containers
-const char *g_container1 = "001";
-const char *g_container2 = "002";
-unsigned int counter_container1 = 0;
-unsigned int counter_container2 = 0;
-boolean flag_container1 = 0;
-boolean flag_container2 = 0;
-
-//Function Prototypes
-void pubnubPublish(char *p_data);
-void prepare_json_data(const char *p_containerId,const char* p_weight);
-
-//Test UUID to begin the BLE communication
-static LGATTUUID test_uuid("B4B4B4B4-B4B4-B4B4-B4B4-B4B4B4B4B4B5");
-LGATTClient bleClient;
-LGATTDeviceInfo info = {0};
-
-//Number of Devices Scanned by the Linkit BLE
-volatile unsigned int g_numOfDevices = 0;
-char g_jsonResponse[26];
-float g_previous_weight_1,g_previous_weight_2,g_transient_weight_1,g_transient_weight_2;
-
-/*******************************************************************************************************
- Function Name            : prepare_json_data
- Description              : Prepares the json data to be published to the pubnub channel
- Parameters               : p_containerId,p_weight
-          p_containerId   : The Unique ID for the container
-          p_weight        : Present weight in the specfic container
- *******************************************************************************************************/
-void prepare_json_data(const char *p_containerId,const char* p_weight)
-{
-  strcat(g_jsonResponse,"{\"containerID\":\"");
-  strcat(g_jsonResponse,p_containerId);
-  strcat(g_jsonResponse,"\",\"weight\":");
-  strcat(g_jsonResponse,p_weight);
-  strcat(g_jsonResponse,"}");
-}
-/*******************************************************************************************************
- Function Name            : setup
- Description              : Initialize the Bluetooth and Connection WiFi to the local AP
-                            and scanning the available bluetooth connections
- Parameters               : None
- *******************************************************************************************************/
-void setup(void) {
-  Serial.begin(115200);
-  delay(3000);
-  //Connecting to the local AP using the SSID and Password
-  while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
-  {
-      Serial.println(" . ");
-      delay(1000);
-  }
-  //Initialize PubNub PUB SUB keys
-  PubNub.begin(pubkey, subkey);
-  //Connecting to the test UUID to establish the ble connection
-BLE_CONNECT:  if (bleClient.begin(test_uuid))
-  {
-    Serial.println("BLE Successfully Started");
-  }
-  else
-  {
-    Serial.println("Failed To Start BLE");
-    delay(0xffffffff);
-    goto BLE_CONNECT;
-  }
-  //Scan's the available ble advertisers
-  g_numOfDevices = bleClient.scan(10);
-}
-/*******************************************************************************************************
- Function Name            : loop
- Description              : Start the Conncection between the nodes and get the data and publish on
-                            pubnub.
- Parameters               : None
- *******************************************************************************************************/
-void loop(void) {
-  while (1)
-  {
-    if(g_numOfDevices == 0){
-      g_numOfDevices = bleClient.scan(10);
-      Serial.printf("Scanning Number of the Devices [%d]", g_numOfDevices);
-    }
-    else{
-      for (int i = 0; i < g_numOfDevices; i++)
-      {
-        bleClient.getScanResult(i, info);
-        if (!bleClient.connect(info.bd_addr)) // search all services till timeout or searching done.
-        {
-//            Serial.println("Failed to connect to the device");
-            delay(0xff);
-        }
-        else{
-//          Serial.println("Successfully Connection Esatablished");
-        }
-        long int l_starttime = millis();
-        while (1)
-        {
-          //Primary Service UUID for the GATT Service
-          LGATTUUID serviceUUID = 0XFFE0;
-          //Charterstic UUID to write the data to the client
-          LGATTUUID characteristicUUID = 0xFFE1;
-          LGATTAttributeValue attrValue;
-          boolean isPrimary;
-          bleClient.setupNotification(1,serviceUUID, isPrimary, characteristicUUID);
-          if((bleClient.queryNotification(serviceUUID, isPrimary, characteristicUUID,
-            attrValue))){
-              Serial.println((char *)attrValue.value);
-              //attValue.value contains the data that is received from the client ble
-              if(attrValue.len > 0){
-                float l_weight_1,l_weight_2;
-                char l_buf[10];
-                char l_buf1[10];
-                for(int i = 0; i<=3;i++){
-                  l_buf[i] = (char)attrValue.value[i+2];
-                  l_buf1[i] = (char)attrValue.value[i+9];
-                }
-                l_buf[4] = '\0';
-                l_buf1[4] = '\0';
-                l_weight_1 = atof(l_buf);
-                l_weight_2 = atof(l_buf1);
-                if((int)(g_previous_weight_1*1000) != (int)(l_weight_1*1000)){
-                  g_transient_weight_1 = l_weight_1;
-                  g_previous_weight_1 = l_weight_1;
-                  flag_container1 = 1;
-                  counter_container1 = 0;
-                }
-                else if((int)(g_transient_weight_1*1000) == (int)(l_weight_1*1000)){
-                  counter_container1++;
-                  if(counter_container1 == 3 && flag_container1 == 1){
-                    flag_container1 = 0;
-                    counter_container1 = 0;
-                    g_transient_weight_1 = 0;
-                    prepare_json_data(g_container1,l_buf);
-                    pubnubPublish(g_jsonResponse);
-                    memset(g_jsonResponse, 0, sizeof(g_jsonResponse));
-                  }
-                }
-                delay(500);
-                if((int)(g_previous_weight_2*1000) != (int)(l_weight_2*1000)){
-                  g_transient_weight_2 = l_weight_2;
-                  g_previous_weight_2 = l_weight_2;
-                  flag_container2 = 1;
-                  counter_container2 = 0;
-                }
-                else if((int)(g_transient_weight_2*1000) == (int)(l_weight_2*1000)){
-                  counter_container2++;
-                  if(counter_container2 == 3 && flag_container2 == 1){
-                    flag_container2 = 0;
-                    counter_container2 = 0;
-                    g_transient_weight_2 = 0;
-                    prepare_json_data(g_container2,l_buf1);
-                    pubnubPublish(g_jsonResponse);
-                    memset(g_jsonResponse, 0, sizeof(g_jsonResponse));
-                  }
-                }
-              }
-              Serial.println("Disconnect BLE Communication");
-              bleClient.disconnect(info.bd_addr);//Once the data is published disconnecting from the ble
-              delay(5000);
-              break;
-          }
-          else{
-            long int l_endtime = millis();
-            if(l_endtime - l_starttime > 1000){
-              break;
-            }
-          }
-        }
-      }
-    }
-    delay(2000);
-  }
-}
-/*******************************************************************************************************
- Function Name            : pubnubPublish
- Description              : Publish the data to the specfied channel
- Parameters               : p_data
-                p_data    : data to be published in the given channel
- *******************************************************************************************************/
-void pubnubPublish(char *p_data){
-  LWiFiClient *client;
-  client = PubNub.publish(channel,p_data);
-  if (!client) {
-      Serial.println("publishing error");
-      delay(1000);
-      return;
-  }
-  while (client->connected()) {
-      while (client->connected() && !client->available()); // wait
-      char c = client->read();
-      Serial.print(c);
-  }
-  client->stop();
-}
-//End of the Program
+/*
+ *SMART KITCHEN TRACKER                                        *
+ */
+//Importing the BLE and Wifi Library for the Bluetooth and WiFi Communication
+#include <LGATT.h>
+#include <LWiFi.h>
+#include <LGATTUUID.h>
+#include <LGATTClient.h>
+#include <LWiFiClient.h>
+#include "SPI.h"
+#include "./PubNub.h"
+#include "settings.h"
+
+#define channel "kitchenDevice-resp"
+
+//Contant Variables to identify the containers
+const char *g_container1 = "001";
+const char *g_container2 = "002";
+unsigned int counter_container1 = 0;
+unsigned int counter_container2 = 0;
+boolean flag_container1 = 0;
+boolean flag_container2 = 0;
+
+//Function Prototypes
+void pubnubPublish(char *p_data);
+void prepare_json_data(const char *p_containerId,const char* p_weight);
+
+//Test UUID to begin the BLE communication
+static LGATTUUID test_uuid("B4B4B4B4-B4B4-B4B4-B4B4-B4B4B4B4B4B5");
+LGATTClient bleClient;
+LGATTDeviceInfo info = {0};
+
+//Number of Devices Scanned by the Linkit BLE
+volatile unsigned int g_numOfDevices = 0;
+char g_jsonResponse[26];
+float g_previous_weight_1,g_previous_weight_2,g_transient_weight_1,g_transient_weight_2;
+
+/*******************************************************************************************************
+ Function Name            : prepare_json_data
+ Description              : Prepares the json data to be published to the pubnub channel
+ Parameters               : p_containerId,p_weight
+          p_containerId   : The Unique ID for the container
+          p_weight        : Present weight in the specfic container
+ *******************************************************************************************************/
+void prepare_json_data(const char *p_containerId,const char* p_weight)
+{
+  strcat(g_jsonResponse,"{\"containerID\":\"");
+  strcat(g_jsonResponse,p_containerId);
+  strcat(g_jsonResponse,"\",\"weight\":");
+  strcat(g_jsonResponse,p_weight);
+  strcat(g_jsonResponse,"}");
+}
+/*******************************************************************************************************
+ Function Name            : setup
+ Description              : Initialize the Bluetooth and Connection WiFi to the local AP
+                            and scanning the available bluetooth connections
+ Parameters               : None
+ *******************************************************************************************************/
+void setup(void) {
+  Serial.begin(115200);
+  delay(3000);
+  //Connecting to the local AP using the SSID and Password
+  while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
+  {
+      Serial.println(" . ");
+      delay(1000);
+  }
+  //Initialize PubNub PUB SUB keys
+  PubNub.begin(pubkey, subkey);
+  //Connecting to the test UUID to establish the ble connection
+BLE_CONNECT:  if (bleClient.begin(test_uuid))
+  {
+    Serial.println("BLE Successfully Started");
+  }
+  else
+  {
+    Serial.println("Failed To Start BLE");
+    delay(0xffffffff);
+    goto BLE_CONNECT;
+  }
+  //Scan's the available ble advertisers
+  g_numOfDevices = bleClient.scan(10);
+}
+/*******************************************************************************************************
+ Function Name            : loop
+ Description              : Start the Conncection between the nodes and get the data and publish on
+                            pubnub.
+ Parameters               : None
+ *******************************************************************************************************/
+void loop(void) {
+  while (1)
+  {
+    if(g_numOfDevices == 0){
+      g_numOfDevices = bleClient.scan(10);
+      Serial.printf("Scanning Number of the Devices [%d]", g_numOfDevices);
+    }
+    else{
+      for (int i = 0; i < g_numOfDevices; i++)
+      {
+        bleClient.getScanResult(i, info);
+        if (!bleClient.connect(info.bd_addr)) // search all services till timeout or searching done.
+        {
+//          Serial.println("Failed to connect to the device");
+            delay(0xff);
+        }
+        long int l_starttime = millis();
+        while (1)
+        {
+          //Primary Service UUID for the GATT Service
+          LGATTUUID serviceUUID = 0XFFE0;
+          //Charterstic UUID to write the data to the client
+          LGATTUUID characteristicUUID = 0xFFE1;
+          LGATTAttributeValue attrValue;
+          boolean isPrimary;
+          bleClient.setupNotification(1,serviceUUID, isPrimary, characteristicUUID);
+          if((bleClient.queryNotification(serviceUUID, isPrimary, characteristicUUID,
+            attrValue))){
+              Serial.println((char *)attrValue.value);
+              //attValue.value contains the data that is received from the client ble
+              if(attrValue.len > 0){
+                float l_weight_1,l_weight_2;
+                char l_buf[10];
+                char l_buf1[10];
+                for(int i = 0; i<=3;i++){
+                  l_buf[i] = (char)attrValue.value[i+2];
+                  l_buf1[i] = (char)attrValue.value[i+9];
+                }
+                l_buf[4] = '\0';
+                l_buf1[4] = '\0';
+                l_weight_1 = atof(l_buf);
+                l_weight_2 = atof(l_buf1);
+                if((int)(g_previous_weight_1*1000) != (int)(l_weight_1*1000)){
+                  g_transient_weight_1 = l_weight_1;
+                  g_previous_weight_1 = l_weight_1;
+                  flag_container1 = 1;
+                  counter_container1 = 0;
+                }
+                else if((int)(g_transient_weight_1*1000) == (int)(l_weight_1*1000)){
+                  counter_container1++;
+                  if(counter_container1 == 3 && flag_container1 == 1){
+                    flag_container1 = 0;
+                    counter_container1 = 0;
+                    g_transient_weight_1 = 0;
+                    prepare_json_data(g_container1,l_buf);
+                    pubnubPublish(g_jsonResponse);
+                    memset(g_jsonResponse, 0, sizeof(g_jsonResponse));
+                  }
+                }
+                delay(500);
+                if((int)(g_previous_weight_2*1000) != (int)(l_weight_2*1000)){
+                  g_transient_weight_2 = l_weight_2;
+                  g_previous_weight_2 = l_weight_2;
+                  flag_container2 = 1;
+                  counter_container2 = 0;
+                }
+                else if((int)(g_transient_weight_2*1000) == (int)(l_weight_2*1000)){
+                  counter_container2++;
+                  if(counter_container2 == 3 && flag_container2 == 1){
+                    flag_container2 = 0;
+                    counter_container2 = 0;
+                    g_transient_weight_2 = 0;
+                    prepare_json_data(g_container2,l_buf1);
+                    pubnubPublish(g_jsonResponse);
+                    memset(g_jsonResponse, 0, sizeof(g_jsonResponse));
+                  }
+                }
+              }
+              Serial.println("Disconnect BLE Communication");
+              bleClient.disconnect(info.bd_addr);//Once the data is published disconnecting from the ble
+              delay(5000);
+              break;
+          }
+          else{
+            long int l_endtime = millis();
+            if(l_endtime - l_starttime > 1000){
+              break;
+            }
+          }
+        }
+      }
+    }
+    delay(2000);
+  }
+}
+/*******************************************************************************************************
+ Function Name            : pubnubPublish
+ Description              : Publish the data to the specfied channel
+ Parameters               : p_data
+                p_data    : data to be published in the given channel
+ *******************************************************************************************************/
+void pubnubPublish(char *p_data){
+  LWiFiClient *client;
+  client = PubNub.publish(channel,p_data);
+  if (!client) {
+      Serial.println("publishing error");
+      delay(1000);
+      return;
+  }
+  while (client->connected()) {
+      while (client->connected() && !client->available()); // wait
+      char c = client->read();
+      Serial.print(c);
+  }
+  client->stop();
+}
+//End of the Program
 /*******************************************************************************************************************************/


findCylinder should work now

findCylinder should work now

(not getIndexOfLargestOpenInterval yet though)

--- Tests/Ping_findCylinder/Ping_findCylinder.ino
+++ Tests/Ping_findCylinder/Ping_findCylinder.ino
@@ -123,14 +123,11 @@
 // getIndexOfLargestOpenInterval to get a free new direction
 // to explore.
 int findCylinder(){
-  //stepsInFullTurn;
-  //measurements;
   const int l = stepsInFullTurn;

-  while(1){
+  while(true){
     int nearestIndex = getIndexMin();
-
-    if(nearestIndex = -1){
+    if(nearestIndex == -1){
       return getIndexOfLargestOpenInterval();
     }

@@ -138,17 +135,17 @@
     int iR = nextIndex(nearestIndex,l);
     int intervalLength = 0;

-    while(abs(measurements[iL])-abs(measurements[iR]) < 5){
+    while(abs(measurements[nearestIndex] - measurements[iL]) < 5){
       iL = prevIndex(iL,l);
       intervalLength++;
     }
-    while(abs(measurements[iR])-abs(measurements[iR]) < 5){
-      iR = prevIndex(iR,l);
+    while(abs(measurements[nearestIndex] - measurements[iR]) < 5){
+      iR = nextIndex(iR,l);
       intervalLength++;
     }

-    if(intervalLength < 5){
-      return (int)(iL+intervalLength/2) % intervalLength;
+    if(intervalLength <= 5){
+      return iL<iR ? (iL + iR)/2 : ((iL + iR+l)/2)%l;
     } else {
       for(int i=iL; i<iR; i++){
         noCylinder[i] = true;
@@ -156,14 +153,13 @@
     }
   }
 }
-
 // Index of the closest measured distance
 int getIndexMin(){
-  int minVal = 500;   //Max
+  int minVal = 500; //Max
   int iMinVal = -1;

   for(int i=0; i<stepsInFullTurn; i++){
-    if( !noCylinder[i] && (minVal > measurements[i]) ){
+    if( !noCylinder[i] && (measurements[i] < minVal) ){
       iMinVal = i;
       minVal = measurements[i];
     }


Additional message to the user

Additional message to the user

--- VSCP/examples/Sparkfun_CAN-BUS_Shield/Sparkfun_CAN-BUS_Shield.ino
+++ VSCP/examples/Sparkfun_CAN-BUS_Shield/Sparkfun_CAN-BUS_Shield.ino
@@ -138,6 +138,8 @@
     Serial.println("Failed to set CAN controller to normal mode!");

   } else {
+
+    Serial.println("CAN controller initialized successful.");

     // Node GUID - Used to unique identify nodes
     VSCPGuid  nodeGuid = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };


Added some debug code

Added some debug code

Mostly just added some debug serial.prints

--- ArduinoServoExample/ArduinoServoExample.ino
+++ ArduinoServoExample/ArduinoServoExample.ino
@@ -1,4 +1,3 @@
-#include <BitOps.h>
 #include <MaskNode.h>
 #include <MultiServoController.h>
 #include <PortMaskNode.h>
@@ -24,21 +23,52 @@
       servo2 = new Servo();

       // Attach a servo controller to pin 4.
-      DDRD |= DDRD | 1<<4;
-      attach(servo1, &PORTD, 1<<4);
+      DDRD |= DDRD | 1<<7;
+      attach(servo1, &PORTD, 1<<7);

       // Attach a servo controller to pins 5 and 6, (will control 2 servos as mirrors)
       DDRD |= DDRD | 1<<5 | 1<<6;
       attach(servo2, &PORTD, 1<<5 | 1<<6);

-      servo1->rotateTo(90);
+      servo1->maxVelocity(425);
+      servo1->rotateTo(0, 20);
+
       servo2->rotateTo(180);

       Serial.println("Setup Complete.");
       Serial.println(DDRD);
 }

+void printHex(int num, int precision) {
+	char tmp[16];
+	char format[128];
+
+	sprintf(format, "0x%%.%dX", precision);
+
+	sprintf(tmp, format, num);
+	Serial.println(tmp);
+}
+
 void loop(){
+
+  // int currentAngle =  atoi(servo1->currentAngle());
+  // int currentPulse =  atoi(servo1->currentPulse());
+            Serial.print("current angle: "); Serial.println(servo1->currentAngle(), DEC);
+            Serial.print("current pulse: "); printHex(servo1->currentPulse(), 8);
+            Serial.print("destination angle: "); Serial.println(servo1->destinationAngle());
+            Serial.print("next angle: "); Serial.println(servo1->nextAngle());
+            Serial.print("max velocity: ");  printHex(servo1->maxVelocity(), 8);
+            Serial.print("destination angle: "); Serial.println(servo1->destinationAngle());
+            Serial.print("is limited: "); Serial.println(servo1->isLimited());
+
+//            Serial.println(servo1->currentPulse(), HEX);
+         //   Serial.print("current pulse: ");
+         //   Serial.println(currentPulse);
+/*  if(servo1->currentAngle() <= 0)
+    servo1->rotateTo(180);
+  else if(servo1->currentAngle() >= 180)
+    servo1->rotateTo(0);*/
+

   if(Serial.available() > 0){
       serialValue = Serial.read();


don't change to screen saver until we have a strong signal. broadcast IR channel while there is a weak signal

--- src/rx5808-pro-diversity/rx5808-pro-diversity.ino
+++ src/rx5808-pro-diversity/rx5808-pro-diversity.ino
@@ -112,6 +112,7 @@
 uint8_t seek_direction=1;
 unsigned long time_of_tune = 0;        // will store last time when tuner was changed
 unsigned long time_screen_saver = 0;
+unsigned long time_next_payload = 0;
 uint8_t last_active_channel=0;
 uint8_t seek_found=0;
 uint8_t last_dip_channel=255;
@@ -508,11 +509,12 @@
         drawScreen.screenSaver(pgm_read_byte_near(channelNames + channelIndex), pgm_read_word_near(channelFreqTable + channelIndex));
 #endif
         do{
-            //delay(10); // timeout delay
-#ifdef USE_DIVERSITY
-            drawScreen.updateScreenSaver(active_receiver, readRSSI(), readRSSI(useReceiverA), readRSSI(useReceiverB));
+            rssi = readRSSI();
+
+#ifdef USE_DIVERSITY
+            drawScreen.updateScreenSaver(active_receiver, rssi, readRSSI(useReceiverA), readRSSI(useReceiverB));
 #else
-            drawScreen.updateScreenSaver(readRSSI());
+            drawScreen.updateScreenSaver(rssi);
 #endif

         }
@@ -578,8 +580,9 @@
         if(state == STATE_MANUAL) // MANUAL MODE
         {
 #ifdef USE_IR_EMITTER
-            if(millis() % 1000 == 0 && rssi < 20) { // send channel info every second until rssi is locked.
+            if(time_next_payload+1000 < millis() && rssi <= 20) { // send channel info every second until rssi is locked.
                 sendIRPayload();
+                time_next_payload = millis();
             }
 #endif
             // handling of keys
@@ -676,7 +679,8 @@
             }
         }
 #ifndef TVOUT_SCREENS
-        if(time_screen_saver+5000 < millis() && time_screen_saver!=0) {
+        // change to screensaver after lock and 5 seconds has passed.
+        if(time_screen_saver+5000 < millis() && time_screen_saver!=0 && rssi > 20) {
             state = STATE_SCREEN_SAVER;
         }
 #endif
@@ -1072,6 +1076,10 @@

 #ifdef USE_IR_EMITTER
 void sendIRPayload() {
+    // beep twice before transmitting.
+    beep(100);
+    delay(100);
+    beep(100);
     uint8_t check_sum = 2;
     Serial.write(2); // start of payload
     check_sum += channelIndex;


fixed bug in sendAndWait()

fixed bug in sendAndWait()

--- tictactoe/tictactoe.ino
+++ tictactoe/tictactoe.ino
@@ -464,6 +464,7 @@
   //If ack -> notReceived = false
   //If wait_for_rival -> delay 1000
   String res = sendAndWait(MSG_DO_MOVE + SEP_CHAR_COMMANDS + player_id + SEP_CHAR_PARAMETERS  + player_move +  END_CHAR);
+  Serial.println("Reply: '" + res + "'");
   String command = getCommand(res);
   while(notReceived){
     if (command.startsWith(CMD_ACK)){
@@ -474,9 +475,14 @@
       Serial.println("Waiting for the rival to retrieve previous move...");
       delay(1000);
       res = sendAndWait(MSG_DO_MOVE + SEP_CHAR_COMMANDS + player_id + SEP_CHAR_PARAMETERS  + player_move +  END_CHAR);
+      Serial.println("Reply: '" + res + "'");
       command = getCommand(res);
     } else {
-      Serial.println("Unknown command");
+      Serial.println("Unknown command: '" + command + "'");
+      delay(1000);
+      res = sendAndWait(MSG_DO_MOVE + SEP_CHAR_COMMANDS + player_id + SEP_CHAR_PARAMETERS  + player_move +  END_CHAR);
+      Serial.println("Reply: '" + res + "'");
+      command = getCommand(res);
     }
   }
 }
@@ -484,16 +490,22 @@
 void sendMsg(String msg){
   Serial1.print(msg);
 }
+
 String sendAndWait(String msg){
   Serial1.print(msg);
-
+
   // Wait for the reply
   String res = "";
-  while (Serial1.available()){
+  while (true){
+    if (Serial1.available()){
       char data = Serial1.read();
       res += data;
-    }
-
+      if (data == '\r'){
+        break;
+      }
+    }
+  }
+
   return res;
 }


wrong boolean logic

wrong boolean logic

--- src/analog_sensors_board.ino
+++ src/analog_sensors_board.ino
@@ -292,7 +292,7 @@
         if(motors_enabled) {
             // send priority alert
             Serial.print("$MOTOR,");
-            Serial.println(motors_enabled, DEC);
+            Serial.println(!motors_enabled, DEC);
         }

         motors_enabled = false;


added Wire library and general concepts

added Wire library and general concepts

--- Testbench/Motor_Shield_Testbench/MotorShieldTestBench_Master/MotorShieldTestBench_Master.ino
+++ Testbench/Motor_Shield_Testbench/MotorShieldTestBench_Master/MotorShieldTestBench_Master.ino
@@ -1,20 +1,27 @@
 #include <Wire.h>

 const int rightDir = 19;
-const int rightSpeed = 20;
+const int rSpeed = A8;
 const int leftDir = 18;
-const int leftSpeed = 21;
+const int lSpeed = A9;
+const int led = 78;
+
+boolean consistent = true;
+
+double leftSpeed[11];
+double rightSpeed[11];

 const int select = 42;

-boolean dir = true;
+boolean dirR[11];
+boolean dirL[11];

 const float wheelCirc = 1.092;
 const float ticks = 6000;
 const float ticksPerM = ticks / wheelCirc;
-float desiredSpeed = 2;
-
-float f = desiredSpeed * ticksPerM;
+const float ticksPerMile = ticksPerM * 1609.34;
+int desiredSpeedL[11] = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5};
+int desiredSpeedR[11] = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5};

 void setup()
 {
@@ -23,13 +30,63 @@
   Wire.begin();

   pinMode(rightDir, INPUT);
-  pinMode(rightSpeed, INPUT);
+  pinMode(rSpeed, INPUT);
   pinMode(leftDir, INPUT);
-  pinMode(leftSpeed, INPUT);
+  pinMode(lSpeed, INPUT);

+  pinMode(select, OUTPUT);
+  digitalWrite(select, HIGH);
 }

 void loop()
 {
+  for (int i = 0; i < 11; i ++)
+  {
+    if (desiredSpeedR[i] < 0)
+    {
+      digitalWrite(select, LOW);
+    }
+    Wire.beginTransmission(7);
+    Wire.write(abs(desiredSpeedL[i] * 100 * ticksPerMile));
+    Wire.endTransmission();
+
+    Wire.beginTransmission(8);
+    Wire.write(abs(desiredSpeedR[i] * 100 * ticksPerMile));
+    Wire.endTransmission();
+
+    delay(1000);

+    dirL[i] = digitalRead(leftDir);
+    dirR[i] = digitalRead(rightDir);
+    leftSpeed[i] = analogRead(lSpeed);
+    rightSpeed[i] = analogRead(rSpeed);
+
+    digitalWrite(select, HIGH);
+  }
+
+  for (int i = 0; i < 11; i ++)
+  {
+    if (abs(leftSpeed[i] - desiredSpeedL[i]) >= 0.1)
+    {
+      consistent = false;
+    }
+  }
+
+  if (consistent)
+  {
+    digitalWrite(led, HIGH);
+    delay(1000);
+    digitalWrite(led, LOW);
+    delay(1000);
+  }
+  else
+  {
+    digitalWrite(led, HIGH);
+    delay(100);
+    digitalWrite(led, LOW);
+    delay(100);
+    digitalWrite(led, HIGH);
+    delay(100);
+    digitalWrite(led, LOW);
+  }
 }


scale / checking poop

scale / checking poop

--- _03-hx711-scale/_03-hx711-scale-v3-adaptor/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
+++ _03-hx711-scale/_03-hx711-scale-v3-adaptor/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
@@ -117,8 +117,9 @@

 void check_blank()
 {
-  for (int i = 0; i < 10; ++i) {
+  for (int i = 0; i < 15; i++) {
     int blank_measured = requestHX711();
+    if ( blank_measured > 300 ) { return ; }
     digitalWrite(ledPin, HIGH);
     ave.push(blank_measured);
     delay(500);
@@ -129,34 +130,53 @@
   blank_checked = HIGH;
   Serial.print("blank_checked : ");
   Serial.println(measured_blank);
-}
-
-void check_blank_again()
+
+  payload = "{\"WeightBlank\":";
+  payload += measured_blank;
+  payload += "}";
+
+  sendHx711toMqtt(payload, topicEvery);
+
+}
+
+void check_poop()
 {
-  for (int i = 0; i < 10; ++i) {
-    int blank_measured = requestHX711();
-    if ( blank_measured > 500 ) { return; }
-    delay(1000);
-  }
-  measured_blank = int(ave.mean());
-  Serial.print("blank_checked : ");
-  Serial.println(measured_blank);
+  for (int i = 0; i < 15; i++) {
+    int poop_measured = requestHX711();
+    digitalWrite(ledPin, HIGH);
+    ave.push(poop_measured);
+    delay(500);
+    digitalWrite(ledPin, LOW);
+    delay(500);
+  }
+
+  measured_poop = int(ave.mean());
+  Serial.print("poop_checked : ");
+  Serial.println(measured_poop);
+
+  payload = "{\"WeightPoop\":";
+  payload += measured_poop;
+  payload += "}";
+
+  sendHx711toMqtt(payload, topicEvery);
+
 }

 void loop() {
   if ( blank_checked == LOW ) {
-    check_blank();
+        delay(5000);
+        check_blank();
   }

   inuse = digitalRead(nemoisOnPin);
   measured = requestHX711();
   if ( inuse == HIGH ) {
     digitalWrite(ledPin, HIGH);
-    if (( measured > 500 ) && ( measured < 10000 ))
+    if ( measured > 20 )
     {
       ave.push(measured);

-      if ( ((ave.maximum() - ave.minimum()) < 100 ) && ( ave.stddev() < 50) && ( nofchecked > 10 ) && ( ave.mean() > 1000 ) && ( ave.mean() < 10000 ) && ( AvgMeasuredIsSent == LOW ) )
+      if ( ((ave.maximum() - ave.minimum()) < 50 ) && ( ave.stddev() < 20) && ( nofchecked > 15 ) && ( ave.mean() > 1000 ) && ( ave.mean() < 10000 ) && ( AvgMeasuredIsSent == LOW ) )
       {
         payload = "{\"WeightAvg\":";
         payload += int(ave.mean());
@@ -174,34 +194,16 @@
   } else {
     digitalWrite(ledPin, LOW);
     if ( AvgMeasuredIsSent == HIGH ) {
-      delay(2000);
-      for (int i = 0; i < 10; ++i) {
-        digitalWrite(ledPin, HIGH);
-        ave.push(requestHX711());
-        delay(500);
-        digitalWrite(ledPin, LOW);
-        delay(500);
-      }
-
-      measured_poop = int(ave.mean());
-
-      Serial.print("measured_poop : ");
-      Serial.println(measured_poop);
-
-      payload = "{\"Weightpoop\":";
-      payload += (measured_poop - measured_blank);
-      payload += "}";
-
-      sendHx711toMqtt(payload, topicEvery);
-    }
-
-    measured       = 0;
+        check_poop();
+    }
+    measured          = 0;
+    nofchecked        = 0;
     AvgMeasuredIsSent = LOW;
-
-    if ( nofchecked > 600 ) {
-      nofchecked     = 0;
-      check_blank_again();
-    }
+  }
+
+  if ( nofchecked > 6000 ) {
+    nofchecked     = 0;
+    blank_checked = LOW;
   }

   nofchecked++;


Motion sensor

Motion sensor

--- ESP-Logger/ESP-Logger.ino
+++ ESP-Logger/ESP-Logger.ino
@@ -7,19 +7,22 @@
 #define DHTPIN D2
 #define FANPIN D6
 #define LIGHTPIN D5
+#define SENSORPIN D8
 #define DHTTYPE DHT11
 #define DELAY_TIME_TO_SEND  5000 // 15 min
-#define TABLE_NAME "leitura"
+#define TABLE_LEITURA "leitura"
+#define TABLE_MOTION "motion"
 #define CLIENT_EMAIL "well.oliveira.snt@gmail.com"
 #define DEVICE_PATH "/devices/mkW3jbNvyKMzC8FLODaQd7GAum02/"

 DHT dht(DHTPIN, DHTTYPE);

-StaticJsonBuffer<1000> jsonBuffer;
-JsonObject &root = jsonBuffer.createObject();
+StaticJsonBuffer<2000> jsonBuffer;
+JsonObject &leitura = jsonBuffer.createObject();
+JsonObject &motion = jsonBuffer.createObject();

-void inline readDataToSend();
-void inline setLeitura(String temperatura, String umidade, String cliente, String data);
+int count = 15000;
+bool motionSensorRead = false;

 void setup() {
     Serial.begin(9600);
@@ -39,49 +42,38 @@
     pinMode(LED_BUILTIN, OUTPUT);
     pinMode(FANPIN, OUTPUT);
     pinMode(LIGHTPIN, OUTPUT);
-    digitalWrite(LED_BUILTIN, !Firebase.getBool(String(DEVICE_PATH) + "light"));
-}
-
-String errorToPrint = String(TABLE_NAME) + " failed to send:";
-
-int count = 15000;
-
-void loop() {
-
-    Serial.print(count);
-
-    count++;
-    if(count > 1500) {
-        WiFi.hostByName(ntpServerName, timeServer);
-        setSyncProvider(getNtpTime);
-        setSyncInterval(300);
-        readDataToSend();
-        delay(100);
-        count = 0;
-        Firebase.push(TABLE_NAME, root);
-    } else {
-        delay(100);
-    }
-
-    if (Firebase.failed()) {
-        Serial.print(errorToPrint);
-        Serial.println(Firebase.error());
-        return;
-    }
-
-    Serial.println(Firebase.getBool(String(DEVICE_PATH) + "light"));
-
-    digitalWrite(FANPIN, !Firebase.getBool(String(DEVICE_PATH) + "fan"));
-    digitalWrite(LIGHTPIN, !Firebase.getBool(String(DEVICE_PATH) + "light"));
+    pinMode(SENSORPIN, INPUT);
+    motionSensorRead = !digitalRead(SENSORPIN);
     digitalWrite(LED_BUILTIN, !Firebase.getBool(String(DEVICE_PATH) + "light"));

 }

+inline String getErrorString(String table) {
+    return String(TABLE_LEITURA) + " failed to send:";
+}
+
+void inline updateMontionSensor() {
+    if (digitalRead(SENSORPIN) != motionSensorRead) {
+        motionSensorRead = digitalRead(SENSORPIN);
+        motion["state"] = String(motionSensorRead);
+        motion["date"] = getEpoch();
+        Firebase.push(TABLE_MOTION, motion);
+        Serial.println("sensor=" + String(motionSensorRead));
+        delay(1000);
+    }
+
+    if (Firebase.failed()) {
+        Serial.print(getErrorString(TABLE_MOTION));
+        Serial.println(Firebase.error());
+        return;
+    }
+}
+
 void inline setLeitura(String temperatura, String umidade, String cliente, String data) {
-    root["temperatura"] = temperatura;
-    root["umidade"] = umidade;
-    root["cliente"] = cliente;
-    root["data"] = data;
+    leitura["temperatura"] = temperatura;
+    leitura["umidade"] = umidade;
+    leitura["cliente"] = cliente;
+    leitura["data"] = data;
 }

 void inline readDataToSend() {
@@ -94,3 +86,41 @@
     setLeitura(temperatura, umid, cliente, data);
     Serial.println("temp=" + temperatura + " umid=" + umid + " clnt=" + cliente + " dateTime=" + data);
 }
+
+void inline updateLeitura() {
+    if (count > 1500) {
+        readDataToSend();
+        count = 0;
+        Firebase.push(TABLE_LEITURA, leitura);
+    }
+
+    if (Firebase.failed()) {
+        Serial.print(getErrorString(TABLE_LEITURA));
+        Serial.println(Firebase.error());
+        return;
+    }
+}
+
+void inline updateLighAndFan() {
+    digitalWrite(FANPIN, !Firebase.getBool(String(DEVICE_PATH) + "fan"));
+    digitalWrite(LIGHTPIN, !Firebase.getBool(String(DEVICE_PATH) + "light"));
+    digitalWrite(LED_BUILTIN, !Firebase.getBool(String(DEVICE_PATH) + "light"));
+}
+
+
+void loop() {
+
+    WiFi.hostByName(ntpServerName, timeServer);
+    setSyncProvider(getNtpTime);
+    setSyncInterval(300);
+
+    updateMontionSensor();
+
+    updateLeitura();
+
+    updateLighAndFan();
+
+    count++;
+    delay(100);
+    Serial.println(count);
+}


alarm now blinks stop function instead

alarm now blinks stop function instead

--- vibrate_alarm_clock.ino
+++ vibrate_alarm_clock.ino
@@ -91,17 +91,17 @@

     display.clearDisplay();

-    boolean blinkOnForSetting = shouldBlinkNow();
+    boolean blinkOn = shouldBlinkNow();

     int voltageADCReading = analogRead(VOLTAGE_MEASURE_PIN);
      //Multiply 2 as we are are using a half voltage divider
     int batteryMilliVolt = ((float) voltageADCReading / ADC_PRECISION) * 2 * VOLTAGE_OF_VCC_MV;

-    writeDateTimeToDisplayBuffer(now, blinkOnForSetting);
-    writeAlarmToDisplayBuffer(blinkOnForSetting);
+    writeDateTimeToDisplayBuffer(now, blinkOn);
+    writeAlarmToDisplayBuffer(blinkOn);
     writeVoltageToDisplayBuffer(batteryMilliVolt);
-    writeButtonStateToDisplayBuffer();
+    writeButtonStateToDisplayBuffer(blinkOn);

     display.display();
@@ -249,12 +249,18 @@
 }

-void writeButtonStateToDisplayBuffer(){
+void writeButtonStateToDisplayBuffer(boolean blinkOn){

   String buttonFunction;
   switch(currentState)
   {
-    case ALARM: buttonFunction = "Stop     Stop    Stop";
+    case ALARM:
+    {
+      if(!blinkOn){
+        buttonFunction = "Stop     Stop    Stop";
+      }
+
+    }
     break;
     case NORMAL : buttonFunction =  "OLED    Alarm    Time";
     break;
@@ -387,10 +393,7 @@
     }

     String alarmTimeString;
-    if(currentState == ALARM && !blinkOn){
-      alarmTimeString = "              ";
-    } else {
-       String alarmSetting;
+    String alarmSetting;

     if(currentState == SETTING_ALARM && settingAlarmProcess == A_TYPE && !blinkOn){
      //Now setting this, do not show
@@ -408,7 +411,7 @@
      }

       alarmTimeString = alarmHourString + ":" + alarmMinuteString + alarmSetting;
-    }
+


ARDUINO CODE: Cleaned up the code, added some comments. Removed the hard coded 10 samples and made it an adjustable variable.

--- ArduinoFiles/sketch/sketch.ino
+++ ArduinoFiles/sketch/sketch.ino
@@ -26,23 +26,22 @@
 uint32_t ulTHR_Start;
 uint32_t ulRUD_Start;
 uint32_t ulAUX_Start;
-  int minJoy = 1076;
-  int divJoy = 38;
-  int maxJoy = 1936;
-  int count = 0;
-  String output = "";
+
+int sampleRate = 10;
+int samples = 0;
+String output = "";

-  int16_t Rud = 0;
-  int16_t Ail = 0;
-  int16_t Thr = 0;
-  int16_t Ele = 0;
-  int16_t Aux = 0;
-
+int16_t sampleRud = 0;
+int16_t sampleAil = 0;
+int16_t sampleThr = 0;
+int16_t sampleEle = 0;
+int16_t sampleAux = 0;
+
 void setup()
 {
-  Serial.begin(9600);
+  Serial.begin(9600); // SERIALLLLLLLLL....

-
+  // setup the interrupt pins
   PCintPort::attachInterrupt(AIL_IN_PIN, isr_AIL, CHANGE);
   PCintPort::attachInterrupt(ELE_IN_PIN, isr_ELE, CHANGE);
   PCintPort::attachInterrupt(THR_IN_PIN, isr_THR, CHANGE);
@@ -63,9 +62,7 @@
   if (bUpdateFlagsShared)
   {
     noInterrupts();
-
     bUpdateFlags = bUpdateFlagsShared;
-
     if (bUpdateFlags & AIL_FLAG)
     {
       unAIL_In = unAIL_InShared;
@@ -88,31 +85,29 @@
     }

     bUpdateFlagsShared = 0;
-
-     bUpdateFlags = 0;
+    bUpdateFlags = 0;
     interrupts();

-    if (count == 10) {
-      output = String(Thr/10) + ",";
-      output += String(Rud/10) + ",";
-      output += String(Ele/10) + ",";
-      output += String(Ail/10) + ",";
-      output += String(Aux/10) + "\n";
-    Serial.print(output);
-    count = 0;
-    Rud = 0;
-    Ail = 0;
-    Thr = 0;
-    Ele = 0;
-    Aux = 0;
-    output = "";
+    if (samples == sampleRate) { // build the output string if enough samples have been collected
+      output = String(sampleThr/sampleRate) + ",";
+      output += String(sampleRud/sampleRate) + ",";
+      output += String(sampleEle/sampleRate) + ",";
+      output += String(sampleAil/sampleRate) + ",";
+      output += String(sampleAux/sampleRate) + "\n";
+      Serial.print(output); // send the output
+      samples = 0; // reset all the variables
+      sampleRud = 0;
+      sampleAil = 0;
+      sampleThr = 0;
+      sampleEle = 0;
+      sampleAux = 0;
     } else {
-      Thr+=unTHR_In;
-      Rud+=unRUD_In;
-      Ele+=unELE_In;
-      Ail+=unAIL_In;
-      Aux+=unAUX_In;
-      count++;
+      sampleThr+=unTHR_In; // add samples to the collections
+      sampleRud+=unRUD_In;
+      sampleEle+=unELE_In;
+      sampleAil+=unAIL_In;
+      sampleAux+=unAUX_In;
+      samples++;
     }
   }
 }


logs format changed

logs format changed

--- src/sonoff-webserver.ino
+++ src/sonoff-webserver.ino
@@ -6,7 +6,7 @@
 */

 void startHttpServer() {
-  if (Configuration.debugger) Serial << endl << " - Starting web server" << endl;
+  if (Configuration.debugger) Serial << endl << "INFO: Starting web server";
   server.on("/", handleRoot);
   server.on("/configure", handleConfiguration);
   server.on("/reboot", handleReboot);
@@ -16,12 +16,11 @@
   server.onNotFound(handleNotFound);
   httpUpdater.setup(&server);
   server.begin();
-  if (Configuration.debugger) Serial << " - Web server is working" << endl;
+  if (Configuration.debugger) Serial << endl << "INFO: Web server is working";
 }

 void handleRoot() {
-  if (Configuration.debugger) Serial << "Server: root requested" << endl;
-  if (Configuration.debugger) Serial << Configuration.language[0];
+  if (Configuration.debugger) Serial << endl << "INFO: HTTPD Main page requested";
   String page =
     "
";page+=Configuration.language[0]==101?"Device information":"Informacje o urządzeniu";page+="
"
     "
"
@@ -150,7 +149,7 @@

 void handleConfiguration() {

-  if (Configuration.debugger) Serial << "Server: configuration" << endl;
+  if (Configuration.debugger) Serial << endl << "INFO: HTTPD Configuration requested";

   String page =
     "<form action=\"/save\"  method=\"post\">"
@@ -334,7 +333,7 @@
   Led.stopBlinking();
   Led.on();

-  if (Configuration.debugger) Serial << "Server: saving data" << endl;
+  if (Configuration.debugger) Serial << endl << "INFO: HTTPD Data saving";

   if (server.arg("device_name").length() > 0) {
     Eeprom.saveDeviceName(server.arg("device_name"));
@@ -441,7 +440,7 @@
 }

 void handleUpgrade() {
-    if (Configuration.debugger) Serial << "Server: upgrade" << endl;
+    if (Configuration.debugger) Serial << endl << "INFO: HTTPD Firmware upgrade" ;
     String page =
       "
";page+=Configuration.language[0]==101?"Firmware upgrade":"Aktualizacja oprogramowania";page+="
"
       "
"
@@ -475,23 +474,23 @@
 }

 void handleNotFound() {
-  if (Configuration.debugger) Serial << "Server: page not found" << endl;
+  if (Configuration.debugger) Serial <<  endl << "WARN: HTTPD Page not found";

   String page =
     "
"
     "
";page+=Configuration.language[0]==101?"Error":"Błąd";page+=" 404: ";page+=Configuration.language[0]==101?"Page Not Found":"Strona nie została odnaleziona";page+=".
"
     "
";

-  if (Configuration.debugger) Serial << server.uri() << " " << server.args() << endl;
+  if (Configuration.debugger) Serial <<  endl << "INFO: HTTPD " << server.uri() << " " << server.args();

   for (uint8_t i = 0; i < server.args(); i++) {
-   if (Configuration.debugger) Serial <<  server.argName(i) << ": " << server.arg(i) << endl;
+   if (Configuration.debugger) Serial << endl << "INFO: HTTPD " << server.argName(i) << ": " << server.arg(i);
   }
   generatePage(page,true,0);
 }

 void handleReboot() {
-  if (Configuration.debugger) Serial << "Server: rebooting device" << endl;
+  if (Configuration.debugger) Serial << endl << "WARN: HTTPD Rebooting device";
   String page =
     "
"
     "
";page+=Configuration.language[0]==101?"Rebooting is in progress":"Trwa restart";page+="
"


Added clear endpoint and documentation

Added clear endpoint and documentation

--- HMTL_Module/HMTL_Module.ino
+++ HMTL_Module/HMTL_Module.ino
@@ -239,9 +239,13 @@
     wfb.configureAccessPoint("HMTL_Module", "12345678");
     wfb.startup();

-    wfb.addRESTEndpoint("/rgb", rgbHandler);
-    wfb.addRESTEndpoint("/circular", circularHandler);
-    wfb.addRESTEndpoint("/sparkle", sparkleHandler);
+    wfb.addRESTEndpoint("/clear", clearHandler, "\"description\":\"clear all patterns\"");
+    wfb.addRESTEndpoint("/rgb", rgbHandler,
+                        "\"description\":\"set to a single color\",\"args\":[\"r\",\"g\",\"b\"]");
+    wfb.addRESTEndpoint("/circular", circularHandler,
+                        "\"description\":\"run circular pattern\",\"args\":[\"pattern\",\"length\",\"period\"]");
+    wfb.addRESTEndpoint("/sparkle", sparkleHandler,
+                        "\"description\":\"run sparkle pattern\",\"args\":[\"r\",\"g\",\"b\",\"threshold\",\"bg\",\"hum_min\",\"hue_max\",\"sat_min\",\"sat_max\",\"val_min\",\"val_max\"]");

     tcpSocket.init(config.address, HMTL_PORT);
     tcpSocket.initBuffer(wifi_data_buffer, WIFI_SEND_BUFFER_SIZE);
@@ -287,6 +291,21 @@
 #endif

 #if defined(ESP32)
+
+void clearHandler() {
+  WebServer *server = wfb.getServer();
+
+  DEBUG3_PRINTLN("/clear");
+
+  hmtl_program_cancel_fmt(sockets[0]->send_buffer,
+                          sockets[0]->send_data_size,
+                          config.address, HMTL_ALL_OUTPUTS);
+  msg_hdr_t *msg = (msg_hdr_t *)sockets[0]->send_buffer;
+  handler.process_msg(msg, sockets[0], NULL, &config);
+
+  server->send(200, "application/json", "ok");
+}
+
 void circularHandler() {
   WebServer *server = wfb.getServer();

@@ -405,24 +424,19 @@
   WebServer *server = wfb.getServer();

   uint8_t rgb[3];
-
-  if (server->args() < 3) {
-    wfb.getServer()->send(400, "application/json", "insufficient args");
-    return;
-  }
-
-  rgb[0] = server->arg("red").toInt();
-  rgb[1] = server->arg("green").toInt();
-  rgb[2] = server->arg("blue").toInt();
+  rgb[0] = server->hasArg("r") ? server->arg("r").toInt() : 0;
+  rgb[1] = server->hasArg("g") ? server->arg("g").toInt() : 0;
+  rgb[2] = server->hasArg("b") ? server->arg("b").toInt() : 0;

   DEBUG3_VALUE("/rgb r:", rgb[0]);
-  DEBUG3_VALUE("g:", rgb[1]);
-  DEBUG3_VALUELN("b:", rgb[2]);
+  DEBUG3_VALUE(" g:", rgb[1]);
+  DEBUG3_VALUELN(" b:", rgb[2]);

   byte output = manager.lookup_output_by_type(HMTL_OUTPUT_PIXELS);
   if (output != HMTL_NO_OUTPUT) {
     DEBUG4_VALUELN("/rgb output:", output);
     hmtl_set_output_rgb(outputs[output], objects[output], rgb);
+    hmtl_update_output(outputs[output], objects[output]);
   }

   DEBUG3_PRINTLN("/rgb done");


Move serial console to separate function, add more includes

--- Mod-Sketch/Mod-Sketch.ino
+++ Mod-Sketch/Mod-Sketch.ino
@@ -1,12 +1,13 @@
-/* Mod Sketch v0.2 -- written by Craig Durkin / Comingle. */
+/* Mod Sketch v0.2.1 -- written by Craig Durkin / Comingle. */
 /* This software comes pre-loaded on Comingle Mod sex toys */

-/* Include the library */
+#include <Wire.h>
 #include <OSSex.h>
+#include <WiiChuck.h>

 void setup() {
   // Button will increase/decrease power by 20%
-  Toy.setPowerScale(0.2);
+  Toy.setPowerScaleStep(0.2);

   // Blip all the motors and flash the LED to show that everything is working and the device is on.
   startupSequence();
@@ -39,7 +40,12 @@

 void loop() {
-  // Serial console. Read a character in to command[1], and a value in to val
+  serialProcessor();
+
+}
+
+// Serial console. Read a character in to command[1], and a value in to val
+void serialProcessor() {
   char command[1];
   byte val;

@@ -93,7 +99,6 @@
       Serial.println(Toy.getInput(in));
     }
   }
-
 }

@@ -191,7 +196,7 @@
 }

-// Randomly blip an output on for a short burst.
+// Constantly randomly blip an output on for a short burst.
 int pulse(int seq) {
   if (seq % 2) {
     Toy.step[0] = Toy.step[1] = Toy.step[2] = 0;


Trying out Github's online editor... That is all

--- plantstation.ino
+++ plantstation.ino
@@ -1,23 +1,23 @@
-//=====General Deployment Definitions==========
+//===== General deployment defs =================
 String appId = "Plant01";
 String location = "Dinning Room Window";

-//=====For private keys, params================
+//===== For private keys, params ================
 #include "params.h"

-//=====For Keen Integration====================
+//===== For Keen integration ====================
 #include "ApiClient.h"
 #include "KeenClient.h"
 KeenClient myKeen;

-//=====For writting to the console=============
+//===== For writting to the console =============
 #include "Bridge.h"
 #include "Console.h"

-//=====For 4 Relay Module======================
+//===== For 4 relay module ======================
 #define LightSwitch 4

-//=====For Probe Thermometer===================
+//===== For probe thermometer ===================
 #include "OneWire.h"
 const byte probePin = 3;
 OneWire myPT(probePin);
@@ -28,7 +28,7 @@
 } SoilMeasurement;
 SoilMeasurement sm;

-//=====For Digital Thermo, Humidity Sensor=====
+//===== For digital thermo, humidity sensor =====
 #include "DHT.h"
 const byte dhtPin = 2;
 DHT myDHT(dhtPin, DHT11);
@@ -41,19 +41,19 @@
 } AirMeasurement;
 AirMeasurement am;

-//=====For photoresistor=======================
+//===== For photoresistor =======================
 const byte lightOnThreshold = 90;
 const byte lightPin = A0;
 boolean lightIsOn = false;
 int lightResistorVal;

-//=====For Hygrometer==========================
+//===== For hygrometer ==========================
 const byte hygroPin = A1;
 // todo - find right value for this
 const int moistureThreshold = 500; // <- made this up
 int moistureSensorVal;

-//=====For Water===============================
+//===== For water ===============================
 const byte waterSensorPin = A2;
 // todo - find right value for this
 const int waterLevelThreshold = 400; // <- made this up
@@ -63,7 +63,7 @@
 unsigned long prevWatering = 0;
 String waterLevel = "OK";

-//=====For Timed Events=========================
+//===== For timed events =========================
 long prevMinOneMillis = 0;
 long minOneInterval = 60000;
 long prevMinFiveMillis = 0;


Min and Max do not overflow

Min and Max do not overflow

--- led-current-tester.ino
+++ led-current-tester.ino
@@ -94,14 +94,14 @@
 }

 void decreaseFocusValue(int amount) {
+  values[focusRow] -= amount;
   if (values[focusRow] < amount) {
     if (focusRow == COUNT_ROW) {
-      values[focusRow] += NUM_LEDS;
+      values[focusRow] = 1;
     } else {
-      values[focusRow] += 255;
+      values[focusRow] = 0;
     }
   }
-  values[focusRow] -= amount;

   drawLabelValue(focusRow);
   refreshLed();
@@ -111,11 +111,11 @@
   values[focusRow] += amount;
   if (focusRow == COUNT_ROW) {
     if (values[focusRow] > NUM_LEDS) {
-      values[focusRow] %= NUM_LEDS;
+      values[focusRow] = NUM_LEDS;
     }
   } else {
     if (values[focusRow] > 255) {
-      values[focusRow] %= 255;
+      values[focusRow] = 255;
     }
   }


Update OTTO_avoid.ino

Update OTTO_avoid.ino

The buzzer is initialized on pin -1, but should be on pin 10

--- OTTO_avoid/OTTO_avoid.ino
+++ OTTO_avoid/OTTO_avoid.ino
@@ -40,7 +40,7 @@
 ///////////////////////////////////////////////////////////////////
 void setup(){
   //Set the servo pins
-  Otto.init(PIN_YL,PIN_YR,PIN_RL,PIN_RR,true, -1, -1, 8, 9);
+  Otto.init(PIN_YL,PIN_YR,PIN_RL,PIN_RR,true, -1, 10, 8, 9);
   Otto.sing(S_connection); //Otto wake up!
   Otto.home();
   delay(50);


Update comments in Arduino code.

Update comments in Arduino code.

--- arduino_keyboard.ino
+++ arduino_keyboard.ino
@@ -1,8 +1,9 @@
 /*
-  DigitalReadSerial
- Reads a digital input on pin 2, prints the result to the serial monitor
-
- This example code is in the public domain.
+Reads digital inputs 2-9, debounces them using a shift register.  Outputs
+char codes '0' - '7' on the serial line when the buttons are pushed.
+
+Expects SPST pushbuttons connected between digital pins 2-9 and ground.
+Uses the internal pull ups.
  */

 unsigned int debounce[8] = {1,1,1,1, 1,1,1,1};
@@ -18,7 +19,7 @@
   // initialize serial communication at 9600 bits per second:
   Serial.begin(9600);

-  // make the pushbutton's pin an input:
+  // Enable internal pull-ups on the inputs.
   pinMode(2, INPUT_PULLUP);
   pinMode(3, INPUT_PULLUP);
   pinMode(4, INPUT_PULLUP);
@@ -35,13 +36,17 @@
   int i;
   int val;

+  // Loop over the pins, read them each in turn.
   for (i = 0; i < 8; i++) {
-    val = digitalRead(i+2);
+    val = digitalRead(i+2); // +2 because pins 0-1 are used for serial.
+
+    // Shift register debouncer, feed 1-bit value in from the right.  Only
+    // trigger a key press once the debouncer is full of 0s.
     debounce[i] = (debounce[i] << 1) | val;
-    if (debounce[i] == 0) {  // normally high.
-      if (repeat[i] == 0){
+    if (debounce[i] == 0) {  // Button down for whole debounce period.
+      if (repeat[i] == 0){
         Serial.write(output_vals[i]);
-        repeat[i] = 40;
+        repeat[i] = 40;  // Auto-repeat every 200 msec or so.
       }
       else
       {


Fix key mapping for osakana.

Fix key mapping for osakana.

Change-Id: I858f0dbde4d02befde0d6f23a21c38e3435754c8


Add LED to PowerSwitcher

Add LED to PowerSwitcher

--- sketches/PowerSwitcher/PowerSwitcher.ino
+++ sketches/PowerSwitcher/PowerSwitcher.ino
@@ -1,29 +1,19 @@
+#include <Arduino.h>
+#include <SimpleTimer.h>
+#include <MotionSensor.h>
+
 #include "printf.h"
-
-#include "Sonar.h"
-#include "MotionSensor.h"
-
-#include <SimpleTimer.h>

 // #define DEBUG

 uint8_t	pinIRInput 		= 11,
-		pinSonarTrigger = 9,
-		pinSonarEcho 	= 10,
 		pinSwitch 		= 13,
-		pinButton		= 8
+		pinButton		= 8,
+		pinLed 			= 6
 		;
-
-Sonar sonar(
-		pinSonarTrigger,
-		pinSonarEcho,
-		500,				   // Maximum distance we want to ping for (in centimeters).
-			  	  	  	  	   // Maximum sensor distance is rated at 400-500cm.
-		100);   // Recognize objects within this many centimeters

 MotionSensor motion(pinIRInput, 5000);
 SimpleTimer timer(1);
-

 const uint16_t INACTIVITY_THRESHOLD = 120;

@@ -32,14 +22,13 @@
 typedef struct StateStruct {
 	bool active;
 	bool motionDetected;
-	bool sonarDetected;
 	bool buttonPressed;
-	unsigned long sonarDistanceDetected;
 	uint32_t lastActivityAt;
 	uint32_t lastStateChangeAt;
 } CurrentState;

 CurrentState state;
+bool ledOn;

 void power(bool on) {
 	digitalWrite(pinSwitch, on ? HIGH : LOW);
@@ -60,28 +49,26 @@
 	}
 }

-void detectSonar(int timerId) {
-	bool prev = state.sonarDetected;
-	state.sonarDetected = sonar.detected();
-	if (state.sonarDetected) {
-#ifdef DEBUG
-		if (!prev) printf("Detected sonar! Distance is %d\n", sonar.getDistance());
-#endif
-		state.sonarDistanceDetected = sonar.getDistance();
-		state.lastActivityAt = millis();
+void showLed(int timerId) {
+	if (state.active && !state.motionDetected) {
+		ledOn = !ledOn;
+	} else {
+		ledOn = false;
 	}
+
+	digitalWrite(pinLed, ledOn ? HIGH : LOW);
 }

 void switchPower(int timerId) {
 	if (state.active) {
 		if ((!state.buttonPressed) ||
-			(!state.motionDetected && !state.sonarDetected && (millis() - state.lastActivityAt) / 1000 > INACTIVITY_THRESHOLD)
+			(!state.motionDetected && (millis() - state.lastActivityAt) / 1000 > INACTIVITY_THRESHOLD)
 			) {
 			state.lastStateChangeAt = millis();
 			state.active = false;
 		}
 	} else {
-		if (state.buttonPressed && (state.motionDetected || state.sonarDetected)) {
+		if (state.buttonPressed && state.motionDetected) {
 			state.active = true;
 			state.lastStateChangeAt = millis();
 		}
@@ -92,16 +79,13 @@

 void logCurrentState() {

-	printf("Active? %s | Button %s | Motion? %s | Sonar? %s (%4d/%4d)",
+	printf("Active? %s | Button %s | Motion? %s",
 			(state.active ? "YES" : " NO"),
 			(state.buttonPressed ? " ON" : "OFF"),
-			(state.motionDetected ? "YES" : " NO"),
-			(state.sonarDetected  ? "YES" : " NO"),
-				sonar.getDistance(),
-				sonar.getDistanceThreshold()
+			(state.motionDetected ? "YES" : " NO")
   			);

-	if (state.active && state.buttonPressed && !state.motionDetected && !state.sonarDetected) {
+	if (state.active && state.buttonPressed && !state.motionDetected) {
 		long timeLeft = INACTIVITY_THRESHOLD - (millis() - state.lastActivityAt) / 1000;
 		if (timeLeft < 0) timeLeft = 0;
 		printf(" | Time Remaining? (%d/%d) sec ",
@@ -118,6 +102,7 @@
 	memset(&state, 0x0, sizeof(StateStruct));

 	pinMode(pinSwitch, OUTPUT);
+	pinMode(pinLed, OUTPUT);
 	pinMode(pinButton, INPUT);
 	pinMode(pinIRInput, INPUT);

@@ -129,9 +114,9 @@
 	motion.init(5000);

 	timer.setInterval( 110,  &detectMotion);
-	timer.setInterval( 150,  &detectSonar);
 	timer.setInterval( 100,  &detectButtonPressed);
 	timer.setInterval(1000,  &switchPower);
+	timer.setInterval( 500,  &showLed);
 }


Updating rectangle to use PROGMEM and lookup table

--- software/rectangle_rag/rectangle_rag.ino
+++ software/rectangle_rag/rectangle_rag.ino
@@ -1,5 +1,7 @@
-/*
+/*
 */
+
+#include <avr/pgmspace.h>

 #define RED_PIN 1
 #define AMBER_PIN 3
@@ -15,14 +17,21 @@
 #define GREEN_FLASH 32
 #define END_SEQUENCE 64

-#define SEQUENCE_TYPES 3
-#define MAX_STEPS 10
-static uint8_t sequence[SEQUENCE_TYPES][MAX_STEPS][2]=
+#define FLASH_INTERVAL_MILLIS 375
+
+#define SEQUENCE_TYPES 4
+#define MAX_STEPS 30
+// see http://www.arduino.cc/en/Reference/PROGMEM
+// https://github.com/lilspikey/arduino_sketches/blob/master/attiny/xmas/xmas.ino
+// bitrate = pgm_read_word_near ( &(bitrate_table[temp][row_num]) );
+// PROGMEM const uint16_t bitrate_table[15][6] =
+
+const uint16_t sequence[SEQUENCE_TYPES][MAX_STEPS][2] PROGMEM =
 {
   { // Normal Traffic RAG
     {RED, 3},
     {RED + AMBER, 2},
-    {GREEN, 4},
+    {GREEN, 7},
     {AMBER, 2},
     {RED, 3},
     {END_SEQUENCE, 1},
@@ -43,27 +52,39 @@
     {AMBER, 3},
     {RED, 3},
     {END_SEQUENCE, 1},
-  }
+  },
+  { // Silly RAG
+    {RED, 1},
+    {RED + AMBER, 1},
+    {AMBER, 1},
+    {AMBER + GREEN, 1},
+    {GREEN, 1},
+    {AMBER + GREEN, 1},
+    {AMBER, 2},
+    {RED + AMBER, 1},
+    {RED, 2},
+    {RED + AMBER, 2},
+    {GREEN, 9},
+    {AMBER, 2},
+    {RED, 3},
+    {END_SEQUENCE, 1},
+  },

 };

-
-
-// the setup routine runs once when you press reset:
 void setup() {
   // initialize the digital pin as an output.
   pinsToOutput();
   pinMode(BUTTON_PIN, INPUT_PULLUP);
 }

-// the loop routine runs over and over again forever:
+
 void loop() {
-  digitalWrite(RED_PIN, HIGH);   // turn the LED on (HIGH is the voltage level)
-  delay(1000);               // wait for a second
-  digitalWrite(RED_PIN, LOW);    // turn the LED off by making the voltage LOW
-  delay(1000);               // wait for a second
+//  doSequence(4);
+  doSequence(3);
+  doSequence(2);
+  doSequence(1);
   doSequence(0);
-  delay(1000);               // wait for a second

 }

@@ -71,21 +92,34 @@
 void doSequence(unsigned char s)  {
   // http://playground.arduino.cc/Code/TimingRollover
   uint8_t current_step = 0;
-  unsigned long start_milliseconds = 0;
-  bool flash = HIGH; // Start with FLASH ON or HIGH
-  while(sequence[s][current_step][0] != END_SEQUENCE )  {
-      start_milliseconds = millis();
-      digitalWrite(RED_PIN, sequence[s][current_step][0] & RED);
-      digitalWrite(AMBER_PIN, sequence[s][current_step][0] & AMBER);
-      digitalWrite(GREEN_PIN, sequence[s][current_step][0] & GREEN);
-      delay(1000 * sequence[s][current_step][1]);
-      current_step++;
+  uint8_t leds = pgm_read_word_near( &(sequence[s][current_step][0]));
+  unsigned long start_milliseconds, length_of_step, last_flash_milliseconds;
+  uint8_t flash = 255; // Start with FLASH ON or HIGH
+  //pgm_read_word_near ( &(bitrate_table[temp][row_num]) )
+
+  while(leds != END_SEQUENCE )  {
+    start_milliseconds = millis();
+    last_flash_milliseconds = start_milliseconds;
+    length_of_step = 1000 * pgm_read_word_near( &(sequence[s][current_step][1]));
+    while((millis() - start_milliseconds) < (length_of_step) )  {
+      digitalWrite(RED_PIN,   (leds & RED)   | (leds & RED_FLASH   & flash));
+      digitalWrite(AMBER_PIN, (leds & AMBER) | (leds & AMBER_FLASH & flash));
+      digitalWrite(GREEN_PIN, (leds & GREEN) | (leds & GREEN_FLASH & flash));
+      if ((millis() - last_flash_milliseconds) > FLASH_INTERVAL_MILLIS)  {
+        last_flash_milliseconds = millis();
+        flash = ~flash;
+      }
+    }
+    current_step++;
+    leds = pgm_read_word_near( &(sequence[s][current_step][0]));
   }
-
+  digitalWrite(RED_PIN,   LOW);
+  digitalWrite(AMBER_PIN, LOW);
+  digitalWrite(GREEN_PIN, LOW);
 }

 void pinsToOutput()  {
-  pinMode(RED_PIN, OUTPUT);
+  pinMode(RED_PIN,   OUTPUT);
   pinMode(AMBER_PIN, OUTPUT);
   pinMode(GREEN_PIN, OUTPUT);
 }


Version 1.7 27th March 2017

Version 1.7 27th March 2017

* Adds the pretty printer function pprint, which allows you to print functions in a nicely formatted way, and a trace feature using trace and untrace, allowing you to trace the calls to and returns from up to three functions at a time.

* Fixes a long-standing bug which could give incorrect results when two functions using the same symbols called each other.

--- ulisp.ino
+++ ulisp.ino
@@ -2031,11 +2031,10 @@
   }
 }

-// Prettyprinter
+// Pretty printer

 const int ppindent = 2;
-const int defaultppwidth = 80;
-int ppwidth;
+int ppwidth = 80;

 int atomwidth (object *obj) {
   if (obj == NULL) return 3;


Update bb-8-Head-stabiliser-controller.ino

--- Head/Stabiliser/Arduino-firmware/bb-8-Head-stabiliser-controller/bb-8-Head-stabiliser-controller.ino
+++ Head/Stabiliser/Arduino-firmware/bb-8-Head-stabiliser-controller/bb-8-Head-stabiliser-controller.ino
@@ -27,7 +27,43 @@

   Big thanks for http://r2builders.fr/ !
   Initial project : http://r2builders.fr/forum/viewtopic.php?f=26&t=3928&hilit=BB8+par+MOUS
-
+
+  ===============
+  EXEMPLE COMMAND
+  ===============
+  < SET >
+  'SET x87 y75 h3 \n'        // SET a new setpoint for x and y with 3degree of Hysteressis
+  'SET x90 y90 i1 j0 k1 \n'  // SET an inversion of the sensor X Y and invert the direction of X
+
+  	x = SETPOINT for X
+	y = SETPOINT for Y
+	m = MULTIPLIER FOR THE SPEED OF THE MOTOR X and Y
+	i = INVERT the angle sensor ( X = Y and Y = X )
+	j = INVERT the direction of X
+	k = INVERT the direction of Y
+	h = SET a new HYSTERESSIS
+
+
+
+  < BOOT >
+  'BOOT \n'  // LAUNCH TEST for X, Y and Z -> Return X and Y to initial SETPOINT (x90 y90 ) and Z to ZERO
+
+
+
+  < RUN >
+  'RUN \n'   // RUN the code in production mode (Recieved all data, X and Y runing for the SETPOINT poistion and Z folow the remote controll
+
+  < STOP >
+  'STOP \n'  // STOP the production mode. All motors are stopped.
+
+
+  < ROTATE >
+  'ROTATE d1 s100 \n'   // ROTATE Z motor on the RIGHT DIRECTION (d0 LEFT, d1 RIGHT) WITH the SPEED at 1000/100 = 10 step/sec = 18dec/sec
+
+
+  < STAT >
+  // It is all data SENDED to the MASTER-BOARD
+
 */

 #include "Wire.h"
@@ -136,7 +172,7 @@
 //=============================================================================//
 void setup()
 {
-	pinMode( pinEnable , OUTPUT );
+    pinMode( pinEnable , OUTPUT );
     pinMode( pinDirX   , OUTPUT );
     pinMode( pinStepX  , OUTPUT );
     pinMode( pinDirY   , OUTPUT );
@@ -281,7 +317,7 @@
   		{
   			if(!xok)
   			{
-  				Serial.println("STAT x1");
+  				Serial.println("STAT x1 ");
   				xok = true;
   				delay(2000);
   			}
@@ -310,7 +346,7 @@
   		{
   			if(!yok)
   			{
-  				Serial.println("STAT y1");
+  				Serial.println("STAT y1 ");
   				yok = true;
   				delay(2000);
   			}
@@ -329,7 +365,7 @@
   		{
   		  	if(!zok)
   			{
-  				Serial.println("STAT z1");
+  				Serial.println("STAT z1 ");
   				zok = true;
   				Zangle = 0;
   				delay(2000);
@@ -338,6 +374,7 @@

   		if( xok && yok && zok)
   		{
+			Serial.println("STAT b1 ");
   			Serial.println("Booting UP OK!");
   			Serial.println("SEND 'RUN \n' for start the production");
   			BOOT = false;
@@ -481,7 +518,7 @@

     	// SEND STATUT
-    	Serial.print("SEND x");
+    	Serial.print("STAT x");
     	Serial.print(x);
     	Serial.print(" y");
     	Serial.print(y);


Version 2.8a - 6th August 2019

Version 2.8a - 6th August 2019

Minor bug fixes

--- ulisp.ino
+++ ulisp.ino
@@ -1,5 +1,5 @@
-/* uLisp AVR Version 2.8 - www.ulisp.com
-   David Johnson-Davies - www.technoblogy.com - 20th July 2019
+/* uLisp AVR Version 2.8a - www.ulisp.com
+   David Johnson-Davies - www.technoblogy.com - 6th August 2019

    Licensed under the MIT license: https://opensource.org/licenses/MIT
 */
@@ -868,12 +868,12 @@
     checkargs(fname, args);
     return ((fn_ptr_type)lookupfn(fname))(args, env);
   }
-  if (listp(function) && issymbol(car(function), LAMBDA)) {
+  if (consp(function) && issymbol(car(function), LAMBDA)) {
     function = cdr(function);
     object *result = closure(0, 0, NULL, function, args, &env);
     return eval(result, env);
   }
-  if (listp(function) && issymbol(car(function), CLOSURE)) {
+  if (consp(function) && issymbol(car(function), CLOSURE)) {
     function = cdr(function);
     object *result = closure(0, 0, car(function), cdr(function), args, &env);
     return eval(result, env);
@@ -1512,7 +1512,7 @@
 object *sp_withsdcard (object *args, object *env) {
 #if defined(sdcardsupport)
   object *params = first(args);
-  if (params == NULL) error2(WITHSPCARD, nostream);
+  if (params == NULL) error2(WITHSDCARD, nostream);
   object *var = first(params);
   object *filename = eval(second(params), env);
   params = cddr(params);
@@ -1523,10 +1523,10 @@
   if (mode == 1) oflag = O_RDWR | O_CREAT | O_APPEND; else if (mode == 2) oflag = O_RDWR | O_CREAT | O_TRUNC;
   if (mode >= 1) {
     SDpfile = SD.open(MakeFilename(filename), oflag);
-    if (!SDpfile) error2(WITHSPCARD, PSTR("problem writing to SD card"));
+    if (!SDpfile) error2(WITHSDCARD, PSTR("problem writing to SD card"));
   } else {
     SDgfile = SD.open(MakeFilename(filename), oflag);
-    if (!SDgfile) error2(WITHSPCARD, PSTR("problem reading from SD card"));
+    if (!SDgfile) error2(WITHSDCARD, PSTR("problem reading from SD card"));
   }
   object *pair = cons(var, stream(SDSTREAM, 1));
   push(pair,env);
@@ -3326,7 +3326,7 @@
   object *function = car(form);
   object *args = cdr(form);

-  if (function == NULL) error2(0, PSTR("'nil' illegal function"));
+  if (function == NULL) error(0, PSTR("illegal function"), nil);
   if (!listp(args)) error(0, PSTR("can't evaluate a dotted pair"), args);

   // List starts with a symbol?
@@ -3409,7 +3409,7 @@
     return result;
   }

-  if (listp(function) && issymbol(car(function), LAMBDA)) {
+  if (consp(function) && issymbol(car(function), LAMBDA)) {
     form = closure(TCstart, fname->name, NULL, cdr(function), args, &env);
     pop(GCStack);
     int trace = tracing(fname->name);
@@ -3427,7 +3427,7 @@
     }
   }

-  if (listp(function) && issymbol(car(function), CLOSURE)) {
+  if (consp(function) && issymbol(car(function), CLOSURE)) {
     function = cdr(function);
     form = closure(TCstart, fname->name, car(function), cdr(function), args, &env);
     pop(GCStack);
@@ -3435,7 +3435,7 @@
     goto EVAL;
   }

-  error2((int)fname, PSTR("is an illegal function")); return nil;
+  error(0, PSTR("illegal function"), fname); return nil;
 }

 // Print functions
@@ -3620,7 +3620,7 @@
     else if (ch == 'B') base = 2;
     else if (ch == 'O') base = 8;
     else if (ch == 'X') base = 16;
-    else if (ch == 0x07) return (object *)QUO;
+    else if (ch == 0x07) return nextitem(gfun);
     else error2(0, PSTR("illegal character after #"));
     ch = gfun();
   }


Update esp8266-Full-Menu-System-v1.ino

Update esp8266-Full-Menu-System-v1.ino

Shave 7kb of the size.

--- esp8266-Full-Menu-System-v1.ino
+++ esp8266-Full-Menu-System-v1.ino
@@ -168,7 +168,7 @@
 		u8g.setFont(u8g_font_5x8);
 		u8g.setPrintPos(0, 10);
 		u8g.print(network);
-		u8g.setFont(u8g_font_helvB14);
+		u8g.setFont(u8g_font_8x13B);
 		u8g.setPrintPos(60, 30);
 		u8g.print(selectedChar);
 		u8g.setFont(u8g_font_5x8);


Fixed bar graph in inertia learning mode

--- examples/ReflowWizard/Learn.ino
+++ examples/ReflowWizard/Learn.ino
@@ -355,14 +355,14 @@
                 drawPerformanceBar(false, map(i, 35, 60, 100, 0));
                 break;
               case TYPE_BOTTOM_ELEMENT:
-                // (120 seconds = excellent, 240 seconds = awful)
-                i = constrain(learningDutyCycle, 100, 240);
+                // (100 seconds = excellent, 240 seconds = awful)
+                i = constrain(secondsTo150C, 100, 240);
                 drawPerformanceBar(false, map(i, 100, 240, 100, 0));
                 break;
               case TYPE_TOP_ELEMENT:
                 // (60 seconds = excellent, 140 seconds = awful)
                 // Closer to thermocouple, heating less of the oven = less time needed
-                i = constrain(learningDutyCycle, 60, 140);
+                i = constrain(secondsTo150C, 60, 140);
                 drawPerformanceBar(false, map(i, 60, 140, 100, 0));
                 break;
             }


only send Pixy data if blocks have been found

--- examples/RoseBot/RoseBotFirmata/RoseBotFirmata.ino
+++ examples/RoseBot/RoseBotFirmata/RoseBotFirmata.ino
@@ -1061,8 +1061,7 @@
   if (currentMillis - previousMillis > samplingInterval) {
     previousMillis += samplingInterval;

-    if ( pingLoopCounter++ > numLoops)
-    {
+    if ( pingLoopCounter++ > numLoops) {
       pingLoopCounter = 0;
       if (numActiveSonars)
       {
@@ -1126,16 +1125,19 @@
     }
     if (pixyIsReporting) {
       numPixyBlocks = pixyPtr->getBlocks();
-      Firmata.write(START_SYSEX);
-      Firmata.write(PIXY_DATA);
-      Firmata.write(numPixyBlocks);
-      if (numPixyBlocks > pixyMaxBlocks) {
-        numPixyBlocks = pixyMaxBlocks;
-      }
-      for (pixyBlockIndex = 0; pixyBlockIndex < numPixyBlocks; pixyBlockIndex++) {
-        writePixyBlock(pixyBlockIndex);
-      }
-      Firmata.write(END_SYSEX);
+      // Only send Pixy data if a block was found.
+      if (numPixyBlocks) {
+        if (numPixyBlocks > pixyMaxBlocks) {
+          numPixyBlocks = pixyMaxBlocks;
+        }
+        Firmata.write(START_SYSEX);
+        Firmata.write(PIXY_DATA);
+        Firmata.write(numPixyBlocks);
+        for (pixyBlockIndex = 0; pixyBlockIndex < numPixyBlocks; pixyBlockIndex++) {
+          writePixyBlock(pixyBlockIndex);
+        }
+        Firmata.write(END_SYSEX);
+      }
     }
   }
   if (keepAliveInterval) {


using ifdefs for msp code

using ifdefs for msp code

--- MSP_CODE/diffie_hellman_cracker/diffie_hellman_cracker.ino
+++ MSP_CODE/diffie_hellman_cracker/diffie_hellman_cracker.ino
@@ -1,4 +1,16 @@
-#include <msp430.h>
+// #define __MSP430
+#define __MSP432
+
+#ifdef __MSP430
+  #include <msp430.h>
+  #define _redled 2
+  #define _greenled 14
+#endif
+#ifdef __MSP432
+  #include <msp432.h>
+  #define _redled 78
+  #define _greenled 76
+#endif

 unsigned long long ipow(unsigned long long b, unsigned long long e);
 unsigned long long fme(unsigned long long a, unsigned long long b, unsigned long long c);
@@ -12,33 +24,40 @@

 void setup()
 {
-
+
 //  bob_secret = 65519;     // 16 bit, prime
-  bob_secret = 167711;    // 18 bit, prime
-//  bob_secret = 15053471;  // 24 bit, prime
+//  bob_secret = 167711;    // 18 bit, prime
+  bob_secret = 15053471;  // 24 bit, prime
 //  bob_secret = 14384393;  // 24 bit, prime

   // groups
 //  p = (157211*2)+1; g = 2;  // good (bad with 167711)
   p = (157211*2)+1; g = 5;  // good (good with 65519, and 167711)

-
   Serial.begin(9600);
   delay(100);

-  P1DIR |= (BIT0 | BIT6);                 // Set P1.0 to output direction
-  P1OUT = 0;
+  pinMode(_redled, OUTPUT);
+  pinMode(_greenled, OUTPUT);
+  digitalWrite(_redled, HIGH);
+  digitalWrite(_greenled, LOW);

   alice_public = fme(g, alice_secret, p);
   bob_public = fme(g, bob_secret, p);

   // crack bob secret
+
   for(unsigned long long test = 3; test < 2147483648; test++){
-    P1OUT ^= BIT0;
-    if(test % 100 == 0){ Serial.println((unsigned long)test); }
+
+    // blinking status
+    digitalWrite(_redled, bitRead((unsigned int)test, 4));
+
+    if(test % 1000 == 0){ Serial.println((unsigned long)test); }
+
     if(bob_public == fme(g, test, p)){
       Serial.println((unsigned long)test);
-      P1OUT = BIT6;
+      digitalWrite(_redled, LOW);
+      digitalWrite(_greenled, HIGH);
       return;
     }
   }
@@ -56,7 +75,6 @@

 void loop(){}

-
 unsigned long long ipow(unsigned long long b, unsigned long long e)
 {
   // this breaks for values > 32


Added sound to Snack game.

Added sound to Snack game.

--- snack/snack.ino
+++ snack/snack.ino
@@ -85,6 +85,16 @@
   }
 }

+void EndGame()
+{
+    arduboy.tunes.tone(200, 200);
+    delay(400);
+    arduboy.tunes.tone(100, 400);
+    delay(600);
+    arduboy.tunes.tone(50, 2000);
+    gameRunning = false;
+}
+
 void CollisionDetection()
 {

@@ -92,7 +102,7 @@

   if(p1.X >= maxX || p1.X <= minX || p1.Y >= maxY || p1.Y <= minY)
   {
-    gameRunning = false;
+    EndGame();
   }

   //Check if hit tail
@@ -102,7 +112,7 @@
         {
         if(p1.Moves[i].X == p1.X && p1.Moves[i].Y == p1.Y)
         {
-          gameRunning = false;
+          EndGame();
         }
       }
   }
@@ -114,7 +124,7 @@
     {
       p1.Len += 1;
     }
-
+    arduboy.tunes.tone(987, 160);
     score += 1;
     LogMove();
     GenerateFood();


Fixed measure().

Fixed measure().

--- examples/Tools/CosaRF24scanner/CosaRF24scanner.ino
+++ examples/Tools/CosaRF24scanner/CosaRF24scanner.ino
@@ -31,6 +31,7 @@
 #include "Cosa/Watchdog.hh"
 #include "Cosa/UART.hh"
 #include "Cosa/Trace.hh"
+#undef measure

 /**
  * Extend the NRF24L01P device driver with measurement and plot of


Move the watchdog later

Move the watchdog later

Forgot this was the watchdog branch :( Start the watchdog after the
lightshow

--- RightpointLabs.Pourcast.Arduino/RightpointLabs.Pourcast.Arduino.ino
+++ RightpointLabs.Pourcast.Arduino/RightpointLabs.Pourcast.Arduino.ino
@@ -100,8 +100,6 @@
   Serial << F("Setup complete") << endl;
   http->LogMessage(F("Done Initializing"));
   Serial << F("Free: ") << freeMemory() << endl;
-
-  ApplicationMonitor.EnableWatchdog(Watchdog::CApplicationMonitor::Timeout_8s);
 }

 // handle interrupt pulses from the taps
@@ -120,7 +118,7 @@
   digitalWrite(7, HIGH);

   delay(2000);
-
+
   long tap1Pulses = tap1->Clear();
   long tap2Pulses = tap2->Clear();
   char buf[128];
@@ -161,6 +159,8 @@
 // send an ALIVE message every loop to assist debugging
 void loop() {
   startupDelay();
+
+  ApplicationMonitor.EnableWatchdog(Watchdog::CApplicationMonitor::Timeout_8s);

   int cycle = 0;
   http->LogMessage("Primary loop initialized");


test git

test git

--- BASIC_Project_v2_301017_2/BASIC_Project_v2_301017_2.ino
+++ BASIC_Project_v2_301017_2/BASIC_Project_v2_301017_2.ino
@@ -4,7 +4,7 @@
 #include <EEPROM.h>
 #include <RemoteReceiver.h>
 #include <RemoteTransmitter.h>
-//---------------------------------------LCD NOKIA3310
+//---------------------------------------LCD NOKIA3310 add test for git
 #define PIN_SCE   7
 #define PIN_RESET 6
 #define PIN_DC    5


Delete PWM_led_stip_control.ino

Delete PWM_led_stip_control.ino

--- PWM_led_stip_control.ino
+++ PWM_led_stip_control.ino
@@ -1,24 +0,0 @@
-//https://github.com/esp8266/Arduino/blob/master/doc/reference.md
-int blue = D2;
-int green = D3;// the pin that the LED is attached to
-int red = D1;
-//d0 = onboard red
-//d4= onboard blue
-
-// the setup routine runs once when you press reset:
-void setup() {
-  // declare pin 9 to be an output:
-  analogWriteRange(255);
-  pinMode(blue, OUTPUT);
-  pinMode(red, OUTPUT);
-  pinMode(green, OUTPUT);
-}
-
-// the loop routine runs over and over again forever:
-void loop() {
-// 0 = bright, 255 = none
-  analogWrite(blue, 50);
-  analogWrite(green, 255);
-  analogWrite(red, 20);
-
-}


boot signal led 13

boot signal led 13

--- project/gesturecar.ino
+++ project/gesturecar.ino
@@ -44,6 +44,10 @@
 int speed = 50, rspeed = 0, lspeed = 0;

 void setup() {
+
+  // Use LED to signal that boot is over
+  pinMode(13, OUTPUT);
+  digitalWrite(13, HIGH);

   // Set interrupt pin as input
   pinMode(APDS9960_INT, INPUT);
@@ -150,7 +154,7 @@
         }
         else if (STATUS == LFT && dirindex > 0){
           dirindex = 0;
-          movement(command, speeds[speedindex], speeds[dirindex]);
+          movement(command, speeds[speedindex], speeds[dirindex]);
         }
         else if (STATUS == RGT){
           if (command == FORWARD)
@@ -220,7 +224,7 @@
         break;
       default:
         Serial.println("NONE");
-
+
     }
   }
 }


Shows weekday better

Shows weekday better

--- TinyScreenClockAndDisplay/TinyScreenClockAndDisplay.ino
+++ TinyScreenClockAndDisplay/TinyScreenClockAndDisplay.ino
@@ -81,7 +81,7 @@
 // Weekday
       display.setFont(liberationSans_10ptFontInfo);
       display.fontColor(BLUE,BLACK);
-      display.setCursor(0,50);
+      display.setCursor(0,46);
     if (weakday == 1)
   {
       display.print("Sunday");


update tf

update tf

--- arduino/opencr_arduino/opencr/libraries/turtlebot3/turtlebot3_burger/turtlebot3_core/turtlebot3_core.ino
+++ arduino/opencr_arduino/opencr/libraries/turtlebot3/turtlebot3_burger/turtlebot3_core/turtlebot3_core.ino
@@ -220,14 +220,11 @@
   tfs_msg.header.stamp    = rosNow();
   tfs_msg.header.frame_id = "base_link";
   tfs_msg.child_frame_id  = "imu_link";
-  tfs_msg.transform.rotation.w = imu.quat[0];
-  tfs_msg.transform.rotation.x = imu.quat[1];
-  tfs_msg.transform.rotation.y = imu.quat[2];
-  tfs_msg.transform.rotation.z = imu.quat[3];

   tfs_msg.transform.translation.x = IMU_POS_X;
   tfs_msg.transform.translation.y = IMU_POS_Y;
   tfs_msg.transform.translation.z = IMU_POS_Z;
+  tfs_msg.transform.rotation      = imu_msg.orientation;

   tfbroadcaster.sendTransform(tfs_msg);
 }
@@ -344,6 +341,8 @@
   {
     if (variable_flag == false)
     {
+      imu.begin();
+
       odom_pose[0] = 0.0;
       odom_pose[1] = 0.0;
       odom_pose[2] = 0.0;
@@ -372,6 +371,7 @@
 bool updateOdometry(double diff_time)
 {
   double odom_vel[3];
+  float* quat4orientation;

   double wheel_l, wheel_r;      // rotation value of wheel [rad]
   double delta_s, theta, delta_theta;
@@ -399,8 +399,9 @@
     wheel_r = 0.0;

   delta_s     = WHEEL_RADIUS * (wheel_r + wheel_l) / 2.0;
-  theta       = atan2f(imu.quat[1]*imu.quat[2] + imu.quat[0]*imu.quat[3],
-                       0.5f - imu.quat[2]*imu.quat[2] - imu.quat[3]*imu.quat[3]);
+  theta       = atan2f(imu.quat[1]*imu.quat[2] + imu.quat[0]*imu.quat[3],
+                0.5f - imu.quat[2]*imu.quat[2] - imu.quat[3]*imu.quat[3]);
+
   delta_theta = theta - last_theta;

   v = delta_s / step_time;
@@ -419,6 +420,9 @@
   odom_vel[1] = 0.0;
   odom_vel[2] = w;

+  odom.header.frame_id = "odom";
+  odom.child_frame_id  = "base_link";
+
   odom.pose.pose.position.x = odom_pose[0];
   odom.pose.pose.position.y = odom_pose[1];
   odom.pose.pose.position.z = 0;
@@ -453,14 +457,12 @@
 *******************************************************************************/
 void updateTF(geometry_msgs::TransformStamped& odom_tf)
 {
-  odom.header.frame_id = "odom";
-  odom.child_frame_id = "base_link";
   odom_tf.header = odom.header;
   odom_tf.child_frame_id = "base_footprint";
   odom_tf.transform.translation.x = odom.pose.pose.position.x;
   odom_tf.transform.translation.y = odom.pose.pose.position.y;
   odom_tf.transform.translation.z = odom.pose.pose.position.z;
-  odom_tf.transform.rotation = odom.pose.pose.orientation;
+  odom_tf.transform.rotation      = odom.pose.pose.orientation;
 }

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


simple logic / 300 recore / sec

simple logic / 300 recore / sec

--- _41-promini-nrf24-ads1115/_41-promini-nrf24-ads1115.ino
+++ _41-promini-nrf24-ads1115/_41-promini-nrf24-ads1115.ino
@@ -9,39 +9,15 @@
    7  miso  12
 */

-/*
-   17  / int 0    ---> record value to influxdb
-   16 / 15 ---> detect range ( m / u / n )
-*/
-
-/* 250 report / sec
-Adafruit_ADS1015.h
---> #define ADS1115_CONVERSIONDELAY         (1)
-
-Adafruit_ADS1015.cpp
----> int16_t Adafruit_ADS1015::readADC_Differential_0_1() {
-  // Start with default values
-  uint16_t config = ADS1015_REG_CONFIG_CQUE_NONE    | // Disable the comparator (default val)
-                    ADS1015_REG_CONFIG_CLAT_NONLAT  | // Non-latching (default val)
-                    ADS1015_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low   (default val)
-                    ADS1015_REG_CONFIG_CMODE_TRAD   | // Traditional comparator (default val)
-                    ADS1015_REG_CONFIG_DR_3300SPS   | // 1600 samples per second (default)
-                    ADS1015_REG_CONFIG_MODE_SINGLE;   // Single-shot mode (default)
-
-
- */
-
 #include <avr/wdt.h>
 #include <avr/interrupt.h>
 #include <avr/sleep.h>
 #include <avr/pgmspace.h>
 #include <avr/power.h>
 #include <SPI.h>
-#include <LowPower.h>
 #include "nRF24L01.h"
 #include "RF24.h"
 #include <Wire.h>
-//#include "PinChangeInterrupt.h"
 #include <Adafruit_ADS1015.h>

 #define adc_disable() (ADCSRA &= ~(1<<ADEN)) // disable ADC
@@ -68,54 +44,30 @@
 RF24 radio(CE_PIN, CSN_PIN);
 Adafruit_ADS1115 ads(0x48);

-// analogPin 3 / 2 / 1 / int 0
-const int wakeupPin = 2;
-const int recordPin = 17;
-const int nanoPin   = 16;
-const int microPin  = 15;
-const int ledPin    = 14;
+const int doRecordPin = 3;
+const int nanoPin     = 16;
+const int microPin    = 15;
+const int ledPin      = 14;

 int rangeStatus;
-volatile unsigned long counterForloop;
-volatile unsigned long counterForloop_old;
-volatile boolean checkRangenow;
-volatile int noOfWake;
+volatile int recordNo;
+volatile boolean dorecored;

-void checkRange() {
-  checkRangenow = true;
-}
-
-void wakeUp() {
-  noOfWake++;
-  counterForloop_old = counterForloop;
-  checkRangenow = true;
-  //detachInterrupt(digitalPinToInterrupt(2));
-  radio.powerUp();
-  checkRecordBttn();
-}
-
-void sleepNow() {
-  radio.powerDown();
-  digitalWrite(ledPin, LOW);
-  attachInterrupt(digitalPinToInterrupt(2), wakeUp, FALLING);
-  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
-}
-
-void checkRecordBttn() {
-  attachInterrupt(digitalPinToInterrupt(2), sleepNow, FALLING);
+void record() {
+  recordNo++;
+  dorecored = !dorecored;
 }

 void setup() {
-  //Serial.begin(115200);
-
   delay(20);
   adc_disable();

-  pinMode(recordPin, INPUT_PULLUP);
-  pinMode(wakeupPin, INPUT_PULLUP);
+  pinMode(doRecordPin, INPUT);
   pinMode(microPin, INPUT_PULLUP);
   pinMode(nanoPin, INPUT_PULLUP);
   pinMode(ledPin, OUTPUT);
+
+  digitalWrite(ledPin, LOW);

   int microStatus = digitalRead(microPin);
   int nanoStatus  = digitalRead(nanoPin);
@@ -123,9 +75,8 @@
   rangeStatus = microStatus << 1;
   rangeStatus = rangeStatus + nanoStatus;

-  noOfWake = 0;
-  counterForloop = 0;
-  checkRangenow = false;
+  recordNo = 0;
+  dorecored = false;

   // radio
   radio.begin();
@@ -138,13 +89,14 @@
   radio.setPayloadSize(11);
   radio.openWritingPipe(pipes[2]);
   radio.stopListening();
-  radio.powerDown();
+  //radio.powerDown();

   payload._salt = 0;
   payload.devid = DEVICE_ID;

   ads.setGain(GAIN_ONE);
   ads.begin();
+  ads.readADC_Differential_0_1_no_delay();

   for (int k = 0; k < 10; k = k + 1) {
     if (k % 2 == 0) {
@@ -155,93 +107,35 @@
     }
     delay(100);
   }
-
-  sleepNow();
+  attachInterrupt(digitalPinToInterrupt(3), record, RISING);
 }

 void loop() {
-  digitalWrite(ledPin, HIGH);
+  if (dorecored == true) {
+    digitalWrite(ledPin, HIGH);
+    int microStatus = digitalRead(microPin);
+    int nanoStatus  = digitalRead(nanoPin);

-  int microStatus = digitalRead(microPin);
-  int nanoStatus  = digitalRead(nanoPin);
+    rangeStatus = microStatus << 1;
+    rangeStatus = rangeStatus + nanoStatus;

-  rangeStatus = microStatus << 1;
-  rangeStatus = rangeStatus + nanoStatus;
+    int16_t results;
+    float multiplier = 0.125F;
+    //results = ads.readADC_Differential_0_1();
+    results = ads.getLastConversionResults_no_delay();

-  int16_t results;
-  float multiplier = 0.125F;
-  results = ads.readADC_Differential_0_1();
+    payload.data1 = results * multiplier ;
+    payload.data2 = rangeStatus;

-  /*
-  Serial.print("noOfWakeup : ");
-  Serial.print(noOfWake);
-  Serial.print(" : counterForloop : ");
-  Serial.print(counterForloop);
-  Serial.print(" : rangeStatus : ");
-  Serial.print(rangeStatus);
-  Serial.print(" : results : ");
-  Serial.print(results * multiplier);
-  Serial.print(" mA ----> ");
-  */
+    payload._salt = recordNo ;
+    payload.volt = 3300;

-  /*
-  if (counterForloop > (counterForloop_old + 10)) {
-    checkRecordBttn();
+    ads.readADC_Differential_0_1_no_delay();
+
+    radio.write(&payload , sizeof(payload));
+
+    digitalWrite(ledPin, LOW);
+  } else {
+    digitalWrite(ledPin, LOW);
   }
-  */
-
-  payload.data1 = results * multiplier ;
-  payload.data2 = rangeStatus;
-
-  payload._salt = noOfWake ;
-  //payload.volt = readVcc();
-  payload.volt = 3300;
-
-  /*
-  Serial.print(payload.data1);
-  Serial.print(" : data2 : ");
-  Serial.println(payload.data2);
-  */
-
-  //if ( rangeStatus == 1 || rangeStatus == 3 || rangeStatus == 2 ) {
-  //if ( rangeStatus != 0 ) {
-
-    //radio.powerUp();
-    radio.write(&payload , sizeof(payload));
-    //radio.powerDown();
-  //}
-
-  digitalWrite(ledPin, LOW);
-  counterForloop++;
-  //delay(30);
 }
-
-int readVcc() {
-  adc_enable();
-  // Read 1.1V reference against AVcc
-  // set the reference to Vcc and the measurement to the internal 1.1V reference
-#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
-  ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
-#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
-  ADMUX = _BV(MUX5) | _BV(MUX0);
-#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
-  ADMUX = _BV(MUX3) | _BV(MUX2);
-#else
-  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
-#endif
-
-  delay(2); // Wait for Vref to settle
-  ADCSRA |= _BV(ADSC); // Start conversion
-  while (bit_is_set(ADCSRA, ADSC)); // measuring
-
-  uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
-  uint8_t high = ADCH; // unlocks both
-
-  long result = (high << 8) | low;
-
-  result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
-  adc_disable();
-
-  return (int)result; // Vcc in millivolts
-}
-


add subscription request

add subscription request

--- Charger/WebSocketTest.ino
+++ Charger/WebSocketTest.ino
@@ -21,6 +21,41 @@
 uint64_t messageTimestamp = 0;
 uint64_t heartbeatTimestamp = 0;
 bool isConnected = false;
+bool isSubscribed = false;
+
+
+const char* PoleSubscriptionRequest =
+"<omiEnvelope xmlns=\"http://www.opengroup.org/xsd/omi/1.0/\" version=\"1.0\" ttl=\"-1\">"
+ "<read msgformat=\"odf\" interval=\"-1\" callback=\"0\">"
+   "<msg>"
+     "<Objects xmlns=\"http://www.opengroup.org/xsd/odf/1.0/\">"
+       "<Object>"
+         "<id>ParkingService</id>"
+         "<Object>"
+           "<id>ParkingFacilities</id>"
+           "<Object>"
+             "<id>CSBuildingParkingLot</id>"
+             "<Object>"
+               "<id>ParkingSpaceTypes</id>"
+               "<Object>"
+                 "<id>ElectricVehicleParkingSpace</id>"
+                 "<Object>"
+                   "<id>Spaces</id>"
+                   "<Object>"
+                     "<id>EVSpace1</id>"
+                     "<InfoItem name=\"OpenLid\"/>"
+                   "</Object>"
+                 "</Object>"
+               "</Object>"
+             "</Object>"
+           "</Object>"
+         "</Object>"
+       "</Object>"
+     "</Objects>"
+   "</msg>"
+ "</read>"
+"</omiEnvelope>" ;
+

 void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {

@@ -35,9 +70,8 @@
                 DFORMAT("[WSc] Connected to url: %s\n\r",  payload);
                 isConnected = true;

-			    // send message to server when Connected
-                // socket.io upgrade confirmation message (required)
-				webSocket.sendTXT("5");
+                DLN("Sending Subscription");
+                isSubscribed = false;
             }
             break;
         case WStype_TEXT:
@@ -135,7 +169,6 @@

-
 void loop() {

   // if not connected try to connect
@@ -144,19 +177,6 @@
   }

-  const char* testRead =
-  "<omi:omiEnvelope xmlns:omi=\"omi.xsd\" version=\"1.0\" ttl=\"50\">"
-    "<omi:read msgformat=\"odf\">"
-      "<omi:msg>"
-        "<Objects xmlns=\"odf.xsd\">"
-          "<Object>"
-            "<id>SmartHouse</id>"
-            "<InfoItem name=\"FrontDoor\"/>"
-          "</Object>"
-        "</Objects>"
-      "</omi:msg>"
-    "</omi:read>"
-  "</omi:omiEnvelope>";

   for (int wait = 0; wait < 15 && !isConnected; wait++) {
     DLN("Waiting for connection.");
@@ -171,16 +191,15 @@

   while (isConnected) {
     webSocket.loop();
-    DFORMAT("RAM Memory left: %d\r\n", ESP.getFreeHeap());
-
+    //DFORMAT("RAM Memory left: %d\r\n", ESP.getFreeHeap());
+
+    if (! isSubscribed) {
+      webSocket.sendTXT(PoleSubscriptionRequest);
+      isSubscribed = true; // TODO: Check response success
+    }
+
     uint64_t now = millis();

-    if(now - messageTimestamp > MESSAGE_INTERVAL) {
-      messageTimestamp = now;
-
-      DLN("Sending testRead");
-      webSocket.sendTXT(testRead);
-    }
     if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
       heartbeatTimestamp = now;


more colors to arkanoid for ssd1331 lcd

more colors to arkanoid for ssd1331 lcd

--- examples/arkanoid/arkanoid.ino
+++ examples/arkanoid/arkanoid.ino
@@ -341,7 +341,12 @@

 void drawBlock(uint8_t x, uint8_t y)
 {
-    ssd1306_drawSpriteEx(LEFT_EDGE + 1 + (x << 4), y, 16, &blockImages[gameField[y][x]][0]);
+    uint8_t block = gameField[y][x];
+    if (block == 1) ssd1331_setColor(RGB_COLOR8(64,64,255));
+    else if (block == 2) ssd1331_setColor(RGB_COLOR8(64,255,255));
+    else if (block == 3) ssd1331_setColor(RGB_COLOR8(64,255,64));
+    else ssd1331_setColor(RGB_COLOR8(64,64,255));
+    ssd1306_drawSpriteEx(LEFT_EDGE + 1 + (x << 4), y, 16, &blockImages[block][0]);
 }

@@ -371,7 +376,6 @@
     {
         for (uint8_t bl = 0; bl<BLOCKS_PER_ROW; bl++)
         {
-            ssd1331_setColor(RGB_COLOR8(64,64,255));
             drawBlock(bl, r);
         }
     }


token and uuid print were incorrect in example, basically working code now again

--- examples/skynetim/skynetim.ino
+++ examples/skynetim/skynetim.ino
@@ -69,8 +69,8 @@
   }else
   {
     Serial.println(F("Connected!"));
-	Serial.println(skynetclient->uuid);
-	Serial.println(skynetclient->token);
+	Serial.println(skynetclient.uuid);
+	Serial.println(skynetclient.token);
   }
 }