Removed last led because I can't count!

Removed last led because I can't count!

--- map/map.ino
+++ map/map.ino
@@ -8,8 +8,8 @@

 ESP8266WebServer server(8222);

-const int PINCOUNT = 9;
-int leds[] = {D0, D1, D2, D3, D4, D5, D6, D7, D8};
+const int PINCOUNT = 8;
+int leds[] = {D0, D1, D2, D3, D4, D5, D7, D8};

 void handleRoot() {
 //    digitalWrite(LED01, 1);
@@ -141,13 +141,14 @@
 }

 void setup(void){
+    Serial.begin(115200);
+//    delay(1000);

     for (int i = 0; i < PINCOUNT; i++ ) {
-        Serial.println(leds[i]);
+        Serial.println(i);
         pinMode(leds[i], OUTPUT);
     }

-    Serial.begin(115200);
     doConnect();

     flashAll(); flashAll();


Types fixes due to lib updates

Types fixes due to lib updates

--- examples/LatencyTest/LatencyTest.ino
+++ examples/LatencyTest/LatencyTest.ino
@@ -35,15 +35,14 @@
     }

     // Print some info about the chip
-    EZRadioReply::PartInfo const& pi = zeta.readPartInformation();
+    auto const& pi = zeta.readPartInformation();
     Serial.println("----------");
     Serial.print("Chip rev: "); Serial.println(pi.CHIPREV);
-    Serial.print("Part    : "); Serial.println(pi.PART.U16, HEX);
+    Serial.print("Part    : "); Serial.println(pi.PART, HEX);
     Serial.print("PBuild  : "); Serial.println(pi.PBUILD);
-    Serial.print("ID      : "); Serial.println(pi.ID.U16);
+    Serial.print("ID      : "); Serial.println(pi.ID);
     Serial.print("Customer: "); Serial.println(pi.CUSTOMER);
     Serial.print("Rom ID  : "); Serial.println(pi.ROMID);
-    Serial.print("Bond    : "); Serial.println(pi.BOND);
     Serial.print('\n');//*/

     zeta.startListeningSinglePacketOnChannel(4);


change PIR sensitivity

change PIR sensitivity

--- embedded-particle/sense-motion.ino
+++ embedded-particle/sense-motion.ino
@@ -34,7 +34,7 @@

 // tracks how many PIR reads have been high in a row
 // 10 is too sensitive, 20 works ok
-const int onThreshold = 15;
+const int onThreshold = 25;
 const int maxOn = 180;
 int highReads = 0;


debugging git

debugging git

--- examples/PCA9557_J2/PCA9557_J2.ino
+++ examples/PCA9557_J2/PCA9557_J2.ino
@@ -21,13 +21,14 @@
  *  2016 May 26 bboyes moved into Systronix_PCA9557 examples folder
  *				Changed name to PCA9557_J2
  *  2016 May 15 bboyes Start with new SALT 2v0 board
- *	2016 Jul 4	wsk		complete thrash of this example used as a test bed for SALT_JX class
+ *	2016 Jul 4	wsk		complete thrash of this example used as a test bed for SALT_JX and SALT_FETs classes
  */

 #include <Arduino.h>
 #include <Systronix_PCA9557.h>
 #include <SALT_JX.h>
+#include <SALT_FETs.h>
 #include <NAP_pod_load_defs.h>

 /**
@@ -38,7 +39,6 @@
 #define I2C_J2 0x1B
 #define I2C_J3 0x1A
 #define I2C_J4 0x19
-#define I2C_FET 0x1C

 // TODO: move to common .h file
 #define JX_LED_ON	false		// yes, opposite to the other bits.  writing a 1 to the 9557 output register
@@ -75,13 +75,7 @@
 // open drain, SETTING (yes, opposite to the other bits) this bit drives output low = LED on
 #define LED BIT0	// 0x01

-// coreFET defines: TODO: move to appropriate .h file
-// LED on bit 0 uses the LED define above
-#define	LIGHTS		BIT2		// when set HIGH, turns on the habitats' fluorescent lights
-#define	ALARM		BIT3		// when set HIGH, sounds the alarm at the top of the A habitat
-#define	FAN3		BIT5		// when set HIGH, turns on the left-most fan
-#define	FAN2		BIT6		// when set HIGH, turns on the middle fan
-#define	FAN1		BIT7		// when set HIGH, turns on the right-most fan
+

 /**
@@ -97,26 +91,35 @@
  */
 #define INMASK (SDIN)

+#ifdef USE_CLASS
 SALT_JX coreJ2 (2);
 //SALT_JX coreJ3 (3);
 //SALT_JX coreJ4 (4);
+#else
+extern void J2_update (void);
+extern void J3_update (void);
+extern void J4_update (void);
+extern struct J_data J2_data, J3_data, J4_data;
+#endif
+
+SALT_FETs coreFETs (1);

 Systronix_PCA9557 coreJ2reg(I2C_J2);
 Systronix_PCA9557 coreJ3reg(I2C_J3);
 Systronix_PCA9557 coreJ4reg(I2C_J4);

-Systronix_PCA9557 coreFET(I2C_FET);
+

 // TODO: move to common .h file as #defines;
 uint8_t periph_rst = 22;	// peripheral reset asserted LOW to PCA9557, etc on board
 uint8_t ether_rst = 8;		// Wiznet module reset LOW

-struct J_data
-	{
-	uint32_t	DC_data_in;			// data read from the DC board '165 shift register
-	uint16_t	AC_data_out;		// data sent to the AC board; send this before sending DC
-	uint16_t	DC_data_out;		// data sent to the DC board
-	} J2_data , J3_data, J4_data;
+//struct J_data
+//	{
+//	uint32_t	DC_data_in;			// data read from the DC board '165 shift register
+//	uint16_t	AC_data_out;		// data sent to the AC board; send this before sending DC
+//	uint16_t	DC_data_out;		// data sent to the DC board
+//	} J2_data , J3_data, J4_data;

 //---------------------------< S E T U P >--------------------------------------------------------------------
@@ -148,16 +151,16 @@
 	coreJ2reg.begin();
 	coreJ3reg.begin();
 	coreJ4reg.begin();
-	coreFET.begin();
+//	coreFETreg.begin();

 	// outmask, outdata, inputinvert
-	coreJ2reg.init(OUTMASK, (SCLK | RCLK595 | LED), 0);
-	coreJ3reg.init(OUTMASK, (SCLK | RCLK595 | LED), 0);
-	coreJ4reg.init(OUTMASK, (SCLK | RCLK595 | LED), 0);
-	// FETs don't have clocks to downstream devices
-	// set all as outputs, all outputs off/low, no input inversion (none are inputs anyway)
-	coreFET.init(0xFF, 0x00, 0x00);
-
+//	coreJ2reg.init(OUTMASK, (SCLK | RCLK595 | LED), 0);
+//	coreJ3reg.init(OUTMASK, (SCLK | RCLK595 | LED), 0);
+//	coreJ4reg.init(OUTMASK, (SCLK | RCLK595 | LED), 0);
+
+	coreFETs.init ();
+
+#ifdef USE_CLASS
 	coreJ2.AC_data_out = 0;				// clear DC and AC 595 registers
 	coreJ2.DC_data_out = 0;
 //	coreJ3.AC_data_out = 0;				// clear DC and AC 595 registers
@@ -170,27 +173,52 @@
 	coreJ2.AC_data_out = 0x8000;	// setup for walking-ones test
 //	coreJ3.AC_data_out = 0x8000;	// setup for walking-ones test
 //	coreJ3.AC_data_out = 0x8000;	// setup for walking-ones test
+#else
+	J2_data.AC_data_out = 0;				// clear DC and AC 595 registers
+	J2_data.DC_data_out = 0;
+	J3_data.AC_data_out = 0;				// clear DC and AC 595 registers
+	J3_data.DC_data_out = 0;
+	J4_data.AC_data_out = 0;				// clear DC and AC 595 registers
+	J4_data.DC_data_out = 0;
+
+	J2_update ();					// do it
+	J3_update ();					// do it
+	J4_update ();					// do it
+
+	J2_data.AC_data_out = 0x8000;	// setup for walking-ones test
+	J3_data.AC_data_out = 0x8000;	// setup for walking-ones test
+	J4_data.AC_data_out = 0x8000;	// setup for walking-ones test
+#endif
+	coreFETs.FET_settings = 0x80;	// init for walking one test
 	}

-	uint8_t fet_test = 0x80;
+//	uint8_t fet_test = 0x80;

 //---------------------------< L O O P >----------------------------------------------------------------------

 void loop(void)
 	{
-	if (0x80 & fet_test)
-		fet_test = 4;								// reset to bit 2, fluorescents
+	if (0x80 & coreFETs.FET_settings)
+		coreFETs.FET_settings = 4;								// reset to bit 2, fluorescents
 	else
-		fet_test <<= 1;
-
-	coreFET.pin_drive ((fet_test | LED), HIGH);		// HIGH turn the LED off and the FET on
+		coreFETs.FET_settings <<= 1;
+
+//	coreFETreg.pin_drive ((fet_test | LED), HIGH);		// HIGH turn the LED off and the FET on
+	coreFETs.update();		// update the fets
+	delay(20);
+
+	coreFETs.update();		// update the fets
+//	coreFETs.LED_off ();	// turn off the 9557 LED
 	delay(1000);

-	coreFET.pin_drive ((fet_test | LED), LOW);		// LOW turn the LED on and the FET off
-//	coreJ2reg.pin_drive (LED, true);
-	// coreFET.pin_drive (LED, true);
-
+//	coreFETreg.pin_drive ((fet_test | LED), LOW);		// LOW turn the LED on and the FET off
+//	coreFETs.update();		// turn off the LED
+
+
+	Serial.print("------INPUT------0x");
+
+#ifdef USE_CLASS
 	if (0x8000 & coreJ2.AC_data_out)			// when the '1' is in the MSB (bit 31)
 		{
 		coreJ2.AC_data_out = 0;				// clear so there is only one '1'
@@ -219,30 +247,45 @@
 //		coreJ4.DC_data_out <<= 1;
 		}

-
 	coreJ2.update ();						// do it
 //	coreJ3.update (coreJ3reg);				// do it
 //	coreJ4.update (coreJ4reg);				// do it
-
-/*	if (0x8000 & J2_data.AC_data_out)		// when the '1' is in the MSB (bit 31)
-		{
-		J2_data.AC_data_out = 0;
-		J2_data.DC_data_out = 1;
-		}
-	else if (0x8000 & J2_data.DC_data_out)	// when the '1' is in the DC board's MSB (bit 15)
-		{
-		J2_data.AC_data_out = 1;			// shift the '1' to lsb of DC data
-		J2_data.DC_data_out = 0;			// clear so there is only one '1'
+	Serial.println(coreJ2.DC_data_in, HEX);
+
+#else
+	if (0x8000 & J2_data.AC_data_out)			// when the '1' is in the MSB (bit 31)
+		{
+		J2_data.AC_data_out = 0;				// clear so there is only one '1'
+		J2_data.DC_data_out = 1;				// shift the '1' to lsb of DC data
+		J3_data.AC_data_out = 0;				// clear so there is only one '1'
+		J3_data.DC_data_out = 1;				// shift the '1' to lsb of DC data
+		J4_data.AC_data_out = 0;				// clear so there is only one '1'
+		J4_data.DC_data_out = 1;				// shift the '1' to lsb of DC data
+		}
+	else if (0x8000 & J2_data.DC_data_out)		// when the '1' is in the DC board's MSB (bit 15)
+		{
+		J2_data.AC_data_out = 1;				// shift the '1' to lsb of DC data
+		J2_data.DC_data_out = 0;				// clear so there is only one '1'
+		J3_data.AC_data_out = 1;				// shift the '1' to lsb of DC data
+		J3_data.DC_data_out = 0;				// clear so there is only one '1'
+		J4_data.AC_data_out = 1;				// shift the '1' to lsb of DC data
+		J4_data.DC_data_out = 0;				// clear so there is only one '1'
 		}
 	else
 		{
 		J2_data.AC_data_out <<= 1;			// shift both registers toward msb
 		J2_data.DC_data_out <<= 1;
-		}
-	coreJ2.update ();
-*/
-	Serial.print("------INPUT------0x");
-	Serial.println(coreJ2.DC_data_in, HEX);
+		J3_data.AC_data_out <<= 1;			// shift both registers toward msb
+		J3_data.DC_data_out <<= 1;
+		J4_data.AC_data_out <<= 1;			// shift both registers toward msb
+		J4_data.DC_data_out <<= 1;
+		}
+
+	J2_update ();						// do it
+	J3_update ();						// do it
+	J4_update ();						// do it
+	Serial.println(J4_data.DC_data_in, HEX);
+#endif

 	delay(1000);
 	}


Add full MQTT addressing to esp8266 firmware.

--- esp8266/TestServer/TestServer.ino
+++ esp8266/TestServer/TestServer.ino
@@ -21,6 +21,11 @@
 // Length of name strings. (hostname, room names, lamp names, etc.)
 #define NAME_LEN 32

+// Each device has an address in the form 'role/location1/location2/etc'
+// eg: 'lighting/kitchen/worktop/left'.
+#define ADDRESS_SEGMENTS 6
+#define ADDRESS_SEGMENT_LEN 32
+

 enum Io_Type {
   test,
@@ -29,9 +34,12 @@
   onoff
 };

+typedef struct Address_Segment {
+  char segment[ADDRESS_SEGMENT_LEN];
+} Address_Segment;
+
 typedef struct Connected_device {
-  char name[NAME_LEN];
-  char room[NAME_LEN];
+  Address_Segment address_segment[ADDRESS_SEGMENTS];
   Io_Type io_type;
   int io_pins[3];
   int io_value[3];
@@ -50,20 +58,35 @@

 String mac_address;
 const int led = 12;
-const int led2 = 13;

 // Configuration
 void SetHostname(const char* new_hostname) {
-  strncpy(config.hostname, new_hostname, NAME_LEN);
-}
-
-void SetDevice(const unsigned int index, struct Connected_device device) {
+  strncpy(config.hostname, new_hostname, NAME_LEN -1);
+  config.hostname[NAME_LEN] = '\0';
+}
+
+void SetDevice(const unsigned int index, struct Connected_device& device) {
   if (index < MAX_DEVICES) {
     memcpy(&(config.devices[index]), &device, sizeof(device));
   }
 }

+String DeviceAddress(Connected_device& device) {
+  String return_value = "";
+  for(int i = 0; i < ADDRESS_SEGMENTS; i++){
+    if(strlen(device.address_segment[i].segment) > 0){
+      if(i > 0){
+        return_value += "/";
+      }
+      return_value += device.address_segment[i].segment;
+    } else {
+      break;
+    }
+  }
+  return return_value;
+}
+

 // mDNS
 Brokers brokers(QUESTION_SERVICE);
@@ -72,8 +95,6 @@
   brokers.ParseMDnsAnswer(answer);
 }
 mdns::MDns my_mdns(NULL, NULL, answerCallback);
-
-

 // MQTT
@@ -93,11 +114,11 @@

   // Switch on the LED if an 1 was received as first character
   if ((char)payload[0] == '1') {
-    digitalWrite(led2, LOW);   // Turn the LED on (Note that LOW is the voltage level
+    digitalWrite(led, LOW);   // Turn the LED on (Note that LOW is the voltage level
     // but actually the LED is on; this is because
     // it is acive low on the ESP-01)
   } else {
-    digitalWrite(led2, HIGH);  // Turn the LED off by making the voltage HIGH
+    digitalWrite(led, HIGH);  // Turn the LED off by making the voltage HIGH
   }
 }

@@ -107,15 +128,35 @@
   mqtt_client.setCallback(mqtt_callback);
   if (mqtt_client.connect(config.hostname)) {
     char lamp[255];
-    strncpy(lamp, "_subject : lighting/unconfigured/", 254);
-    strncat(lamp, config.hostname, 254 - strlen(lamp));
-    strncat(lamp, " , _state : off", 254 - strlen(lamp));
-
-    mqtt_client.publish("homeautomation/0/lighting/_announce", lamp);
-    //mqtt_client.subscribe("homeautomation/+/lighting/unconfigured/" + config.hostname);
-    mqtt_client.subscribe("homeautomation/+/lighting/unconfigured/_all");
-    mqtt_client.subscribe("homeautomation/+/lighting/_all");
-    mqtt_client.subscribe("homeautomation/+/_all/_all");
+    char address[255];
+
+    strncpy(address, "homeautomation/+/_all/_all", 254);
+    mqtt_client.subscribe(address);
+
+    for (int i = 0; i < MAX_DEVICES; ++i) {
+      if (strlen(config.devices[i].address_segment[0].segment) > 0) {
+        String announce = "_subject : " + DeviceAddress(config.devices[i]);
+        announce += " , _state : off";
+        announce.toCharArray(lamp, 255);
+
+        mqtt_client.publish("homeautomation/0/lighting/_announce", lamp);
+
+        strncpy(address, "homeautomation/+/_all", 254);
+
+        for(int j = 0; j < ADDRESS_SEGMENTS; j++){
+          if(strlen(config.devices[i].address_segment[j].segment) <= 0) {
+            break;
+          }
+          address[strlen(address) -4] = '\0';
+          strncat(address, config.devices[i].address_segment[j].segment, 254 - strlen(address));
+          if (j < (ADDRESS_SEGMENTS -1) && strlen(config.devices[i].address_segment[j +1].segment) > 0) {
+            strncat(address, "/_all", 254 - strlen(address));
+          }
+          Serial.println(address);
+          mqtt_client.subscribe(address);
+        }
+      }
+    }
   }
   brokers.RateBroker(mqtt_client.connected());
   if (mqtt_client.connected()) {
@@ -162,12 +203,10 @@
   message += "\n";

   for (int i = 0; i < MAX_DEVICES; ++i) {
-    if (strlen(config.devices[i].name)) {
-      message += i;
+    message += i;
+    if (strlen(config.devices[i].address_segment[0].segment) > 0) {
       message += "  ";
-      message += config.devices[i].name;
-      message += "  ";
-      message += config.devices[i].room;
+      message += DeviceAddress(config.devices[i]);
       message += "  ";
       if (config.devices[i].io_type == Io_Type::test) {
         message += "test";
@@ -188,9 +227,8 @@
           message += config.devices[i].io_pins[0];
         }
       }
-
-      message += "\n";
-    }
+    }
+    message += "\n";
   }

   message += brokers.Summary();
@@ -200,25 +238,45 @@
 }

 void handleConfig() {
+  Serial.println("handleConfig()");
   const unsigned int now = millis() / 1000;

   String message = "";
+
+  for(int i = 0; i < http_server.args(); i++){
+    message += http_server.argName(i);
+    message += '\t';
+    message += http_server.arg(i);
+    message += '\n';
+  }
+  message += '\n';

   if (http_server.hasArg("test_arg")) {
     message += "test_arg: " + http_server.arg("test_arg") + "\n";
   }
+
   if (http_server.hasArg("hostname")) {
     char tmp_buffer[NAME_LEN];
     http_server.arg("hostname").toCharArray(tmp_buffer, NAME_LEN);
     SetHostname(tmp_buffer);
     message += "hostname: " + http_server.arg("hostname") + "\n";
   }
-  Serial.println("device");
-  if (http_server.hasArg("device") and http_server.hasArg("name") and http_server.hasArg("room") and http_server.hasArg("io_type") and http_server.hasArg("io_pins")) {
+
+  if (http_server.hasArg("device") and http_server.hasArg("address_segment") and
+      http_server.hasArg("io_type") and http_server.hasArg("io_pins")) {
     unsigned int index = http_server.arg("device").toInt();
     Connected_device device;
-    http_server.arg("name").toCharArray(device.name, NAME_LEN);
-    http_server.arg("room").toCharArray(device.room, NAME_LEN);
+
+    int segment_counter = 0;
+    for(int i = 0; i < http_server.args(); i++){
+      if(http_server.argName(i) == "address_segment"){
+        http_server.arg(i).toCharArray(device.address_segment[segment_counter++].segment, ADDRESS_SEGMENT_LEN);
+      }
+    }
+    for(int i = segment_counter; i < ADDRESS_SEGMENTS; i++){
+      device.address_segment[segment_counter++].segment[0] = '\0';
+    }
+
     if (http_server.arg("io_type") == "test") {
       device.io_type = Io_Type::test;
     } else if (http_server.arg("io_type") == "rgb") {
@@ -238,14 +296,10 @@
       io_pins_buffer[strlen(io_pins_buffer)] = ',';
     }

-    Serial.println(io_pins_buffer);
-    Serial.println();
-
     unsigned int pin_num = 0, pin_buffer_pointer = 0;
     memset(pin_buffer, '\0', 4);
     for (unsigned int i = 0; i < strlen(io_pins_buffer); ++i) {
       if (io_pins_buffer[i] == ',') {
-        Serial.println(pin_buffer);
         device.io_pins[pin_num++] = atoi(pin_buffer);
         memset(pin_buffer, '\0', 4);
         pin_buffer_pointer = 0;
@@ -257,12 +311,14 @@
         break;
       }
     }
-    Serial.println();

     SetDevice(index, device);

     message += "device: " + http_server.arg("device") + "\n";
     Serial.println(message);
+
+    // Force reconnect to MQTT so we subscribe to any new addreses.
+    mqtt_client.disconnect();
   }

   http_server.send(200, "text/plain", message);


Update a_variable_declarations.ino

Update a_variable_declarations.ino

Change to use serial input

--- a_variable_declarations.ino
+++ a_variable_declarations.ino
@@ -1,76 +1,76 @@
-// pins for the encoder inputs
-
-
-int rightCount = 0;
-float Pos=0;
-//double targetCount = 1000;//-1000; // later overwritten by PSARJ value
-float PosErr = 0;
-unsigned long time;
-float tmpSpeed = 0;
-float tmpSpeed2 = 0;
-
-// === for PID  ========
-int Kp = 50; // Proportional Gain of PID
-int Ki = 4; // Integral Gain of PID
-int Kd = 0; // Derivative Gain of PID
-unsigned long previousMillis = 0;
-unsigned long LoopStartMillis = 0;
-// For debugging
-unsigned long millisChPt1 = 0;
-unsigned long millisChPt2 = 0;
-unsigned long millisChPt3 = 0;
-unsigned long millisChPt4 = 0;
-unsigned long millisChPt5 = 0;
-unsigned long millisChPt6 = 0;
-int LEDstatus=0;
-//
-unsigned long  delta_t_millis = 1;
-float inverse_delta_t_millis = 1;
-float dErr_dt = 0;
-float PosErr_old = 0;
-float dPosErr=0;
-float Int_Old=0;
-float Int_Now=0;
-
-uint8_t i;
-int CmdSpeed;
-int MyFlag;
-String response="";
-
-//PSARJ
-
-boolean PSARJstartup = true;
-double PSARJdiff = 0.00;
-double oldPSARJstep = 0.00;
-double oldPSARJangle = 0.00;
-double oldPSARJ = 0.00;
-double PSARJcheck = 0.00;
-double PSARJstep = 0.00;
-
-
-//SSARJ
-
-boolean SSARJstartup = true;
-double SSARJdiff = 0.00;
-double oldSSARJstep = 0.00;
-double oldSSARJangle = 0.00;
-double oldSSARJ = 0.00;
-double SSARJcheck = 0.00;
-double SSARJstep = 0.00;
-
-double Beta1B = 0.0;
-double Beta2B = 0.0;
-double Beta3B = 0.0;
-double Beta4B = 0.0;
-double Beta1A = 0.0;
-double Beta2A = 0.0;
-double Beta3A = 0.0;
-double Beta4A = 0.0;
-double PSARJ = -1.0;
-double SSARJ = 0.0;
-double PTRRJ = 0.0;
-double STRRJ = 0.0;
-boolean AOS = false;
-
-
+// pins for the encoder inputs

+String test;
+int rightCount = 0;
+float Pos=0;
+//double targetCount = 1000;//-1000; // later overwritten by PSARJ value
+float PosErr = 0;
+unsigned long time;
+float tmpSpeed = 0;
+float tmpSpeed2 = 0;
+
+// === for PID  ========
+int Kp = 50; // Proportional Gain of PID
+int Ki = 4; // Integral Gain of PID
+int Kd = 0; // Derivative Gain of PID
+unsigned long previousMillis = 0;
+unsigned long LoopStartMillis = 0;
+// For debugging
+unsigned long millisChPt1 = 0;
+unsigned long millisChPt2 = 0;
+unsigned long millisChPt3 = 0;
+unsigned long millisChPt4 = 0;
+unsigned long millisChPt5 = 0;
+unsigned long millisChPt6 = 0;
+int LEDstatus=0;
+//
+unsigned long  delta_t_millis = 1;
+float inverse_delta_t_millis = 1;
+float dErr_dt = 0;
+float PosErr_old = 0;
+float dPosErr=0;
+float Int_Old=0;
+float Int_Now=0;
+
+uint8_t i;
+int CmdSpeed;
+int MyFlag;
+String response="";
+
+//PSARJ
+
+boolean PSARJstartup = true;
+double PSARJdiff = 0.00;
+double oldPSARJstep = 0.00;
+double oldPSARJangle = 0.00;
+double oldPSARJ = 0.00;
+double PSARJcheck = 0.00;
+double PSARJstep = 0.00;
+
+
+//SSARJ
+
+boolean SSARJstartup = true;
+double SSARJdiff = 0.00;
+double oldSSARJstep = 0.00;
+double oldSSARJangle = 0.00;
+double oldSSARJ = 0.00;
+double SSARJcheck = 0.00;
+double SSARJstep = 0.00;
+
+double Beta1B = 0.0;
+double Beta2B = 0.0;
+double Beta3B = 0.0;
+double Beta4B = 0.0;
+double Beta1A = 0.0;
+double Beta2A = 0.0;
+double Beta3A = 0.0;
+double Beta4A = 0.0;
+double PSARJ = -1.0;
+double SSARJ = 0.0;
+double PTRRJ = 0.0;
+double STRRJ = 0.0;
+boolean AOS = false;
+
+
+


tweak

tweak

--- sensRH/src/sketch.ino
+++ sensRH/src/sketch.ino
@@ -63,11 +63,10 @@

   Serial.print("Humidity: ");
   Serial.print(h);
-  Serial.print(" %\t");
+  Serial.print(" % \t");
   Serial.print("Temperature: ");
   Serial.print(t);
-  Serial.print(" *C");
-  Serial.print(" %\t");
+  Serial.print(" *C \t");
   Serial.print("Dewpoint: ");
   Serial.print(dpc);
   Serial.println(" *C");


Cleaned-up leftovers from experiments.

Cleaned-up leftovers from experiments.

--- examples/DemoArcRPM/DemoArcRPM.ino
+++ examples/DemoArcRPM/DemoArcRPM.ino
@@ -2,9 +2,6 @@
 ///
 ///  Created for personal use, use it at your own risk and benefit.
 ///
-#define X9_CS_PIN 3
-#define X9_UD_PIN 4
-#define X9_INC_PIN 5

 #include "PinDefinitions.h"
 #include "LedDefinitions.h"


ESP8266 changes

ESP8266 changes

--- aqualightsrpi_esp8266/aqualightsrpi_esp8266.ino
+++ aqualightsrpi_esp8266/aqualightsrpi_esp8266.ino
@@ -118,6 +118,9 @@
 void loop() {
   // put your main code here, to run repeatedly:
   if (!client.connected()) {
+    if (WiFi.status() != WL_CONNECTED) {
+      setup_wifi();
+    }
     reconnect();
   }
   client.loop();


Bumped version to 1.2.0

Bumped version to 1.2.0

--- arduino-weather-station/arduino-weather-station.ino
+++ arduino-weather-station/arduino-weather-station.ino
@@ -47,7 +47,7 @@
     weatherSensor.begin();

     blinkLedSynchronous(statusLed, 3); // Device initialized
-    Serial.println("arduino-weather-station v1.1.0 (https://github.com/drasive/arduino-weather-station)");
+    Serial.println("arduino-weather-station v1.2.0 (https://github.com/drasive/arduino-weather-station)");
     Serial.println("Initialization successful\n");
     delay(1 * 1000);
 }


Fix turning command

Fix turning command

--- examples/Car/SimpleCar/SimpleCar.ino
+++ examples/Car/SimpleCar/SimpleCar.ino
@@ -13,7 +13,7 @@
     car.setSpeed(50);
     delay(3000);
     // Start turning sharp left
-    car.setSpeed(-90);
+    car.setAngle(-90);
     delay(3000);
     // Straighten the car and move backward
     car.setAngle(0);


empty char to empty string

empty char to empty string

--- firmware/examples/serialInterval.ino
+++ firmware/examples/serialInterval.ino
@@ -17,7 +17,6 @@
       Serial.print(' ');
     }
     // Terminate message with a linefeed and a carriage return
-    Serial.println('');
+    Serial.println("");
   }
 }
-


, が抜けていたのを修正.

, が抜けていたのを修正.

--- arduino/GeneralIoSerial/GeneralIoSerial.ino
+++ arduino/GeneralIoSerial/GeneralIoSerial.ino
@@ -749,7 +749,7 @@
    的なjsonを作る.
  */
 String wrapEventJson(String type, String dataJson){
-  String body = stringJson("event", type)
+  String body = stringJson("event", type) + ","
           + wrapDq("data") + ":" + dataJson;
   return wrapBrace(body);
 }


updated example to fit new boot sequence

--- firmware/examples/ble-mesh-cloud.ino
+++ firmware/examples/ble-mesh-cloud.ino
@@ -22,12 +22,13 @@
 // send commands with
 // curl https://api.spark.io/v1/devices/[ID]/set_val -d access_token=[token] -d "args=11"

-#include "nrf8001-ble-uart-spark-io/lib_aci.h"
-#include "nrf8001-ble-uart-spark-io/boards.h"
+#include "lib_aci.h"
+#include "boards.h"

-#include "nrf8001-ble-uart-spark-io/rbc_mesh_interface.h"
-#include "nrf8001-ble-uart-spark-io/serial_evt.h"
+#include "rbc_mesh_interface.h"
+#include "serial_evt.h"

+#define ACCESS_ADDR     (0xA541A68F)

 // defining the state of the system for communication
 enum state_t{
@@ -40,6 +41,8 @@

 // buffer for the last value send by the SPI slave
 int lastResponse;
+
+int initState = 0;

 // callback function for http command to set a handle value
 int set_val(String args){
@@ -105,58 +108,56 @@

 // sending intialization commands to SPI slave
 // alternating sending of commands and waiting for response
-int initState = 0;
-bool newMessage = false;
-
 void initConnectionSlowly(){
-    uint32_t accAddr = 0xA541A68F;
     switch(initState) {
         case 0:
-            rbc_mesh_init(accAddr, (uint8_t) 38, (uint8_t) 2, (uint32_t) 0x64000000); // 100 as little endian, spark is big endian
-
+            rbc_mesh_init(ACCESS_ADDR, (uint8_t) 38, (uint8_t) 2, (uint32_t) 100);
             initState++;
+            Serial.println("Sent init command");
             break;
         case 1:
-            if(newMessage){
-                rbc_mesh_value_enable((uint8_t) 1);
-                initState++;
-            }
+            rbc_mesh_value_enable((uint8_t) 1);
+            initState++;
+            Serial.println("Enabled value 1");
             break;
         case 2:
-            if(newMessage){
-                rbc_mesh_value_enable((uint8_t) 2);
-                initState++;
-            }
+            rbc_mesh_value_enable((uint8_t) 2);
+            initState++;
+            Serial.println("Enabled value 2");
             break;
         case 3:
-            if(newMessage){
-                state = ready;
-                Serial.println("init done");
-            }
+            state = ready;
+            Serial.println("init done");
     }
 }

 // arduino conform main loop
 void loop() {
-
+    static bool newMessage = false;
     // send next initialization command to SPI slave until we leave init state
-    if(state == init){
+    if (state == init && newMessage) {
         initConnectionSlowly();
     }
+
     //Process any ACI commands or events
     serial_evt_t evnt;
     newMessage = rbc_mesh_evt_get(&evnt);

-    if(state == waitingForEvent && newMessage
-        && evnt.opcode == SERIAL_EVT_OPCODE_CMD_RSP){
-        state = ready;
-
-        // save the response value of SPI slave into buffer
-        // can be read via callback function
-        lastResponse = evnt.params.cmd_rsp.response.val_get.data[0];
+    if(newMessage && evnt.opcode == SERIAL_EVT_OPCODE_CMD_RSP){
+        if (evnt.params.cmd_rsp.status != ACI_STATUS_SUCCESS)
+        {
+            Serial.print("Error response on cmd ");
+            Serial.print(evnt.params.cmd_rsp.command_opcode, HEX);
+            Serial.print(": ");
+            Serial.print(evnt.params.cmd_rsp.status, HEX);
+            Serial.println();
+        }
+
+        if (state == waitingForEvent) {
+            state = ready;
+            // save the response value of SPI slave into buffer
+            // can be read via callback function
+            lastResponse = evnt.params.cmd_rsp.response.val_get.data[0];
+        }
     }
-
-    //Serial.print(state);
-    //Serial.print("  ");
-    //Serial.println(initState);
 }


Improve pin configuration for ATtiny.

Improve pin configuration for ATtiny.

--- examples/Blink/CosaBlinkTemp/CosaBlinkTemp.ino
+++ examples/Blink/CosaBlinkTemp/CosaBlinkTemp.ino
@@ -22,21 +22,18 @@
  * less than 10 uA while idle (and no LED on).
  *
  *                       DS18B20/sensor
- * (VCC)--[4K7]--+       +------------+
+ * (D3)---[4K7]--+       +------------+
  * (GND)---------)-----1-|GND         |\
  * (D4)----------+-----2-|DQ          | |
  * (VCC/GND)-----------3-|VDD         |/
  *                       +------------+
  *
- * (D0)---------RED->|---+
+ * (D5/D0)------RED->|---+
  *                       |
- * (D1)-------GREEN->|---+----[330]---(GND)
+ * (D6/D1)----GREEN->|---+----[330]---(GND)
  *                       |
- * (D2)--------BLUE->|---+
+ * (D7/D2)-----BLUE->|---+
  *
- * Connect Arduino to DS18B20 in D4 and GND. May use parasite
- * powering (connect DS18B20 VCC to GND) otherwise to VCC.
- *
  * This file is part of the Arduino Che Cosa project.
  */

@@ -45,9 +42,15 @@
 #include "Cosa/OWI/Driver/DS18B20.hh"

 // RGB LED pins
+#if !defined(BOARD_ATTINY)
+OutputPin red(Board::D5);
+OutputPin green(Board::D6);
+OutputPin blue(Board::D7);
+#else
 OutputPin red(Board::D0);
 OutputPin green(Board::D1);
 OutputPin blue(Board::D2);
+#endif

 // 1-wire bus and digital thermometer
 OutputPin pw(Board::D3);


Calibrate sensors needs control over LTA loading to function

--- examples/CalibrateSensors/CalibrateSensors.ino
+++ examples/CalibrateSensors/CalibrateSensors.ino
@@ -1,8 +1,6 @@
 #include "Wire.h"
 #include "SPI.h"
 #include "MINDS-i-Drone.h"
-#include "platforms/Ardupilot.h"
-using namespace Platform;

 enum ProgramState {
     COLLECT_STATES,
@@ -30,9 +28,12 @@
 float acclLog[6][3];
 float magnLog[6][3];

-InertialVec* sens[2] = {&mpu, &hmc};
+MPU6000  mpu;
+HMC5883L cmp;
+InertialVec* sens[2] = {&mpu, &cmp};
 Translator   conv[2] = {Translators::identity, Translators::identity};
 InertialManager sensors(sens, conv, 2);
+Settings set(eeStorage::getInstance());

 class datastream{
 private:
@@ -83,8 +84,12 @@
 datastream magn[3];

 void setup(){
-    beginAPM();
     Serial.begin(9600);
+    mpu.begin();
+    cmp.begin();
+    delay(1000);
+    mpu.calibrate();
+    cmp.calibrate();
     delay(250);

     auto mpuState = mpu.status();
@@ -93,10 +98,10 @@
         Serial.println(mpuState.message);
         while(true);
     }
-    auto hmcState = hmc.status();
-    if(!hmcState.good()){
+    auto cmpState = cmp.status();
+    if(!cmpState.good()){
         Serial.println("Bad HMC5883L status");
-        Serial.println(hmcState.message);
+        Serial.println(cmpState.message);
         while(true);
     }

@@ -105,8 +110,6 @@
 }

 void loop(){
-    updateAPM();
-
     static uint32_t time = millis();
     if( millis() > time){
         time += UPDATE_DELAY;
@@ -200,6 +203,9 @@
     LTATune newAccl = LTATune::FitEllipsoid(acclLog);
     LTATune newMagn = LTATune::FitEllipsoid(magnLog);

+//{"-X","+X","-Y","+Y","-Z","+Z"}
+
+
     Serial.println();
     for(int i=0; i<3; i++){
         float a = magnLog[i*2+0][i];
@@ -214,6 +220,20 @@
             newMagn.scalar[i] *= -1;
         }
     }
+/*
+    Serial.println();
+    for(int j=0; j<6; j++){
+        float data[3];
+        for(int i=0; i<3; i++) data[i] = magnLog[j][i];
+        newMagn.calibrate(data);
+        float val = data[j/2] * ((j%2)? 1.0 : -1.0);
+        Serial.print(j/2);
+        Serial.print("\t");
+        Serial.print(val);
+        Serial.print("\t");
+        Serial.println();
+    }
+*/

     Serial.println("res = (raw+shift)*scalar");
     Serial.println("New accelerometer tune:");
@@ -222,18 +242,18 @@
     printTune(newMagn);
     Serial.println("Would you like to save these values? (y/n)");
     if(getTrueFalseResponse()){
-        settings.writeTuningValues(newAccl, newMagn);
+        set.writeTuningValues(newAccl, newMagn);
     }
 }

 void applyTuneFromEEPROM(){
-    mpu.tuneAccl(settings.getAccelTune());
-    hmc.tune(settings.getMagTune());
+    mpu.tuneAccl(set.getAccelTune());
+    cmp.tune(set.getMagTune());
 }

 void resetTuneParameters(){
     mpu.tuneAccl(LTATune());
-    hmc.tune(LTATune());
+    cmp.tune(LTATune());
 }

 void streamData(){


readable code in application controller

readable code in application controller

The state machine to send ble-mesh commands in a certain order is more
readable and understandable now

--- application_controller/serial_interface/serial_interface.ino
+++ application_controller/serial_interface/serial_interface.ino
@@ -108,19 +108,22 @@
 bool stringComplete = false;  // whether the string is complete
 uint8_t stringIndex = 0;      //Initialize the index to store incoming chars

-int num = -1;
+int state = -1;

 // Application specific example code. Arduino version of the LED example project for nRF51
+// state machine to write commands in order and with delay, triggered by serial input
 void actions_loop() {
-
-  if (stringComplete)
+  // executed after line is read through serial input (hit enter to increment state)
+  if (stringComplete)
   {
     uart_buffer_len = stringIndex + 1;
-    num++;
-
-    if(num == 0){
+    state++;
+
+
+    // echo to test spi-connection
+    if(state == 0){
        if (!rbc_mesh_echo(uart_buffer, uart_buffer_len)){
         Serial.println(F("Serial input dropped"));
       }
@@ -128,7 +131,9 @@
        Serial.println(F("echo done"));
      }
     }
-    if(num == 1){
+
+    // initialization: enable the handles
+    if(state == 1){
       if(!rbc_mesh_value_enable((uint8_t) 1)){
        Serial.println(F("enable 1 dropped"));
      }
@@ -136,7 +141,7 @@
        Serial.println(F("enable 1 done"));
      }
     }
-    if(num == 2){
+    if(state == 2){
       if(!rbc_mesh_value_enable((uint8_t) 2)){
        Serial.println(F("enable 2 dropped"));
      }
@@ -144,18 +149,17 @@
        Serial.println(F("enable 2 done"));
      }
     }
-    if(num > 2){
-      uint8_t on = (num/2) % 2;
-      uint8_t handle = (num % 2) + 1;
-      if(handle == 1) {
-		rbc_mesh_value_set((uint8_t)2, &on, (uint8_t) 1);
-       		Serial.println(F("set done"));
-	}
-      if(handle == 2){
-		rbc_mesh_value_get((uint8_t) 2);
-       		Serial.println(F("get done"));
-	}
-
+
+    // toogle state of one handle after every state change
+    if(state > 2){
+      uint8_t value = (state/2) % 2;
+      uint8_t handle = (state % 2) + 1;
+      if(!rbc_mesh_value_set(handle, &value, (uint8_t) 1)){
+        Serial.println(F("set dropped"));
+      }
+      else{
+        Serial.println(F("set done"));
+      }
     }

     // clear the uart_buffer:


Updated test file.

Updated test file.

--- OpenBCI_32bit/tests/OpenBCI_32bit_Libraries_Test/OpenBCI_32bit_Libraries_Test.ino
+++ OpenBCI_32bit/tests/OpenBCI_32bit_Libraries_Test/OpenBCI_32bit_Libraries_Test.ino
@@ -179,6 +179,8 @@
     byte expectedNumberOfBytes = 34;

     byte acutalNumberOfBytes = board.sendChannelData();
+
+    Serial1.print("\n");

     test.assertEqual(expectedNumberOfBytes, acutalNumberOfBytes, "Stream packet writes 34 bytes");
 }


Remove Serial references

Remove Serial references

--- dee-oh-tee.ino
+++ dee-oh-tee.ino
@@ -32,8 +32,6 @@
 Servo tiltServo;

 void setup() {
-  Serial.begin(9600);
-
   pinMode(buttonPin, INPUT_PULLUP);
   pinMode(laserPin, OUTPUT);

@@ -138,8 +136,6 @@

 void drawRectangle(int startX, int startY, int width, int height, int xDegreesPerCycle) {
   if (startX + width > USABLE_DEGREES || startY + height > USABLE_DEGREES) {
-    Serial.print("The requested rectangle goes beyond the servo's usable range");
-    Serial.println();
     return;
   }


Examples: WDRC_SingleBand: change whitespace

--- examples/03-Intermediate/WDRC_SingleBand/WDRC_SingleBand.ino
+++ examples/03-Intermediate/WDRC_SingleBand/WDRC_SingleBand.ino
@@ -20,7 +20,7 @@

 //create audio library objects for handling the audio
-Tympan						      myTympan(TympanRev::D);  //TympanRev::D or TympanRev::C
+Tympan                  myTympan(TympanRev::D);  //TympanRev::D or TympanRev::C
 AudioInputI2S_F32       i2s_in;
 AudioFilterBiquad_F32   iir1;
 AudioEffectCompWDRC_F32  compWDRC1;


Fix error in example

Fix error in example

--- examples/BasicESPWebConfig/BasicESPWebConfig.ino
+++ examples/BasicESPWebConfig/BasicESPWebConfig.ino
@@ -49,12 +49,12 @@
   // Verify that wifi works
   static bool first = true;
   if (first) {
+    WiFiClient client;
     HTTPClient http;
-    int httpCode;

     first = false;
-    http.begin("http://google.com/robots.txt");
-    httpCode = http.GET();
+    http.begin(client, "http://google.com/robots.txt");
+    int httpCode = http.GET();
     Serial.println("Test wifi connection");
     Serial.print("Google responded with code ");
     Serial.print(httpCode);


fix bug in example CustomTimedThread when overriding shouldRun

--- examples/CustomTimedThread/CustomTimedThread.ino
+++ examples/CustomTimedThread/CustomTimedThread.ino
@@ -113,7 +113,7 @@
 		"Old" default Thread method 'shouldRun' return if
 		it should run.
 	*/
-	bool shouldRun(long time){
+	bool shouldRun(unsigned long time){
 		// Override enabled on thread when pin goes LOW.
 		if(digitalRead(pin) == LOW){
 			enabled = true;


Update octosonarx2_bench.ino

Update octosonarx2_bench.ino

checked in version was not the one I was actually using

--- examples/octosonarx2_bench/octosonarx2_bench.ino
+++ examples/octosonarx2_bench/octosonarx2_bench.ino
@@ -8,12 +8,12 @@
 #include <Wire.h>

 #define JIGADDR_T 0x21
-#define JIGADDR_E 0x21
+#define JIGADDR_E 0x22
 #define OCTO_ADDR 0x20
 #define GREEN_LED 5
 #define RED_LED 6
 #define INT_PIN 7
-#define DEBUG_PIN A7
+#define DEBUG_PIN 8
 #define debug(thing) if (digitalRead(DEBUG_PIN) == LOW) {Serial.print(thing);}
 #define debugln(thing) if (digitalRead(DEBUG_PIN) == LOW) {Serial.println(thing); delay(50);}
 #define debugln2(thing,format) if (digitalRead(DEBUG_PIN) == LOW) {Serial.println(thing, format); delay(50);}
@@ -23,7 +23,7 @@

 void setup() {
   uint8_t i;
-  Serial.begin(9600);
+  Serial.begin(57600);
   Wire.begin();

   pinMode(GREEN_LED, OUTPUT);
@@ -97,7 +97,7 @@
   byte error = 1;
   // keep last status 5s before start again
   delay(5000);
-  digitalWrite(GREEN_LED, ON);
+  digitalWrite(GREEN_LED, OFF);
   digitalWrite(RED_LED, OFF);
   Serial.println("Looking for OctoSonar");
   while (error != 0) {
@@ -130,8 +130,8 @@
     return;

   }
-  retVal = Wire.read() << 8;
   retVal += Wire.read();
+  retVal += (Wire.read() << 8);

   if (retVal != 0xffff) {
     Serial.print("Error T_READ ");
@@ -156,22 +156,28 @@

   for (byte port = 0; port <= 0xf; port++) {
     uint16_t portByte = ~(1 << port);
-    //  debug("Checking port ");
-    //  debugln(port);
-    //  debug("portByte ");
-    //  debugln2(portByte, HEX);
-    // set all echos high
+    uint16_t echoByte = 0xffff;
+    debug("Checking port ");
+    debugln(port);
+    debug("portByte ");
+    debugln2(portByte, HEX);
     // set all echos high
     Wire.beginTransmission(JIGADDR_E);
-    Wire.write(0xff);
-    Wire.write(0xff);
+    Wire.write((uint8_t)(echoByte & 0xff));
+    Wire.write((uint8_t)((echoByte >> 8) & 0xff));
     error = Wire.endTransmission(true);
+    if ( error ) {
+      Serial.print("Failed to write to jig E  = ");
+      Serial.println(error);
+      digitalWrite(RED_LED, ON);
+      return;
+    }

     // enable the port

     Wire.beginTransmission(OCTO_ADDR);
+    Wire.write((uint8_t)(portByte & 0xff));
     Wire.write((uint8_t)((portByte >> 8) & 0xff));
-    Wire.write((uint8_t)(portByte & 0xff));
     error = Wire.endTransmission(true);
     if ( error ) {
       Serial.print("Failed to write to OctoSonar error = ");
@@ -179,8 +185,8 @@
       digitalWrite(RED_LED, ON);
       return;
     }
-    //  debug("sent portByte ");
-    //  debugln2(portByte, HEX);
+    debug("sent portByte ");
+    debugln2(portByte, HEX);
     //read them back
     Wire.requestFrom(JIGADDR_T, 2);
     if (Wire.available() != 2) {
@@ -190,8 +196,10 @@
       return;

     }
-    retVal = Wire.read() << 8;
-    retVal += Wire.read();
+    retVal = Wire.read();
+    retVal += (Wire.read() << 8);
+    debug("trigs ");
+    debugln2(retVal, HEX);

     if (retVal != portByte) {
       Serial.print("Error 1 - I see trigs ");
@@ -199,56 +207,71 @@
       digitalWrite(RED_LED, ON);
       return;
     }
-    //    debug("trigs ");
-    //  debugln2(retVal, HEX);

     // check the pin val - should be high
-    if (digitalRead(INT_PIN) == LOW) {
+    while (digitalRead(INT_PIN) == LOW) {
       Serial.print("Error: INT is low when echo is high trig ");
-      Serial.println(port, HEX);
-     Serial.println(LOW);
-     Serial.println(HIGH);
-     Serial.println(INT_PIN);
-     Serial.println(digitalRead(INT_PIN));
-      digitalWrite(RED_LED, ON);
-      return;
+      Serial.println(portByte, HEX);
+      Serial.print("echo ");
+      Serial.println(echoByte, HEX);
+      Serial.println(digitalRead(INT_PIN));
+      digitalWrite(RED_LED, ON);
+      //return;
     }
     //    debugln("High gives high");

     // drop the other echoes - should have no effect
+    echoByte = 0xffff;
     for (i = 0; i <= 0xf; i++) {
       if (i == port) continue; // skip self
-      //      digitalWrite(echoPin[i], LOW);
-      //read them back
-      Wire.requestFrom(JIGADDR_T, 1);
-      retVal = Wire.read();
+      echoByte &= ~(1 << i);
+      Wire.beginTransmission(JIGADDR_E);
+      Wire.write((uint8_t)(echoByte & 0xff));
+      Wire.write((uint8_t)((echoByte >> 8) & 0xff));
       error = Wire.endTransmission(true);
       if ( error ) {
-        Serial.print("Failed to read from jig error = ");
+        Serial.print("Failed to write to JIG E error 3 = ");
         Serial.println(error);
-        digitalWrite(RED_LED, HIGH);
+        digitalWrite(RED_LED, ON);
+        return;
+      }
+
+      //read trigs - should not have changed
+      Wire.requestFrom(JIGADDR_T, 2);
+      retVal = Wire.read();
+      retVal += (Wire.read() << 8);
+      error = Wire.endTransmission(true);
+      if ( error ) {
+        Serial.print("Failed to read from jig error 3 = ");
+        Serial.println(error);
+        digitalWrite(RED_LED, ON);
         return;
       }
       if (retVal != portByte) {
         Serial.print("Error 3 - I see trigs ");
-        Serial.println(retVal, HEX);
-        digitalWrite(RED_LED, HIGH);
+        Serial.print(retVal, HEX);
+        Serial.print(" wanted ");
+        Serial.println(portByte, HEX);
+        digitalWrite(RED_LED, ON);
         return;
       }
       if (digitalRead(INT_PIN) == LOW) {
         Serial.print("Error: INT goes low with pin ");
         Serial.println(i);
-        Wire.requestFrom(JIGADDR_T, 1);
-        Serial.println(Wire.read(), HEX);
+        Wire.requestFrom(JIGADDR_T, 2);
+        retVal = Wire.read();
+        retVal += (Wire.read() << 8);
+        error = Wire.endTransmission(true);
+        Serial.println(retVal, HEX);
         error = Wire.endTransmission(true);
         if ( error ) {
           Serial.print("Failed to read from jig error = ");
           Serial.println(error);
-          digitalWrite(RED_LED, HIGH);
+          digitalWrite(RED_LED, ON);
           return;
         }

-        digitalWrite(RED_LED, HIGH);
+        digitalWrite(RED_LED, ON);
         return;
       }
       //     debug("INT ok with low pin ");
@@ -257,19 +280,40 @@
     //   debugln("No interference from other echoes");

     // drop self
-    //    digitalWrite(echoPin[port], LOW);
-    if (digitalRead(INT_PIN) == HIGH) {
+    echoByte &= ~(1 << port);
+    Wire.beginTransmission(JIGADDR_E);
+    Wire.write((uint8_t)(echoByte & 0xff));
+    Wire.write((uint8_t)((echoByte >> 8) & 0xff));
+    error = Wire.endTransmission(true);
+    while (digitalRead(INT_PIN) == HIGH) {
       Serial.println("Error: INT is high when echo is low");
-      digitalWrite(RED_LED, HIGH);
-      return;
-    }
-    //   debugln("Low gives low");
+      Serial.print("echo ");
+      Serial.println(echoByte, HEX);
+      Serial.print("port ");
+      Serial.println(portByte, HEX);
+        Wire.requestFrom(JIGADDR_T, 2);
+        retVal = Wire.read();
+        retVal = Wire.read() << 8;
+        error = Wire.endTransmission(true);
+        Serial.print("I see trigs ");
+        Serial.println(retVal, HEX);
+        error = Wire.endTransmission(true);
+        if ( error ) {
+          Serial.print("Failed to read from jig error = ");
+          Serial.println(error);
+          digitalWrite(RED_LED, ON);
+          return;
+        }
+      digitalWrite(RED_LED, ON);
+      // return;
+    }
+    debugln("Low gives low");
   }

   // if we got here, we passed
   Serial.println("PASS");
-  digitalWrite(GREEN_LED, HIGH);
-  digitalWrite(RED_LED, LOW);
+  digitalWrite(GREEN_LED, ON);
+  digitalWrite(RED_LED, OFF);
 }


Board::A8 was removed. Ripple effect; changed to A5.

--- examples/Pins/CosaAnalogPins/CosaAnalogPins.ino
+++ examples/Pins/CosaAnalogPins/CosaAnalogPins.ino
@@ -38,7 +38,7 @@
   Board::A0,
   Board::A1,
   Board::A2,
-  Board::A8
+  Board::A5
 };

 // Buffer for sample values


Continued attempts to make 2 gyros read.  Giving up on this repo - these gyro units are not fit to the task, and keep freezing up no matter how clean my code is.  One works fine, two always freezes after a few seconds to a few minutes.  Appears to be a memory leak, but no amount of garbage collection seems to help.

--- ardu-predator/ardu-predator.ino
+++ ardu-predator/ardu-predator.ino
@@ -2,7 +2,7 @@
  * ardu-predator.ino
  *
  * @author Mike Muscato
- * @date   2017-07-04
+ * @date   2017-11-05
  *
  * Refactored to handle two GY-521 MPU6050 Breakout Boards.
  * One fixed to the body, the other dynamic on the head.
@@ -31,7 +31,7 @@
 #include "Servo.h"

 // Comment to turn off Serial printing
-#define DEBUG
+//#define DEBUG

 // DEBUG serial printing macros
 #ifdef DEBUG
@@ -61,6 +61,13 @@
 // NOTE: Yaw direction is inverted via map() method in moveServos()
 const int maxYaw = 135;
 const int minYaw = 45;
+
+//used to center servos when gyros are level.
+//e.g. 0 degrees becomes 90 degrees, the middle of the servo's swing.
+const int servoAngleOffset = 90;
+
+//millis between servo position write events.
+const int servoDelay = 1000;

 // You must supply your gyro offsets here,
 // Use MPU6050_calibration.ino found at:
@@ -80,9 +87,6 @@
 // var to store the servo position when testing
 int pos = 0;

-// vars for angle values.
-float Yaw, Pitch, Roll;
-
 // Will be used for timing events.
 unsigned long currentMillis = 0;    // stores the value of millis() in each iteration of loop()
 unsigned long prevMillis = 0;    // stores the value of millis() in each iteration of loop()
@@ -223,27 +227,27 @@
  *
  */
 void GetDMP() {
-
-  for (int i = 0; i < 2; i++) {
-    mpuInterrupt[i] = false;
-    FifoAlive[i] = 1;
-    fifoCount[i] = mpus[i].getFIFOCount();
-
-    if ((!fifoCount[i]) || (fifoCount[i] % packetSize[i])) { // we have failed Reset and wait till next time!
-      digitalWrite(LED_PIN, LOW); // lets turn off the blinking LED so we can see we are failing.
-        mpus[i].resetFIFO();// clear the buffer and start over
+  if (currentMillis >= prevMillis + servoDelay) {
+    for (int i = 0; i < 2; i++) {
+      mpuInterrupt[i] = false;
+      FifoAlive[i] = 1;
+      fifoCount[i] = mpus[i].getFIFOCount();
+
+      if ((!fifoCount[i]) || (fifoCount[i] % packetSize[i])) { // we have failed Reset and wait till next time!
+        digitalWrite(LED_PIN, LOW); // lets turn off the blinking LED so we can see we are failing.
+          mpus[i].resetFIFO();// clear the buffer and start over
+      }
+      else {
+        while (fifoCount[i]  >= packetSize[i]) { // Get the packets until we have the latest!
+            mpus[i].getFIFOBytes(fifoBuffer[i], packetSize[i]); // lets do the magic and get the data
+            fifoCount[i] -= packetSize[i];
+        }
+      }
     }
-    else {
-      while (fifoCount[i]  >= packetSize[i]) { // Get the packets until we have the latest!
-          mpus[i].getFIFOBytes(fifoBuffer[i], packetSize[i]); // lets do the magic and get the data
-          fifoCount[i] -= packetSize[i];
-      }
-    }
-  }
-
-  MPUMath(); // Successful!  Do the math and show angles from both MPUs
-  digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Blink the LED on each cycle
-
+
+    MPUMath(); // Successful!  Do the math and show angles from both MPUs
+    digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Blink the LED on each cycle
+  }
 }

@@ -257,6 +261,14 @@
  *
  */
 void MPUMath() {
+  // vars for angle values.
+  float Yaw[2], Pitch[2];
+  int yawDiff, pitchDiff;
+
+  //Add Roll if you need it, we don't for the Predator project;
+  //float Roll[2];
+  //int rollDiff;
+
   for (int i = 0; i < 2; i++) {
     // Get the raw data from the sensor
     mpus[i].dmpGetQuaternion(&q, fifoBuffer[i]);
@@ -264,33 +276,36 @@
     mpus[i].dmpGetYawPitchRoll(ypr, &q, &gravity);

     // Calculate readable angles
-    // Adds 90-degrees to center servos when sensor is level (e.g. 0 degrees)
-    // TODO: Move the +90 gyro/servo leveling magic number to another method,
-    // ...it doesn't belong here and will cause readability problems later.
-    Yaw = (ypr[0] * 180.0 / M_PI) + 90;
-    Pitch = (ypr[1] *  180.0 / M_PI) + 90;
-    Roll = (ypr[2] *  180.0 / M_PI) + 90;
-
-    //TODO: Add YPR values to temp var for each MPU, so that we can diff them.
+    Yaw[i] = (ypr[0] * 180.0 / M_PI);
+    Pitch[i] = (ypr[1] *  180.0 / M_PI);
+
+    //Calculate Roll if you need it.  We don't for the Predator project.
+    //Roll[i] = (ypr[2] *  180.0 / M_PI) + servoAngleOffset;

     // Serial.print the current angle values of the gyro position.
     // DPRINTSTIMER(x) argument is the number of milliseconds between print events
-    // Smaller numbers give more reliable switching between MPU 0 an 1 but seem to cause crashing (Buffer overrun?)
-    //    DPRINTSTIMER(1) {
-    //      DPRINTSFN(15, "\tValues for MPU :", i, 6, 1);
-    //      DPRINTSFN(15, "\tYaw:", Yaw, 6, 1);
-    //      DPRINTSFN(15, "\tPitch:", Pitch, 6, 1);
-    //      DPRINTSFN(15, "\tRoll:", Roll, 6, 1);
-    //      DPRINTLN();
-    //    }
-
-  }
-
-    // Timer - don't try and move the servos too frequently, they need time to get to the current position.
-    // TODO: Remove delay magic number and move to global var for tuning mechanical response
-    if (currentMillis >= prevMillis + 15) {
-      moveServos(round(Yaw), round(Pitch)); // TODO:  Change these values to the new diff'd values.
-    }
+    // Smaller numbers seem to give more reliable switching between MPU 0 an 1 but seem to cause crashing (Buffer overrun?)
+      // DPRINTSTIMER(15) {
+      //   DPRINTSFN(15, "\tValues for MPU :", i, 6, 1);
+      //   DPRINTSFN(15, "\tYaw:", Yaw[i], 6, 1);
+      //   DPRINTSFN(15, "\tPitch:", Pitch[i], 6, 1);
+          //Write out Roll if you're using it.  We don't for the predator Project
+          //   DPRINTSFN(15, "\tRoll:", Roll[i], 6, 1);
+      //   DPRINTLN();
+      // }
+
+  }
+
+  // Calculates the relative difference in angles between the two sensors.
+  // Adds 90-degrees, value defined above, to center servos when diff between sensors is level.
+  yawDiff = round((Yaw[1] - Yaw[0]) + servoAngleOffset);
+  pitchDiff = round((Pitch[1] - Pitch[0]) + servoAngleOffset);
+
+  // Timer - don't try and move the servos too frequently, they need time to get to the current position.
+  //if (currentMillis >= prevMillis + servoDelay) {
+    moveServos(yawDiff, pitchDiff); // TODO:  Change these values to the new diff'd values.
+  //}
+
 }

 /**
@@ -312,10 +327,11 @@
   // If so, assume actual gyro position and provide max servo value.

   // Invert Yaw values for my servo orientation.
+  // Comment out this line if your yaw is moving opposite the gyro.
   int invertedYaw = map(servoYaw, 0, 179, 179, 0);

   // Prevent the servos from panning farther than my head can rotate.
-  // May not be necessary after adding 2nd gyro and using relative angles.
+  // TODO: May not be necessary after adding 2nd gyro and using relative angles.
   if (invertedYaw > maxYaw) {
     invertedYaw = maxYaw;
   }
@@ -323,8 +339,8 @@
     invertedYaw = minYaw;
   }

-  // Prevent the servos from tilting farther than my head can nod.
-  // May not be necessary after adding 2nd gyro and using relative angles.
+  // Prevent the servos from tilting farther than my head can pitch.
+  // TODO: May not be necessary after adding 2nd gyro and using relative angles.
   if (servoPitch > maxPitch) {
     servoPitch = maxPitch;
   }
@@ -333,12 +349,9 @@
   }

   // Print out the current yaw and pitch angle values being sent to the servos.
-  //  DPRINTSTIMER(100) {
-  //    DPRINTSFN(15, "\tServo - Yaw:", servoYaw, 6, 1);
-  //    DPRINTSFN(15, "\tServo - invertYaw:", invertedYaw, 6, 1);
-  //    DPRINTSFN(15, "\tPitch:", servoPitch, 6, 1);
-  //    DPRINTLN();
-  //  }
+  Serial.print("\tServo - Yaw:"); Serial.print(servoYaw);
+  Serial.print("\tServo - invertYaw:"); Serial.print(invertedYaw);
+  Serial.print("\tPitch:"); Serial.println(servoPitch);

   // Move the servos to the current yaw/pitch values
   yawServo.write(invertedYaw);


New version without the schedulers: Using Ticker was nicer, but caused occasional crashes. Exceptions (9) "Load or store to an # unaligned address" was triggered inside the Adafruit VCNL4010 (readProximity) when it was call from the Ticker callback.

--- arduino/catdoor/catdoor.ino
+++ arduino/catdoor/catdoor.ino
@@ -1,17 +1,17 @@
 #include <ESP8266WiFi.h>
 #include <EEPROM.h>
-#include <Ticker.h>
 #include <PubSubClient.h>
+// #include <Ticker.h>

 #include "Adafruit_VCNL4010.h"

-Ticker tickerHeartbeat;
-Ticker tickerUpdate;
+// Ticker tickerHeartbeat;
+// Ticker tickerUpdate;

 Adafruit_VCNL4010 proxim_sensor;

 #define NB_PROXIM_SAMPLES 20
-#define NB_ANOMALY_COUNTS 8
+#define NB_ANOMALY_COUNTS 15

 uint16_t proxim_nominal = 2000;
 uint16_t proxim_anomaly = 100;
@@ -28,6 +28,7 @@
 PubSubClient mqttClient(espWifiClient);

 void heartbeat() {
+  publish_heartbeat();
   Serial.print("average promimity = ");
   Serial.println(proxim_nominal);
 }
@@ -67,26 +68,17 @@
     }
     counter++;
   }
-  // take a sample for the average every second (update is called at 10Hz)
-  if ( counter >= 9 ) {
+  // take a sample for the average every second (update is called at 20Hz)
+  if ( counter >= 20 ) {
     counter = 0;
   }
 }

-void publish_state(int8_t state) {
-  char payload[8];
-  if (state) {
-    strcpy(payload, "open");
-  }
-  else {
-    strcpy(payload, "closed");
-  }
+void connectClient() {
   while (!mqttClient.connected()) {
     Serial.print("Attempting MQTT connection...");
     if (mqttClient.connect("MistyDoor")) {
       Serial.println("connected");
-      payload[0] = static_cast<char>(state);
-      mqttClient.publish("/catdoor/state", payload);
     } else {
       Serial.print("failed, rc=");
       Serial.print(mqttClient.state());
@@ -94,6 +86,35 @@
       // Wait 5 seconds before retrying
       delay(5000);
     }
+  }
+
+}
+void publish_heartbeat() {
+  char payload[8];
+  sprintf(payload, "%d", proxim_nominal);
+//  connectClient();
+  if ( mqttClient.connected() ) {
+    mqttClient.publish("/catdoor/avgproxim", payload);
+  }
+  else {
+    Serial.println("Error: mqttClient not connected anymore");
+  }
+}
+
+void publish_state(int8_t state) {
+  char payload[8];
+  if (state) {
+    strcpy(payload, "open");
+  }
+  else {
+    strcpy(payload, "closed");
+  }
+//  connectClient();
+  if ( mqttClient.connected() ) {
+    mqttClient.publish("/catdoor/state", payload);
+  }
+  else {
+    Serial.println("Error: mqttClient not connected anymore");
   }
 }

@@ -120,10 +141,10 @@
   char pass[MAX_STRING_LENGTH];
   eeprom2str(0, ssid);
   eeprom2str(MAX_STRING_LENGTH, pass);
-  delay(100);   // not sure why, but examples work like this
   Serial.println();
   Serial.print("Connecting to network with SSID = ");
   Serial.println(ssid);
+  delay(100);

   // Connect to Wifi
   while (WiFi.status() != WL_CONNECTED) {
@@ -134,6 +155,7 @@
   Serial.println("WiFi connected");
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
+
 }

 void setup() {
@@ -141,7 +163,7 @@
   for (uint16_t i = 0; i < NB_PROXIM_SAMPLES; i++) {
     proxim_samples[i] = proxim_nominal;
   }
-  Serial.begin(9600);
+  Serial.begin(115200);
   if ( !proxim_sensor.begin() ) {
     Serial.println("Proximity Sensor not found: stop!");
     while (1);
@@ -154,14 +176,33 @@
   setup_wifi();
   mqttClient.setServer(MQTT_SERVER, MQTT_PORT);

+  // Prepare client
+  connectClient();
+
   // Schedulers
-  tickerHeartbeat.attach(10, heartbeat);
-  tickerUpdate.attach_ms(100, update);
+  // tickerHeartbeat.attach(10, heartbeat);
+  // tickerUpdate.attach_ms(100, update);

 }

 void loop() {
   static bool raised = false;
+  static uint8_t counter = 0;
+  static unsigned long last_millis = millis();
+
+  // publish heartbeat
+  unsigned long now_millis = millis();
+  if ( now_millis - last_millis > 50 ) {
+    update();
+    counter++;
+    if ( counter == 200 ) {
+      heartbeat();
+      counter = 0;
+    }
+    last_millis = now_millis;
+  }
+
+  // take care of event if any
   if ( !raised && event_count >= NB_ANOMALY_COUNTS ) {
     door_opened();
     raised = true;
@@ -170,10 +211,13 @@
     door_closed();
     raised = false;
   }
+
   // Let the MQTT client do some work
   mqttClient.loop();

+  delay(10);
+
   // Let the ESP Wifi do some work?
-  yield();
-}
-
+  //yield();
+}
+


Add more example configurations.

Add more example configurations.

--- examples/UART/CosaSoftUART/CosaSoftUART.ino
+++ examples/UART/CosaSoftUART/CosaSoftUART.ino
@@ -27,15 +27,22 @@
 #include "Cosa/Watchdog.hh"
 #include "Cosa/Soft/UART.hh"

+OutputPin led(Board::LED);
 IOBuffer<Soft::UART::RX_BUFFER_MAX> ibuf;
+
 #if defined(BOARD_ATTINY)
+// Arduino Tiny: RX(D2), TX(D1)
 Soft::UART uart(Board::D2, Board::PCI1, &ibuf);
 #define BAUDRATE 38400
+#elif defined(BOARD_ATMEGA2560)
+// Arduino Mega: RX(D11), TX(D10)
+Soft::UART uart(Board::D11, Board::PCI4, &ibuf);
+#define BAUDRATE 57600
 #else
+// Arduino Standard: RX(D5), TX(D4)
 Soft::UART uart(Board::D5, Board::PCI4, &ibuf);
 #define BAUDRATE 57600
 #endif
-OutputPin led(Board::LED);

 void setup()
 {


In stepper_driver, added support for x (disable Serial) and X (Enable serial) commands via I2C

--- examples/stepper_driver/command_parsing.ino
+++ examples/stepper_driver/command_parsing.ino
@@ -98,6 +98,13 @@
       v = 0;
       PROMPT;
       break;
+    case 'x':
+      Serial.end();
+      v = 0;
+    case 'X':
+      Serial.begin(115200);
+      v = 0;
+      PROMPT;
     default:
       v = 0;
       PROMPT;


compass example: further cleanup

compass example: further cleanup

--- ZumoMotors/examples/CompassExample/CompassExample.ino
+++ ZumoMotors/examples/CompassExample/CompassExample.ino
@@ -4,17 +4,22 @@
 #include <LSM303.h>

 /* This example uses ZumoMotors, Wire, and LSM303 (compass) library to
- * drive the Zumo in squares. To do this, the Zumo first calibrates to
- * find North and East. Calibration is accomplished in setup().
+ * drive the Zumo in squares. To do this, the Zumo first calibrates
+ * the compass to account for offsets in its output. Calibration is
+ * accomplished in setup().
+ *
  * In loop(), The driving angle then changes its offset by 90 degrees
  * from the heading every second. Essentially, this navigates the
  * Zumo to drive in square patterns.
  *
- * It is important to note that electronics, buildings, and environment
- * may adversly affect readings from the LSM303 compass.
+ * It is important to note that stray magnetic fields from electric
+ * current (including from the Zumo's own motors) and the environment
+ * (for example, steel rebar in a concrete floor) might adversely
+ * affect readings from the LSM303 compass and make them less
+ * reliable.
  */

-#define SPEED 200
+#define SPEED 200 // maximum motor speed when turning or going straight

 #define CALIB_SAMPLES 70
 #define CRA_REG_M_220HZ 0x1C // CRA_REG_M value for magnetometer 220 Hz update rate
@@ -132,26 +137,23 @@
   Serial.print(heading);
   Serial.print("    Difference: ");
   Serial.print(relHeading);
-
-
-  // We now want to turn 90 degrees relative to the direction we are pointing at.
-  // This will help account for variable magnetic field.
-
-  // We want to take a relative heading and turn 90 degrees to make our right turn
+
+  // If we have turned to the direction we want to be pointing, go straight and then do another turn
   if((relHeading < DEVIATE_RIGHT_THRESHOLD) || (relHeading > DEVIATE_LEFT_THRESHOLD))
   {
     motors.setSpeeds(SPEED, SPEED);

     Serial.print("   Straight");

-      delay(1000);
-
-      motors.setSpeeds(0, 0);
-      delay(100);
-
-      // We now want to turn 90 degrees relative to the direction we are pointing at.
-      // This will help account for variable magnetic field.
-      targetHeading = (averageHeading() + 90) % 360;
+    delay(1000);
+
+    // turn off motors and wait a short time to reduce interference from motors
+    motors.setSpeeds(0, 0);
+    delay(100);
+
+    // We now want to turn 90 degrees relative to the direction we are pointing at.
+    // This will help account for variable magnetic field.
+    targetHeading = (averageHeading() + 90) % 360;
   }
   else
   {
@@ -171,7 +173,7 @@

 // The closer we get to our driving angle, the slower we will turn.
 // We do not want to overshoot our direction.
-// turnRight(), takes in the ideal speed and refactors it accordingly to how close
+// turnRight() takes the ideal speed and refactors it accordingly to how close
 // the zumo is pointing towards the direction we want to drive.
 void turnRight(int refactor)
 {
@@ -182,7 +184,7 @@

 // The closer we get to our driving angle, the slower we will turn.
 // We do not want to overshoot our direction.
-// turnLeft(), takes in the ideal speed and refactors it accordingly to how close
+// turnLeft() takes the ideal speed and refactors it accordingly to how close
 // the zumo is pointing towards the direction we want to drive.
 void turnLeft(int refactor)
 {
@@ -191,13 +193,11 @@
   motors.setLeftSpeed(-SPEED*adjust - 100);
 }

-// Heading gives you degrees starting clockwise away from the from vector v
+// Converts x and y components of a vector to a heading in degrees
 int heading(LSM303::vector v)
 {
-  int x = (int)v.x;
-  int y = (int)v.y;
-  float xScaled =  2.0*(float)(x - compass.m_min.x) / ( compass.m_max.x - compass.m_min.x) - 1.0;
-  float yScaled =  2.0*(float)(y -  compass.m_min.y) / (compass.m_max.y - compass.m_min.y) - 1.0;
+  float xScaled =  2.0*(float)(v.x - compass.m_min.x) / ( compass.m_max.x - compass.m_min.x) - 1.0;
+  float yScaled =  2.0*(float)(v.y -  compass.m_min.y) / (compass.m_max.y - compass.m_min.y) - 1.0;

   int angle = round(atan2(yScaled, xScaled)*180 / M_PI);
   if (angle < 0)
@@ -205,7 +205,7 @@
   return angle;
 }

-// Yields a relative heading in respect to our driving angle/heading
+// Yields the angle difference in degrees between two headings
 int relativeHeading(int headingFrom, int headingTo)
 {
   if(headingFrom < headingTo)
@@ -231,7 +231,7 @@
   }
   avg.x /= 10.0;
   avg.y /= 10.0;
-  avg.z = 0;
+
   // avg is the average measure of the north vector.
   return heading(avg);
 }


Arduino: slow down smoothing factor

Arduino: slow down smoothing factor

--- arduino-light-dimmer-ble/arduino-light-dimmer-ble.ino
+++ arduino-light-dimmer-ble/arduino-light-dimmer-ble.ino
@@ -108,7 +108,7 @@
     }

     void set_duty_cycle_smoothing_rate(uint8_t value) {
-      duty_cycle_smoothing_rate_us_ = ((uint16_t) (value + 1)) << 2;
+      duty_cycle_smoothing_rate_us_ = ((uint16_t) (value + 1)) << 1;
     }

   private:


Combination of servo and motors

Combination of servo and motors

--- motor/motor.ino
+++ motor/motor.ino
@@ -1,9 +1,25 @@
+#include <Servo.h>
+Servo myservo;
+
 int motorPin1 = 2;
 int motorPin2 = 4;

 void setup() {
   pinMode(motorPin1, OUTPUT);
   pinMode(motorPin2, OUTPUT);
+
+  myservo.attach(11);
+  int pos = myservo.read();
+
+  //set servo at 45 degrees to begin with
+  while (pos != 180) {
+    myservo.write(pos);
+    delay(15);
+    pos++;
+  }
+  myservo.write(130);
+  delay(2000);
+
 }

 void loop() {
@@ -24,31 +40,6 @@
  delay(200);
 }

-
-
-
-
-
-#include <Servo.h>
-Servo myservo;
-
-void setup() {
-  myservo.attach(11);
-  int pos = myservo.read();
-
-  //set servo at 45 degrees to begin with
-  while (pos != 180) {
-    myservo.write(pos);
-    delay(15);
-    pos++;
-  }
-  myservo.write(130);
-  delay(2000);
-}
-
-void loop() {
-}
-
 //opens cage to deliver drink
 void openCage() {
   myservo.write(85);


Adding smoke detection MQ2

Adding smoke detection MQ2

--- arduinoHouse/mqttRelayDelays/mqttRelayDelays.ino
+++ arduinoHouse/mqttRelayDelays/mqttRelayDelays.ino
@@ -23,6 +23,10 @@
   There is a 400ms between 2 mutuallyExcluded relays

   Pins 2->7 are used as input (switch) detection. Their state are published on domogik/relayArduinoPin1
+
+  A MQ2 smoke sensor on A0
+  https://create.arduino.cc/projecthub/Aritro/smoke-detection-using-mq-2-gas-sensor-79c54a
+

 */
 #include <Ethernet.h>
@@ -42,6 +46,7 @@
 int value = 0;
 AsyncDelay delay_400ms;
 AsyncDelay delay_30s;
+AsyncDelay delay_5s;

 //MutuallyExclude the 'on' state between pairs of relays (for shutter to prevent up and down at the same time)
 //ask R1 to turn on while R2 = on -> turns off R2 first (and broadcasts 'domogik/in/relay/r2 0')
@@ -68,6 +73,8 @@
 #define PIN_DETECT_4 5
 #define PIN_DETECT_5 6
 #define PIN_DETECT_6 7
+#define SMOKE_PIN A0
+
 Bounce debounce1 = Bounce();
 Bounce debounce2 = Bounce();
 Bounce debounce3 = Bounce();
@@ -97,7 +104,9 @@
 void delayTimers() {
   delay_400ms.start(400, AsyncDelay::MILLIS);
   delay_30s.start(30000, AsyncDelay::MILLIS);
-}
+  delay_5s.start(5000, AsyncDelay::MILLIS);
+}
+
 void  publishStates() {
   for (int thisPin = 0; thisPin < pinCount; thisPin++) {
     char* state = relayStates[thisPin] == HIGH ? "0" : "1";
@@ -238,6 +247,7 @@
   }
   pinMode(13, OUTPUT);

+
   //init state relayboard
   //turnAllOff();

@@ -250,6 +260,7 @@
   pinMode(PIN_DETECT_4, INPUT_PULLUP);
   pinMode(PIN_DETECT_5, INPUT_PULLUP);
   pinMode(PIN_DETECT_6, INPUT_PULLUP);
+  pinMode(SMOKE_PIN, INPUT);
   debounce1.attach(PIN_DETECT_1);
   debounce2.attach(PIN_DETECT_2);
   debounce3.attach(PIN_DETECT_3);
@@ -281,6 +292,15 @@
     reconnect();
   }

+  if (delay_5s.isExpired()) {
+    int analogSensor = analogRead(SMOKE_PIN);
+    char bufferSensor[6];
+    sprintf(bufferSensor, "%d", analogSensor);
+    client.publish("domogik/smoke", bufferSensor);
+    delay_5s.repeat();
+  }
+
+
   if (delay_400ms.isExpired()) {
     setStates();
     delay_400ms.repeat();


Update Example1.ino

Update Example1.ino

--- sketches/Example1.ino
+++ sketches/Example1.ino
@@ -2,6 +2,32 @@
    Based on the DigitalReadSerial example provided by Arduino.
    This is a slight modification. If the button state is changed from LOW to HIGH
    then the text 'BUTTON PRESSED' is emitted over Serial connection.
+
+   Use the schematic/circuit suggested here http://arduino.cc/en/Tutorial/DigitalReadSerial
+
+   You'll need to install mosquitto or another MQTT broker.
+
+   1. Start the mosquitto broker (using default host/port localhost:1883)
+   2. Pipe the serial output through mqtt like this...
+
+      tail -f /dev/tty.usbmodemfd131 | mosquitto_pub -t arduino -l
+
+   3. Start up Craftbukkit like this...
+
+      java -cp sc-mqtt.jar:craftbukkit.jar org.bukkit.craftbukkit.Main
+
+   4. At the server console prompt type
+
+      js var mqtt = require('sc-mqtt'), client = mqtt.client();
+      js client.connect();
+      js client.subscribe('arduino');
+      js world = server.getWorld('world');
+      js client.onMessageArrived(function(topic,message){ var time = world.time+12000; world.time=time });
+
+   5. Launch the minecraft client and join the server in multi-player mode.
+
+   6. Press the pushbutton to advance time by 1/2 a day.
+
  */

 // digital pin 2 has a pushbutton attached to it. Give it a name:


Check if RTC running at startup; support flashing both LEDs

Add support to flash both LEDs at same time.

Flash both LEDs once at initial startup.

Test the RTC returned time twice at startup and if the time is the same,
flash both LEDs 8 times.

--- sketches/control/single_bench/single_bench.ino
+++ sketches/control/single_bench/single_bench.ino
@@ -29,10 +29,10 @@
 const byte maxm2Dev = 13;

 // Start and end hours of operation
-const unsigned char start_hh = 18;
-const unsigned char start_mm = 39;
-const unsigned char stop_hh = 18;
-const unsigned char stop_mm = 40;
+const unsigned char start_hh = 19;
+const unsigned char start_mm = 50;
+const unsigned char stop_hh = 19;
+const unsigned char stop_mm = 51;

 // Length of first MaxM light cycle in seconds
 // The light scripts on the MaxMs MUST be
@@ -48,16 +48,11 @@
 // const byte check_cycle = 60;
 const byte check_cycle = 15;

-// Somewhere I got the idea there was a pause needed
-// at the end of the setup() function. Set it to
-// 2 seconds.
-const byte startup_pause = 20;
-
 // LEDs
 const byte led1 = 1;
 const byte led2 = 2;

-// boilerplate for low-power waiting
+// Boilerplate for low-power waiting
 ISR(WDT_vect) { Sleepy::watchdogEvent(); }

 // RTC based on the DS1307 chip connected via the Ports library
@@ -106,28 +101,32 @@
     return (hh * 60) + mm;
 }

-void doFlash(const Port ledPort, const byte ledNum, const byte cnt) {
+void ledOn (const Port ledPort, byte mask) {
+  if (mask & 1) {
+    ledPort.digiWrite(1);
+  }
+  if (mask & 2) {
+    ledPort.digiWrite2(1);
+  }
+}
+
+void ledOff (const Port ledPort, byte mask) {
+  if (mask & 1) {
+    ledPort.digiWrite(0);
+  }
+  if (mask & 2) {
+    ledPort.digiWrite2(0);
+  }
+}
+
+void doFlash(const Port ledPort, const byte mask, const byte cnt) {
 #ifdef DEBUG_FLASH
-    /* Serial.print("Flash LED "); */
-    /* Serial.print(ledNum); */
-    /* Serial.print(" "); */
-    /* Serial.print(cnt); */
-    /* Serial.println(" times"); */
-    /* Serial.flush(); */
-
     byte cntr = cnt;
     while (cntr > 0) {
         cntr--;
-        if (ledNum == 1) {
-          ledPort.digiWrite(1);
-          Sleepy::loseSomeTime(50);
-          ledPort.digiWrite(0);
-        } else {
-          ledPort.digiWrite2(1);
-          Sleepy::loseSomeTime(50);
-          ledPort.digiWrite2(0);
-        }
-
+        ledOn(ledPort, mask);
+        Sleepy::loseSomeTime(50);
+        ledOff(ledPort, mask);
         if (cntr < 1) break;
         Sleepy::loseSomeTime(250);
     }
@@ -172,6 +171,12 @@
     // Not sure this is needed since it is a null function
     RTC.begin();

+    ledPort.mode(OUTPUT);
+    ledPort.mode2(OUTPUT);
+
+    // Flash both LEDs to show setup starting
+    doFlash(ledPort, 1 + 2, 1);
+
     // Turn the radio off completely
     rf12_initialize(17, RF12_868MHZ);
     rf12_sleep(RF12_SLEEP);
@@ -179,9 +184,6 @@
     // Convert start hh:mm to a start minutes
     start_min = toMin(start_hh, start_mm);
     stop_min = toMin(stop_hh, stop_mm);
-
-    ledPort.mode(OUTPUT);
-    ledPort.mode2(OUTPUT);

     // The MaxMs are supposed to be programmed to not start on power-on
     // but turn thenm off just to be sure
@@ -205,11 +207,19 @@
     maxm2.write(0);
     maxm2.stop();

-    //TODO check the RTC is working correctly
-
-    // Start tasks after a pause for the power supply to settle
-    // Not sure where the "pause" came from!
-    scheduler.timer(OPER_TIME, startup_pause);
+    // Check the RTC is working correctly
+    DateTime t1 = RTC.now();
+    // Wait 2 seconds and see if the clock changes
+    Sleepy::loseSomeTime(2000);
+    DateTime t2 = RTC.now();
+
+    // If no time elapsed, RTC is stopped so blink both LEDs 8 times
+    if (t1.second() == t2.second()) {
+        doFlash(ledPort, 1 + 2, 8);
+    }
+
+    // Start the main task
+    scheduler.timer(OPER_TIME, 0);
 }

 void loop () {


Attempt to fix how time is measured before "sleeping."

--- xy.ino
+++ xy.ino
@@ -101,8 +101,9 @@

 void setup() {
    int t;
-   unsigned long desiredDuration = 3600 * 1000; // total desired run time, milliseconds
-
+   unsigned long desiredDuration = 3600UL * 1000UL; // total desired run time, milliseconds
+   // desiredDuration = 120UL * 1000UL;
+
    strip.begin();
    // clearStrip();
    strip.show();
@@ -454,7 +455,7 @@
    for (i = 0; i < 25; i += 2)
       strip.setPixelColor( i, c);
    strip.show();
-   delay( 5000);
+   delay( 10000);

    // Old code, to be deleted at some point:
    // for (run = 0; run < 3; run++)


Added the header to the Bridge.ino example Removed Serial.begin(), there are no serial prints in the sketch.

--- libraries/Bridge/examples/Bridge/Bridge.ino
+++ libraries/Bridge/examples/Bridge/Bridge.ino
@@ -1,12 +1,32 @@
+/*
+  Bridge
+
+ This example shows how to use the Bridge library to access the digital
+ and analog pins on the board through REST calls.
+ It demonstrates how you can create your own API when using REST style
+ calls through the browser.
+
+ Example of possible commands are listed here:

-// Possible commands are listed here:
-//
-// "digital/13"     -> digitalRead(13)
-// "digital/13/1"   -> digitalWrite(13, HIGH)
-// "analog/2/123"   -> analogWrite(2, 123)
-// "analog/2"       -> analogRead(2)
-// "mode/13/input"  -> pinMode(13, INPUT)
-// "mode/13/output" -> pinMode(13, OUTPUT)
+ "/arduino/digital/13"     -> digitalRead(13)
+ "/arduino/digital/13/1"   -> digitalWrite(13, HIGH)
+ "/arduino/analog/2/123"   -> analogWrite(2, 123)
+ "/arduino/analog/2"       -> analogRead(2)
+ "/arduino/mode/13/input"  -> pinMode(13, INPUT)
+ "/arduino/mode/13/output" -> pinMode(13, OUTPUT)
+
+ The circuit:
+ there is no need of a particular circuit, you can connect:
+ * some analog sensors to the analog inputs
+ * LEDs to digital or analog outputs
+ * digital sensors such as buttos to the digital inputs
+
+ created April 2013
+ by Cristian Maglie
+
+ This example code is in the public domain.
+
+ */

 #include <Bridge.h>
 #include <YunServer.h>
@@ -17,8 +37,6 @@
 YunServer server;

 void setup() {
-  Serial.begin(9600);
-
   // Bridge startup
   pinMode(13,OUTPUT);
   digitalWrite(13, LOW);


Fixed typo in LightBrightMain.ino

Fixed typo in LightBrightMain.ino

--- lightbright/LightBrightMain/LightBrightMain.ino
+++ lightbright/LightBrightMain/LightBrightMain.ino
@@ -8,7 +8,8 @@
 */

 // Third-party headers
-#include <PS2Keyboard.h>
+# #include <PS2Keyboard.h>
+

 // LightBright headers


fix controller bugs

fix controller bugs

--- document/arduino/motor_control/motor_control.ino
+++ document/arduino/motor_control/motor_control.ino
@@ -1,7 +1,7 @@
 /*
 Copyright 2017 ADLINK Technology Inc.
-Developer: Chester, Tseng
-           HaoChih, LIN
+Developer: Chester, Tseng (for pySerial & encoder)
+           HaoChih, LIN (for controller)
 Email: chester.tseng@adlinktech.com
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
@@ -26,6 +26,8 @@
 // Timer internal
 const int timer_period = 50; // ms
 const float timer_hz = 1000.0/( (float)timer_period ); // hz
+const int filter_size = 5;
+const int counter_protect = 200;

 // encoder
 volatile int decoder_pin_1_counter = 0;
@@ -33,12 +35,14 @@
 volatile int decoder_pin_1_delay_counter = 0;
 volatile int decoder_pin_2_delay_counter = 0;
 volatile int encoder_res = 18; // 20 pulse in a circle --> 360/20 = 18(deg/pulse)
+volatile int average_filter_pin1[filter_size] = {}; // all zeros
+volatile int average_filter_pin2[filter_size] = {}; // all zeros

 // controller
 volatile float WL_ref = 0.0; //reference speed for left wheel (deg/sec)
 volatile float WR_ref = 0.0;
-volatile float Kp_L = 0.1;
-volatile float Kp_R = 0.1;
+volatile float Kp_L = 0.2; //0.11 //without loading
+volatile float Kp_R = 0.2;

 void setup() {
   // Set 4 pwm channel pin to output
@@ -73,21 +77,13 @@
 void loop() {
     if (Serial.available()) {
       String commad_string = Serial.readString();
-      String out_1 = getValue(commad_string, ',', 0); //getValue func should be removed (TBD)
-      String out_2 = getValue(commad_string, ',', 1);
-      String out_3 = getValue(commad_string, ',', 2);
-      String out_4 = getValue(commad_string, ',', 3);
-      if (out_1 != NULL)
-        WL_ref =  out_1.toFloat(); // deg/sec
-
-      if (out_2 != NULL)
-        WL_ref = -out_2.toFloat();
-
-      if (out_3 != NULL)
-        WR_ref =  out_3.toFloat();
-
-      if (out_4 != NULL)
-        WR_ref = -out_4.toFloat();
+      float out_1 = getValue(commad_string, ',', 0).toFloat(); //getValue func should be removed (TBD)
+      float out_2 = getValue(commad_string, ',', 1).toFloat();
+      float out_3 = getValue(commad_string, ',', 2).toFloat();
+      float out_4 = getValue(commad_string, ',', 3).toFloat();
+
+      WL_ref =  out_1 - out_2; // deg/sec, pos: forward, neg: backward
+      WR_ref =  out_3 - out_4; // deg/sec
     }
 }

@@ -101,16 +97,42 @@

 // convert required deg/s to pwm command (based on statistical)
 float feedforward(float value) {
-  return 0.1335 * value + 7.07;
+  //return 0.1335 * value + 7.07; //withous laoding
+    return 0.4 * value;
 }

 void controller_repoter_isr() {
+  // copy current counter
+  int pin1_counter = decoder_pin_1_counter;
+  int pin2_counter = decoder_pin_2_counter;
+
+  // average filter of encoder data
+  float average_counter_pin1 = 0.0;
+  for(int i=0; i<filter_size-1; i++)
+  {
+    average_filter_pin1[i] = average_filter_pin1[i+1];
+    average_counter_pin1 = average_counter_pin1 + average_filter_pin1[i+1];
+  }
+  average_filter_pin1[filter_size-1] = pin1_counter;
+  average_counter_pin1 = average_counter_pin1 + pin1_counter;
+  average_counter_pin1 = average_counter_pin1/(float)filter_size;
+
+  float average_counter_pin2 = 0.0;
+  for(int i=0; i<filter_size-1; i++)
+  {
+    average_filter_pin2[i] = average_filter_pin2[i+1];
+    average_counter_pin2 = average_counter_pin2 + average_filter_pin2[i+1];
+  }
+  average_filter_pin2[filter_size-1] = pin2_counter;
+  average_counter_pin2 = average_counter_pin2 + pin2_counter;
+  average_counter_pin2 = average_counter_pin2/(float)filter_size;
+
   // controller (feedforward + feedback)
   float cmd = 0.0;
   float error = 0.0;
-  if(WL_ref >= 0.0)
-  {
-    error = WL_ref - (float)(decoder_pin_1_counter*encoder_res)*timer_hz; // deg/sec
+  if(WL_ref > 0.0)
+  {
+    error = WL_ref - average_counter_pin1*(float)(encoder_res)*timer_hz; // deg/sec
     cmd = feedforward(WL_ref) + error*Kp_L;
     if(cmd>=0.0)
     {
@@ -123,10 +145,10 @@
       analogWrite(out2_pin, -(int)cmd);
     }
   }
-  else // the encoder has no capability of distinguishing the cw/ccw rotation
-  {
-    error = -WL_ref - (float)(decoder_pin_1_counter*encoder_res)*timer_hz; // deg/sec
-    cmd = feedforward(WL_ref) + error*Kp_L;
+  else if(WL_ref < 0.0) // the encoder has no capability of distinguishing the cw/ccw rotation
+  {
+    error = -WL_ref - average_counter_pin1*(float)(encoder_res)*timer_hz; // deg/sec
+    cmd = feedforward(-WL_ref) + error*Kp_L;
     if(cmd>=0.0)
     {
       analogWrite(out2_pin, (int)cmd);
@@ -138,10 +160,15 @@
       analogWrite(out1_pin, -(int)cmd);
     }
   }
-
-  if(WR_ref >= 0.0)
-  {
-    error = WR_ref - (float)(decoder_pin_2_counter*encoder_res)*timer_hz; // deg/sec
+  else // == 0
+  {
+    analogWrite(out1_pin, 0);
+    analogWrite(out2_pin, 0);
+  }
+
+  if(WR_ref > 0.0)
+  {
+    error = WR_ref - average_counter_pin2*(float)(encoder_res)*timer_hz; // deg/sec
     cmd = feedforward(WR_ref) + error*Kp_R;
     if(cmd>=0.0)
     {
@@ -154,10 +181,10 @@
       analogWrite(out4_pin, -(int)cmd);
     }
   }
-  else // the encoder has no capability of distinguishing the cw/ccw rotation
-  {
-    error = -WR_ref - (float)(decoder_pin_2_counter*encoder_res)*timer_hz; // deg/sec
-    cmd = feedforward(WR_ref) + error*Kp_R;
+  else if(WR_ref < 0.0)// the encoder has no capability of distinguishing the cw/ccw rotation
+  {
+    error = -WR_ref - average_counter_pin2*(float)(encoder_res)*timer_hz; // deg/sec
+    cmd = feedforward(-WR_ref) + error*Kp_R;
     if(cmd>=0.0)
     {
       analogWrite(out4_pin, (int)cmd);
@@ -169,17 +196,22 @@
       analogWrite(out3_pin, -(int)cmd);
     }
   }
+  else // == 0
+  {
+    analogWrite(out3_pin, 0);
+    analogWrite(out4_pin, 0);
+  }

   // This is a workaround to prevent from motor idle when speed  = 0;
-  if (decoder_pin_1_delay_counter > (100 + WR_ref/encoder_res/timer_hz) ) {
+  if (decoder_pin_1_delay_counter > counter_protect ) {
     WR_ref = 0.0;
     analogWrite(out3_pin, 0);
     analogWrite(out4_pin, 0);
     decoder_pin_1_delay_counter = 0;
   }

-  if (decoder_pin_2_delay_counter > (100 + WL_ref/encoder_res/timer_hz) ) {
+  if (decoder_pin_2_delay_counter > counter_protect ) {
     WL_ref = 0.0;
     analogWrite(out1_pin, 0);
     analogWrite(out2_pin, 0);
@@ -188,15 +220,19 @@

   // report encoder info (deg/sec)
   char str[16];
-  sprintf(str, "%d,%d\r\n", decoder_pin_1_counter*encoder_res
-                          , decoder_pin_2_counter*encoder_res ); // deg/sec
+  sprintf(str, "%d,%d\r\n", (int)(average_counter_pin1*(float)encoder_res*timer_hz)
+                          , (int)(average_counter_pin2*(float)encoder_res*timer_hz) ); // deg/sec
   Serial.print(str);

   if (decoder_pin_1_counter == 0)
     decoder_pin_1_delay_counter += 1;
+  else
+    decoder_pin_1_delay_counter = 0;
   if (decoder_pin_2_counter == 0)
     decoder_pin_2_delay_counter += 1;
-
+  else
+    decoder_pin_2_delay_counter = 0;
+
   decoder_pin_1_counter = 0;
   decoder_pin_2_counter = 0;
 }


Curtain tweaks

Curtain tweaks

--- examples/sorenson-curtains/sorenson-curtains.ino
+++ examples/sorenson-curtains/sorenson-curtains.ino
@@ -72,7 +72,7 @@
   //input = new AudioShieldInput(&peak, &note);
   input = new FFTInput(&fft);

-  viz = new RippleVisualization(input, 50, 1, true);
+  viz = new RippleVisualization(input, 35, 1, true);

   anim1 = new CurtainAnimation(viz, leds1);
   anim2 = new CurtainAnimation(viz, leds2);
@@ -86,9 +86,9 @@
      25,    // height in pixels
      6,     // width in pixels
      1.0,   // height in ratio of visualiation
-     0.33,  // width in ratio of visualiation
+     0.17,  // width in ratio of visualiation
      0.0,   // rotation in radians
-     0.66,  // x distance from visualization start in ratio of visualization
+     0.75,  // x distance from visualization start in ratio of visualization
     -0.5,   // y "
      0.0);  // z "

@@ -97,9 +97,9 @@
      25,    // height in pixels
      6,     // width in pixels
      1.0,   // height in ratio of visualiation
-     0.33,  // width in ratio of visualiation
+     0.17,  // width in ratio of visualiation
      0.0,   // rotation in radians
-     0.33,  // x distance from visualization start in ratio of visualization
+     0.50,  // x distance from visualization start in ratio of visualization
     -0.5,   // y "
      0.0);  // z "

@@ -108,9 +108,9 @@
      25,    // height in pixels
      6,     // width in pixels
      1.0,   // height in ratio of visualiation
-     0.33,  // width in ratio of visualiation
+     0.17,  // width in ratio of visualiation
      0.0,   // rotation in radians
-     0.0,   // x distance from visualization start in ratio of visualization
+     0.25,   // x distance from visualization start in ratio of visualization
     -0.5,   // y "
      0.0);  // z "

@@ -119,9 +119,9 @@
      25,    // height in pixels
      6,     // width in pixels
      1.0,   // height in ratio of visualiation
-     0.33,  // width in ratio of visualiation
+     0.17,  // width in ratio of visualiation
      0.0,   // rotation in radians
-    -0.33,  // x distance from visualization start in ratio of visualization
+    -0.50,  // x distance from visualization start in ratio of visualization
     -0.5,   // y "
      0.0);  // z "

@@ -130,9 +130,9 @@
      25,    // height in pixels
      6,     // width in pixels
      1.0,   // height in ratio of visualiation
-     0.33,  // width in ratio of visualiation
+     0.17,  // width in ratio of visualiation
      0.0,   // rotation in radians
-    -0.66,  // x distance from visualization start in ratio of visualization
+    -0.75,  // x distance from visualization start in ratio of visualization
     -0.5,   // y "
      0.0);  // z "

@@ -141,9 +141,9 @@
      25,    // height in pixels
      6,     // width in pixels
      1.0,   // height in ratio of visualiation
-     0.33,  // width in ratio of visualiation
+     0.17,  // width in ratio of visualiation
      0.0,   // rotation in radians
-    -1.0,   // x distance from visualization start in ratio of visualization
+    -1.00,   // x distance from visualization start in ratio of visualization
     -0.5,   // y "
      0.0);  // z "


Return back to MPU6050 library as getMotion9 is not working and getMag is not in MPU0150 library Works very well!

--- Arduino/MPU9150_MS5611_IMU/MPU9150_MS5611_IMU.ino
+++ Arduino/MPU9150_MS5611_IMU/MPU9150_MS5611_IMU.ino
@@ -90,7 +90,7 @@

 #include <Wire.h>
 #include "I2Cdev.h" //from https://github.com/sparkfun/MPU-9150_Breakout.git
-#include "MPU9150.h"
+#include "MPU6050_9Axis_MotionApps41.h"
 #include <MS561101BA.h>

 #define OUTPUT_RATE_ms 50 // 20Hz
@@ -116,7 +116,7 @@
 // specific I2C addresses may be passed as a parameter here
 // AD0 low = 0x68 (default for InvenSense evaluation board)
 // AD0 high = 0x69
-MPU9150 accelGyroMag(0x69);
+MPU6050 accelGyroMag(0x69);

 // global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System)
 #define GyroMeasError PI * (40.0f / 180.0f)       // gyroscope measurement error in rads/s (shown as 3 deg/s)
@@ -277,8 +277,11 @@
     if(accelGyroMag.getIntDataReadyStatus() == 1)// wait for data ready status register to update all data registers
     {
       // read the raw sensor data
-        accelGyroMag.getMotion9(&a1, &a1, &a3, &g1, &g2, &g3, &m1, &m2, &m3);
-
+        //getMotion9 is not working properly for unknown reason
+        //accelGyroMag.getMotion9(&a1, &a1, &a3, &g1, &g2, &g3, &m1, &m2, &m3);
+        accelGyroMag.getAcceleration  ( &a1, &a2, &a3  );
+        accelGyroMag.getRotation  ( &g1, &g2, &g3  );
+        accelGyroMag.getMag  ( &m1, &m2, &m3 );
         a2 = -a2;// Invert y to get NED classical convention
         a1 = a1 + ACC_1_OFFSET;
         a2 = a2 + ACC_2_OFFSET;


New version of project 15. changed int to long for delays

--- Arduino/Project_15_Flasher/Project_15_Flasher.ino
+++ Arduino/Project_15_Flasher/Project_15_Flasher.ino
@@ -1,7 +1,7 @@
 const int flashPins[] = {7, 6, 5};

-const int overallDelay = 30; // seconds
-const int delayBetweenFlashes = 1; // seconds
+const long overallDelay = 20; // seconds
+const long delayBetweenFlashes = 1; // seconds

 void setup()
 {
@@ -13,7 +13,7 @@
 void loop()
 {
   flashCircle();
-  delay(overallDelay * 1000l);
+  delay(overallDelay * 1000);
 }

 void flashCircle()
@@ -23,7 +23,7 @@
     digitalWrite(flashPins[i], HIGH);
     delay(200);
     digitalWrite(flashPins[i], LOW);
-    delay(delayBetweenFlashes * 1000l);
+    delay(delayBetweenFlashes * 1000);
   }
 }