Update BB-UNIT.ino

Update BB-UNIT.ino

--- Firmware/BB-UNIT/BB-UNIT.ino
+++ Firmware/BB-UNIT/BB-UNIT.ino
@@ -7,14 +7,14 @@

  https://github.com/Gruniek/OPEN-BB-X
  Made by Daniel M/Gruniek/
-
+
  Compatible only with an Arduino MEGA 2560 and the specific PCB.
  PCB Link : https://github.com/Gruniek/OPEN-BB-X/tree/master/Head/Stabiliser/PCB
-
+
  --------------
  - Change log -
  --------------
-
+
  11/2016
  =========
  - Conversion for a Arduino Mega 2560 Board
@@ -23,61 +23,61 @@
  - ADD BOOT, STAT, ROTATE command
  - ADD Z motor configuration and production
  - ADD BOOT mode, for initilize or reinizialize the Droid position
-
+
  10/2016
  ==========
  - Add PID for X and Y
-
-
+
+
  To do list
  ==========
  - Add Z rotation controller
- - Add Rx/Tx from the motherboard for change de coordinate of the head,
+ - Add Rx/Tx from the motherboard for change de coordinate of the head,
   rotate the head and report to the remote the status off all sensors/positiom.
-
-
+
+
   Big thanks for http://r2builders.fr/ !
   Initial project : http://r2builders.fr/forum/viewtopic.php?f=26&t=3928&hilit=BB8+par+MOUS
-
+
   ===============
-  EXEMPLE COMMAND
+  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 >
+	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 >
   '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 remote
-
-  < ENABLE >
+
+  < ENABLE >
   'ENABLE a1 x1 z1 \n'    // ENABLE MOTOR AB, XY and Z (a = AB, x=XY, z = Z | 0 = desabled | 1 = enabled )
-
-
-
-  FOR AFTER
+
+
+
+  FOR AFTER
   http://tutorial.cytron.com.my/2014/05/15/wireless-uart-with-arduino-and-433mhz-or-434mhz-module/
   note : 10, 11, 12, 13, 14, 15, 50, 51, 52, 53
-
+
 */

 #include "Wire.h"
@@ -94,7 +94,7 @@

 // HC-12
 bool ifHead = false; // True if the head are wireless connected
-SoftwareSerial remote(10, 11); // RX, TX // For the renote communication
+SoftwareSerial controler(10, 11); // RX, TX // For the renote communication
 SoftwareSerial head(12, 13);   // RX, TX // For the head communication

@@ -107,36 +107,35 @@
 int16_t ax, ay, az;
 int16_t gx, gy, gz;

-// MOTOR CONFIGURATION // YOU CAN TOUCH THIS
-
-bool    invertA        = false; // INVERT THE A MOTOR DIRECTION
-bool    invertB        = false; // INVERT THE B MOTOR DIRECTION
-bool    invertX        = false; // INVERT THE X MOTOR DIRECTION
-bool    invertY        = true;  // INVERT THE Y MOTOR DIRECTION
-bool    invertXY       = false; // INVERT X Y AXIAL
-
-int     minX           = 45;    // SET THE MIN INCLINAISON FOR X
-int     maxX           = 135;   // SET THE MAX INCLINAISON FOR X
-int     minY           = 45;    // SET THE MIN INCLINAISON FOR Y
-int     maxY           = 135;   // SET THE MAX INCLINAISON FOR Y
-
-int     etalonX        = 0;     // AJUSTEMENT FOR X
-int     etalonY        = -6;    // AJUSTEMENT FOR Y
-
-int     hysteresis     = 1;     // HYSTERESSIS FOR THE ANGLE CALCULATION
-
-//
+// MOTOR CONFIGURATION // YOU CAN TOUCH THIS
+
+bool    INVERT_A       = false; // INVERT THE A MOTOR DIRECTION
+bool    INVERT_B       = false; // INVERT THE B MOTOR DIRECTION
+bool    INVERT_X       = false; // INVERT THE X MOTOR DIRECTION
+bool    INVERT_Y       = true;  // INVERT THE Y MOTOR DIRECTION
+bool    INVERT_XY      = false; // INVERT X Y AXIAL
+
+int     MIN_X          = 45;    // SET THE MIN INCLINAISON FOR X
+int     MAX_X          = 135;   // SET THE MAX INCLINAISON FOR X
+int     MIN_Y          = 45;    // SET THE MIN INCLINAISON FOR Y
+int     MAX_Y          = 135;   // SET THE MAX INCLINAISON FOR Y
+
+int     ETALON_X       = 0;     // AJUSTEMENT FOR X
+int     ETALON_Y       = -6;    // AJUSTEMENT FOR Y
+
+int     HYSTERESIS     = 1;     // HYSTERESSIS FOR THE ANGLE CALCULATION
+
 //=====================//
 // NOW YOU CAN'T TOUCH //
 //=====================//

 //PINOUT

-#define pinEnableXY      2      // Activation off all stepper
-#define pinEnableAB      3
-#define pinEnableZ       4
-
-#define pinStepA         5      // PIN STEP FOR X
+#define PIN_ENABLE_AB    2      // Activation off all stepper
+#define PIN_ENABLE_XY    3
+#define PIN_ENABLE_Z     4
+
+#define PIN_STEP_A       5      // PIN STEP FOR X
 #define pinDirA          6      // PIN DIRECTION FOR X

 #define pinStepB         7      // PIN STEP FOR X
@@ -153,7 +152,10 @@

 #define Z_POSITION       16      // PIN FOR THE DIGITAL INPUT FOR THE HEAD POSITION

-#define PING             13
+#define PING             13
+
+#define LIGHT            20      // Pin for turn on/off lighting on the ball (Great for a technical maintenance ;) )
+#define TRIGGER_LIGHT    21      // Pin trigger for the lighting

 #define CurrentBat1      0
 #define CurrentBat2      1
@@ -172,16 +174,16 @@
 bool dirA          = true;   // true = Front | false = back
 bool dirB          = true;   // true = Front | false = back

-int x              = 0;
-int y              = 0;
-int vx             = 0;
-int vy             = 0;
+int x              = 0;
+int y              = 0;
+int vx             = 0;
+int vy             = 0;

 int speedX         = 0;
 int speedY         = 0;
 int speedZ         = 0;
-int setpointX      = 90;
-int setpointY      = 90;
+int setpointX      = 90;
+int setpointY      = 90;

 int Zangle         = 0;
 bool newData       = false;
@@ -191,8 +193,8 @@
 int eStop          = 12; // PIN
 bool emgStop       = false;

-bool runX          = false;
-bool runY          = false;
+bool runX          = false;
+bool runY          = false;
 bool runZ          = false;
 bool directX       = false; // false = Gauche / true = droite
 bool directY       = false; // false = Gauche / true = droite
@@ -203,7 +205,7 @@
 bool zok           = false;

 long intX          = 0;
-long intY          = 0;
+long intY          = 0;

 bool production    = false;
 bool LED_PING      = false;
@@ -232,75 +234,76 @@
 //=============================================================================//
 void setup()
 {
-    // PINMODE
-    pinMode( pinEnableAB , OUTPUT );
-    pinMode( pinEnableXY , OUTPUT );
-    pinMode( pinEnableZ  , OUTPUT );
-    pinMode( pinDirX     , OUTPUT );
-    pinMode( pinStepX    , OUTPUT );
-    pinMode( pinDirY     , OUTPUT );
-    pinMode( pinStepY    , OUTPUT );
-    pinMode( pinDirA     , OUTPUT );
-    pinMode( pinStepA    , OUTPUT );
-    pinMode( pinDirB     , OUTPUT );
-    pinMode( pinStepB    , OUTPUT );
-    pinMode( PING        , OUTPUT );
-
-    pinMode( Z_POSITION  , INPUT  );
-
-    // SERIAL
-    Serial.begin(9600);
-
-    // Blabla, blablabla
-    Serial.println("==================================================");
-    Serial.println("  _______ ______     _     _  ______  ____ ______ ");
-    Serial.println(" (____   (____  )   | |   | |/ ___  |(____|______)");
-    Serial.println("  ____)  )____)  )__| |   | | |   | | | |   | |   ");
-    Serial.println(" |  __  (|  __  (___) |   | | |   | | | |   | |   ");
-    Serial.println(" | |__)  ) |__)  )  | |___| | |   | |_| |_  | |   ");
-    Serial.println(" |______/|______/   |______/|_|   |_(_____) |_|   ");
-    Serial.println("            _ Astromech Industrie _               ");
-    Serial.println("      > https://github.com/Gruniek/BB-UNIT <      ");
-    Serial.println("           > http://r2builders.fr/ <              ");
-    Serial.print("           FIRMWARE VERSION : ");
-    Serial.print(version);
-    Serial.println("               ");
-    Serial.println("==================================================");
-
-    Serial.println(" ");
-    Serial.println("[1]-Booting up...");
-
-    // Start of the I2C protocol
-    Serial.print("[2]-Initializing I2C devices...  I2C ADRESS :");
-    Serial.println(adress);
-    Wire.begin(adress);
-
-    // Start the MPU6050 Gyroscope
-    Serial.print("[3]-Connect to the MPU6050 : ");
-    accelgyro.initialize();
-    //Serial.println(accelgyro.testConnection());
-    Serial.println(accelgyro.testConnection() ? "Connection successful" : "Connection failed");
-
-    // Start the RF24 Radio controll
-    //Serial.println("[4]-Initializing RF24 devices...  ");
-    //radio.begin();
-    //radio.openReadingPipe(0, 00001);
-    //radio.startListening();
-
-    // Start remote connexion
-    Serial.println("[4]-Initializing HC-12 devices [REMOTE] ");
-    remote.begin(9600);
-
-    // Start remote connexion
-    if(ifHead)
-    {
-	Serial.println("[5]-Initializing HC-12 devices [ HEAD ] ");
-        remote.begin(9600);
-    }
-    // END OF BOOT/SETUP
-    Serial.println("====================");
-    Serial.println("Booting successful !");
-    Serial.println("====================");
+	// PINMODE
+	pinMode( PIN_ENABLE_AB , OUTPUT );
+	pinMode( PIN_ENABLE_XY , OUTPUT );
+	pinMode( PIN_ENABLE_Z  , OUTPUT );
+	pinMode( pinDirX       , OUTPUT );
+	pinMode( pinStepX      , OUTPUT );
+	pinMode( pinDirY       , OUTPUT );
+	pinMode( pinStepY      , OUTPUT );
+	pinMode( pinDirA       , OUTPUT );
+	pinMode( PIN_STEP_A    , OUTPUT );
+	pinMode( pinDirB       , OUTPUT );
+	pinMode( pinStepB      , OUTPUT );
+	pinMode( PING          , OUTPUT );
+	pinMode( LIGHT         , OUTPUT );
+
+	pinMode( Z_POSITION    , INPUT  );
+
+	// SERIAL
+	Serial.begin(9600);
+
+	// Blabla, blablabla
+	Serial.println("==================================================");
+	Serial.println("  _______ ______     _     _  ______  ____ ______ ");
+	Serial.println(" (____   (____  )   | |   | |/ ___  |(____|______)");
+	Serial.println("  ____)  )____)  )__| |   | | |   | | | |   | |   ");
+	Serial.println(" |  __  (|  __  (___) |   | | |   | | | |   | |   ");
+	Serial.println(" | |__)  ) |__)  )  | |___| | |   | |_| |_  | |   ");
+	Serial.println(" |______/|______/   |______/|_|   |_(_____) |_|   ");
+	Serial.println("            _ Astromech Industrie _               ");
+	Serial.println("      > https://github.com/Gruniek/BB-UNIT <      ");
+	Serial.println("           > http://r2builders.fr/ <              ");
+	Serial.print("           FIRMWARE VERSION : ");
+	Serial.print(version);
+	Serial.println("               ");
+	Serial.println("==================================================");
+
+	Serial.println(" ");
+	Serial.println("[1]-Booting up...");
+
+	// Start of the I2C protocol
+	Serial.print("[2]-Initializing I2C devices...  I2C ADRESS :");
+	Serial.println(adress);
+	Wire.begin(adress);
+
+	// Start the MPU6050 Gyroscope
+	Serial.print("[3]-Connect to the MPU6050 : ");
+	accelgyro.initialize();
+	//Serial.println(accelgyro.testConnection());
+	Serial.println(accelgyro.testConnection() ? "Connection successful" : "Connection failed");
+
+	// Start the RF24 Radio controll
+	//Serial.println("[4]-Initializing RF24 devices...  ");
+	//radio.begin();
+	//radio.openReadingPipe(0, 00001);
+	//radio.startListening();
+
+	// Start remote connexion
+	Serial.println("[4]-Initializing HC-12 devices [REMOTE] ");
+	controler.begin(9600);
+
+	// Start remote connexion
+	if(ifHead)
+	{
+		Serial.println("[5]-Initializing HC-12 devices [ HEAD ] ");
+		head.begin(9600);
+	}
+	// END OF BOOT/SETUP
+	Serial.println("====================");
+	Serial.println("Booting successful !");
+	Serial.println("====================");
 }

 //=============================================================================//
@@ -308,551 +311,602 @@
 //=============================================================================//
 void loop()
 {
-    unsigned long currentG = millis(); // millis();
-
-    if (currentG - trigG  >= trigGyro)
-    {
-    	trigG = currentG;
-
-         // GET MOTION
-         //-------------------------------------------------------------------------//
-    	accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
-	if(invertXY)
+	unsigned long currentG = millis(); // millis();
+
+	if (currentG - trigG  >= trigGyro)
 	{
-	    y = (((ax/180)+etalonX)+90);
-  	    x = (((ay/180)+etalonY)+90);
+		trigG = currentG;
+
+		// GET MOTION
+		//-------------------------------------------------------------------------//
+		accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
+		if(INVERT_XY)
+		{
+			y = (((ax / 180) + ETALON_X) + 90);
+			x = (((ay / 180) + ETALON_Y) + 90);
+		}
+		else
+		{
+			x = (((ax / 180) + ETALON_X) + 90);
+			y = (((ay / 180) + ETALON_Y) + 90);
+		}
 	}
-	else
+
+	// GET SERIAL AND RF24 DATA
+	//-------------------------------------------------------------------------//
+
+	char msg[64];
+	if (Serial.available() > 0)
 	{
-	    x = (((ax/180)+etalonX)+90);
-  	    y = (((ay/180)+etalonY)+90);
+		Serial.readBytesUntil('\n', msg, sizeof msg);
+		newData = true;
 	}
-    }
-
-    // GET SERIAL AND RF24 DATA
-    //-------------------------------------------------------------------------//
-
-    char msg[64];
-    if (Serial.available() > 0)
-    {
-    	Serial.readBytesUntil('\n', msg, sizeof msg);
-    	newData = true;
-    }
-
-    if (remote.available()) // IF RF24 ---> radio.available()
-    {
-    	char msg[64] = {0};
-    	remote.readBytesUntil('\n', msg, sizeof msg); // IF RF24 ---> radio.read(&msg, sizeof(msg));
-    	newData = true;
-    }
-
-    if(newData)
-    {
-	Serial.println(msg);
-	newData = false;
+
+	if (controler.available()) // IF RF24 ---> radio.available()
+	{
+		char msg[64] = {0};
+		controler.readBytesUntil('\n', msg, sizeof msg); // IF RF24 ---> radio.read(&msg, sizeof(msg));
+		newData = true;
+	}
+
+	if(newData)
+	{
+		Serial.println(msg);
+		newData = false;
+
+		if (strcmp(strtok(msg, " "), "SET") == 0)
+		{
+			Serial.println("UPDATE SETPOINT");
+			// trouvé le message
+			char *p;
+			while ((p = strtok(NULL, " ")) != NULL)
+			{
+				int val = atoi(p + 1);
+				switch (*p)
+				{
+					case 'x':
+						setpointX  = val;
+						break;
+					case 'y':
+						setpointY  = val;
+						break;
+					case 'm':
+						multiplier = val;
+						break;
+					case 'i':
+						INVERT_XY   = val;
+						break;
+					case 'j':
+						INVERT_X    = val;
+						break;
+					case 'k':
+						INVERT_Y    = val;
+						break;
+					case 'h':
+						HYSTERESIS = val;
+						break;
+				}
+			}
+		}
+
+		if (strcmp(strtok(msg, " "), "RUN") == 0)
+		{
+			Serial.println("ROll BB-8 ROLL !");
+			production = true;
+		}
+
+		if (strcmp(strtok(msg, " "), "STOP") == 0)
+		{
+			Serial.println("STOP");
+			production = false;
+		}
+
+		if (strcmp(strtok(msg, " "), "RESET") == 0)
+		{
+			Serial.println("RESET");
+			production = false;
+			emgStop    = false;
+		}
+
+		if (strcmp(strtok(msg, " "), "BOOT") == 0)
+		{
+			BOOT = true;
+			Serial.println("BOOTING UP...");
+			delay(2000);
+		}
+
+		if (strcmp(strtok(msg, " "), "ROTATE") == 0) // ROTATE d1 s100  <-- Rotate Z right, 18c/sec
+		{
+			// trouvé le message
+			char *p;
+			while ((p = strtok(NULL, " ")) != NULL)
+			{
+				int val = atoi(p + 1);
+				switch (*p)
+				{
+					case 'd':
+						directZ  = val;
+						break;
+					case 's':
+						speedZ   = val;
+						break;
+				}
+			}
+		}
+
+		if (strcmp(strtok(msg, " "), "MOVE") == 0)
+		{
+			Serial.println("UPDATE SETPOINT");
+			// trouvé le message
+			char *p;
+			while ((p = strtok(NULL, " ")) != NULL)
+			{
+				int val = atoi(p + 1);
+				switch (*p)
+				{
+					case 'a':
+						speedA  = val;
+						break;
+					case 'b':
+						speedB  = val;
+						break;
+					case 'c':
+						dirA    = val;
+						break;
+					case 'd':
+						dirB    = val;
+						break;
+				}
+			}
+		}
+
+		if (strcmp(strtok(msg, " "), "ENABLE") == 0)
+		{
+			//Serial.println("UPDATE SETPOINT");
+			// trouvé le message
+			char *p;
+			while ((p = strtok(NULL, " ")) != NULL)
+			{
+				int val = atoi(p + 1);
+				switch (*p)
+				{
+					case 'a':
+						enMotAB  = val;
+						break;
+					case 'x':
+						enMotXY  = val;
+						break;
+					case 'z':
+						enMotZ   = val;
+						break;
+				}
+			}
+		}
+
+	}
+
+	digitalWrite( PIN_ENABLE_AB, enMotAB );
+	digitalWrite( PIN_ENABLE_XY, enMotXY );
+	digitalWrite( PIN_ENABLE_Z,  enMotZ  );
+
+	if(BOOT)
+	{
+		enMotAB = true;
+		enMotXY = true;
+		enMotZ  = true;
+
+		// SET X IN POSITION
+		if(x < 90) directX = false;
+		else directX = true;
+
+		if(INVERT_X)
+		{
+			if(directX) directX = false;
+			else directX = true;
+		}
+		digitalWrite(pinDirX, directX); // dirX
+
+		if(x > (setpointX + HYSTERESIS || (x < setpointX - HYSTERESIS || !xok )))
+		{
+			digitalWrite(pinStepX, 1);
+			delayMicroseconds( 500 );
+			digitalWrite(pinStepX, 0);
+			delayMicroseconds( 500 );
+		}
+		else
+		{
+			if(!xok)
+			{
+				Serial.println("BOOT x1 ");
+				xok = true;
+				delay(2000);
+			}
+		}
+
+		// SET Y IN POSITION
+		if(y < 90) directY = false;
+		else directY = true;
+
+		if(INVERT_Y)
+		{
+			if(directY) directY = false;
+			else directY = true;
+		}
+		digitalWrite(pinDirY, directY); // dirX
+
+		if(y > (setpointY + HYSTERESIS) || (y < setpointY - HYSTERESIS || !yok))
+		{
+			digitalWrite(pinStepY, 1);
+			delayMicroseconds( 500 );
+			digitalWrite(pinStepY, 0);
+			delayMicroseconds( 500 );
+		}
+		else
+		{
+			if(!yok)
+			{
+				Serial.println("BOOT y1 ");
+				yok = true;
+				delay(2000);
+			}
+		}
+
+		// SET Z IN POSITION
+		if(!digitalRead(Z_POSITION))
+		{
+			digitalWrite(pinStepZ, 1);
+			delayMicroseconds( 500 );
+			digitalWrite(pinStepZ, 0);
+			delayMicroseconds( 500 );
+		}
+		else
+		{
+			if(!zok)
+			{
+				Serial.println("BOOT z1 ");
+				zok = true;
+				Zangle = 0;
+				delay(2000);
+			}
+		}
+
+		if( xok && yok && zok)
+		{
+			Serial.println("STAT b1 ");
+			Serial.println("Booting UP OK!");
+			Serial.println("SEND 'RUN \n' for start the production");
+			BOOT = false;
+		}
+	}
+
+	// PRODUCTION CODE
+	//-------------------------------------------------------------------------//
+	if(production && !emgStop)  //-
+	{
+		enMotAB = true;
+		enMotXY = true;
+		enMotZ  = true;
+
+		//======================================================================
+		//        d8888
+		//       d88888
+		//	d88P888
+		//     d88P 888
+		//    d88P  888
+		//   d88P   888
+		//  d8888888888
+		// d88P     888
+		//======================================================================
+		// MOTOR A (Left)
+
+		// Run the motor
+		if(speedA > 0) runA = true;
+		else runA = false;
+		speedA = 1000 / speedA;
+
+		// Motor direction / With inversion
+		if(INVERT_A)
+		{
+			if(dirA) dirA = false;
+			else dirA = true;
+		}
+		digitalWrite(pinDirA, dirA); // Set the direction
+
+		// Send Step inpultion to the motor
+		unsigned long currentA = millis(); // millis();
+		if (currentA - previousMillisA >= speedA)
+		{
+			previousMillisA = currentA;
+
+			if(runA)
+			{
+				digitalWrite(PIN_STEP_A, 1);
+				delayMicroseconds( 500 );
+				digitalWrite(PIN_STEP_A, 0);
+				delayMicroseconds( 500 );
+			}
+		}
+
+		//======================================================================
+		// 888888b.
+		// 888  "88b
+		// 888  .88P
+		// 8888888K.
+		// 888  "Y88b
+		// 888    888
+		// 888   d88P
+		// 8888888P"
+		//======================================================================
+		// MOTOR B (Right)
+
+		// Run the motor
+		if(speedB > 0) runB = true;
+		else runB = false;
+		speedB = 1000 / speedB;
+
+		// Motor direction / With inversion
+		if(INVERT_B)
+		{
+			if(dirB) dirB = false;
+			else dirB = true;
+		}
+		digitalWrite(pinDirB, dirB); // Set the direction
+
+		// Send Step inpultion to the motor
+		unsigned long currentB = millis(); // millis();
+		if (currentB - previousMillisB >= speedB)
+		{
+			previousMillisB = currentB;
+
+			if(runB)
+			{
+				digitalWrite(pinStepB, 1);
+				delayMicroseconds( 500 );
+				digitalWrite(pinStepB, 0);
+				delayMicroseconds( 500 );
+			}
+		}
+
+		//======================================================================
+		// Y88b   d88P
+		//  Y88b d88P
+		//   Y88o88P
+		//    Y888P
+		//    d888b
+		//   d88888b
+		//  d88P Y88b
+		// d88P   Y88b
+		//======================================================================
+
+		// Direction
+		if(x < 90) directX = false;
+		else directX = true;
+
+		if(INVERT_X)
+		{
+			if(directX) directX = false;
+			else directX = true;
+		}
+		digitalWrite(pinDirX, directX); // dirX
+
+		// Si ont doit demarer le moteur
+		if(x > (setpointX + HYSTERESIS) || (x < setpointX - HYSTERESIS ))
+		{
+			if(x > MIN_X && x < MAX_X) runX = true;
+			else runX = false;
+		}
+		else runX = false;
+
+		// Calcul du PID X
+		if(x < setpointX) vx = (setpointX - x);
+		if(x == 0) vx = 0;
+		if(x > setpointX) vx = (x - setpointX);
+
+		speedX = 1000 / (vx);
+		speedX = speedX * multiplier; // DEL
+		if(speedX < 15) speedX = 15;
+
+		// Mise en route du moteur
+		unsigned long currentX = millis();
+
+		if (currentX - previousMillisX >= speedX)
+		{
+			previousMillisX = currentX;
+
+			if(runX)
+			{
+				digitalWrite(pinStepX, 1);
+				delayMicroseconds( 500 );
+				digitalWrite(pinStepX, 0);
+				delayMicroseconds( 500 );
+			}
+		}
+
+		//======================================================================
+		// Y88b   d88P
+		//  Y88b d88P
+		//   Y88o88P
+		//    Y888P
+		//     888
+		//     888
+		//     888
+		//     888
+		//======================================================================
+
+		// Direction
+		if(y < 90) directY = false;
+		else directY = true;
+		if(INVERT_Y)
+		{
+			if(directY) directY = false;
+			else directY = true;
+		}
+		digitalWrite(pinDirY, directY);
+
+		// Si ont doit demarer le moteur
+		if(y > (setpointY + HYSTERESIS) || (y < setpointY - HYSTERESIS ))
+		{
+			if(y > MIN_Y && y < MAX_Y) runY = true;
+			else runY = false;
+		}
+		else runY = false;
+
+		// Calcul du PID Y
+		if(y < setpointY) vy = (setpointY - y);
+		if(y == 0) vy = 0;
+		if(y > setpointY) vy = (y - setpointY);
+
+		speedY = 1000 / (vy);
+		speedY = speedY * multiplier; // DEL
+		if(speedY < 15) speedY = 15;
+
+		// Mise en route du moteur
+		unsigned long currentY = millis(); // millis();
+
+		if (currentY - previousMillisY >= speedY)
+		{
+			previousMillisY = currentY;
+
+			if(runY)
+			{
+				digitalWrite(pinStepY, 1);
+				delayMicroseconds( 500 );
+				digitalWrite(pinStepY, 0);
+				delayMicroseconds( 500 );
+			}
+		}
+
+		//======================================================================
+		// 8888888888P
+		//       d88P
+		//      d88P
+		//     d88P
+		//    d88P
+		//   d88P
+		//  d88P
+		// d8888888888
+		//======================================================================
+
+		digitalWrite(pinDirZ, directZ);
+		if(speedZ != 0)
+		{
+			unsigned long currentZ = millis();
+
+			if (currentZ - previousMillisZ >= speedZ)
+			{
+				previousMillisZ = currentZ;
+
+				digitalWrite(pinStepY, 1);
+				delayMicroseconds( 500 );
+				digitalWrite(pinStepY, 0);
+				delayMicroseconds( 500 );
+				if(directZ) Zangle++;
+				else Zangle--;
+			}
+		}
+
+		if(Zangle == 201) Zangle = 0;
+		if(Zangle == -1)  Zangle = 0;
+
+	}
+
+	// TRIGGER / SEC
+	//-------------------------------------------------------------------------//
+	unsigned long currentS = millis(); // millis();
+
+	if (currentS - trigS  >= trigSec)
+	{
+		trigS = currentS;
+
+		// PING
+		if(LED_PING) LED_PING = false;
+		else LED_PING = true;
+		digitalWrite(PING, LED_PING);
+
+		// IF THE MPU6050 ARE ALWAYS CONNECTED, IF NOT, HE RECONNECT AUTOMATICLY
+		if(!accelgyro.testConnection());
+		{
+			production = false;
+			emgStop = true;
+			accelgyro.initialize();
+			if(accelgyro.testConnection())
+			{
+				production = true;
+			}
+		}
+

-    	if (strcmp(strtok(msg, " "), "SET") == 0)
-    	{
-            Serial.println("UPDATE SETPOINT");
-      	    // trouvé le message
-      	    char *p;
-      	    while ((p = strtok(NULL, " ")) != NULL)
-      	    {
-       		int val = atoi(p + 1);
-       		switch (*p)
-       		{
-		        case 'x': setpointX  = val; break;
-          	    case 'y': setpointY  = val; break;
-      	  	    case 'm': multiplier = val; break;
-      		    case 'i': invertXY   = val; break;
-      		    case 'j': invertX    = val; break;
-      		    case 'k': invertX    = val; break;
-      		    case 'h': hysteresis = val; break;
-        	}
-      	    }
-    	}
-
-    	if (strcmp(strtok(msg, " "), "RUN") == 0)
-    	{
-            Serial.println("ROll BB-8 ROLL !");
-      	    production = true;
-    	}
-
-    	if (strcmp(strtok(msg, " "), "STOP") == 0)
-    	{
-    	    Serial.println("STOP");
-    	    production = false;
-    	}
-
-    	if (strcmp(strtok(msg, " "), "RESET") == 0)
-    	{
-    	    Serial.println("RESET");
-    	    production = false;
-    	    emgStop    = false;
-    	}
-
-    	if (strcmp(strtok(msg, " "), "BOOT") == 0)
-    	{
-    	    BOOT = true;
-    	    Serial.println("BOOTING UP...");
-    	    delay(2000);
-    	}
-
-    	if (strcmp(strtok(msg, " "), "ROTATE") == 0) // ROTATE d1 s100  <-- Rotate Z right, 18c/sec
-    	{
-      	    // trouvé le message
-      	    char *p;
-      	    while ((p = strtok(NULL, " ")) != NULL)
-      	    {
-                 int val = atoi(p + 1);
-        	 switch (*p)
-        	 {
-          	     case 'd': directZ  = val; break;
-          	     case 's': speedZ   = val; break;
-                 }
-            }
-    	}
-
-    	if (strcmp(strtok(msg, " "), "MOVE") == 0)
-    	{
-            Serial.println("UPDATE SETPOINT");
-      	    // trouvé le message
-      	    char *p;
-      	    while ((p = strtok(NULL, " ")) != NULL)
-      	    {
-                int val = atoi(p + 1);
-        	switch (*p)
-        	{
-          	     case 'a': speedA  = val; break;
-          	     case 'b': speedB  = val; break;
-      	  	     case 'c': dirA    = val; break;
-      		     case 'd': dirB    = val; break;
-        	}
-      	    }
-        }
-
-    	if (strcmp(strtok(msg, " "), "ENABLE") == 0)
-    	{
-       	    //Serial.println("UPDATE SETPOINT");
-  	    // trouvé le message
-  	    char *p;
-      	    while ((p = strtok(NULL, " ")) != NULL)
-   	    {
-      	        int val = atoi(p + 1);
-        	switch (*p)
-        	{
-        	    case 'a': enMotAB  = val; break;
-        	    case 'x': enMotXY  = val; break;
-      		    case 'z': enMotZ   = val; break;
-        	}
-      	    }
-    	}
-
-    }
-
-   digitalWrite(pinEnableAB, enMotAB);
-   digitalWrite(pinEnableXY, enMotXY);
-   digitalWrite(pinEnableZ, enMotZ);
-
-   if(BOOT)
-   {
- 	enMotAB = true;
- 	enMotXY = true;
- 	enMotZ  = true;
-
-   	// SET X IN POSITION
-   	if(x < 90) directX = false;
-  	else directX = true;
-
-  	if(invertX)
-  	{
-    		if(directX) directX = false;
-    		else directX = true;
-  	}
-  	digitalWrite(pinDirX, directX); // dirX
-
-  	if(x > (setpointX + hysteresis) || (x < setpointX - hysteresis || !xok ))
-  	{
-  	    digitalWrite(pinStepX, 1);
-            delayMicroseconds( 500 );
-    	    digitalWrite(pinStepX, 0);
-    	    delayMicroseconds( 500 );
-  	}
-  	else
-  	{
-  	    if(!xok)
-            {
-  	        Serial.println("BOOT x1 ");
-  		xok = true;
-  		delay(2000);
- 	    }
-  	}
-
-        // SET Y IN POSITION
-   	if(y < 90) directY = false;
-  	else directY = true;
-
-	if(invertY)
-  	{
-    	    if(directY) directY = false;
-    	    else directY = true;
-  	}
-  	digitalWrite(pinDirY, directY); // dirX
-
-  	if(y > (setpointY + hysteresis) || (y < setpointY - hysteresis || !yok))
-  	{
-  	    digitalWrite(pinStepY, 1);
-            delayMicroseconds( 500 );
-    	    digitalWrite(pinStepY, 0);
-    	    delayMicroseconds( 500 );
-        }
-  	else
-  	{
-  	    if(!yok)
-  	    {
-  		Serial.println("BOOT y1 ");
-  		yok = true;
-  		delay(2000);
-  	    }
-  	}
-
-  	// SET Z IN POSITION
-  	if(!digitalRead(Z_POSITION))
-  	{
-  	    digitalWrite(pinStepZ, 1);
-            delayMicroseconds( 500 );
-    	    digitalWrite(pinStepZ, 0);
-    	    delayMicroseconds( 500 );
-  	}
-  	else
-  	{
-       	    if(!zok)
-  	    {
-  	        Serial.println("BOOT z1 ");
-  		zok = true;
-  		Zangle = 0;
-  		delay(2000);
-  	    }
-  	}
-
-  	if( xok && yok && zok)
-  	{
-	    Serial.println("STAT b1 ");
-  	    Serial.println("Booting UP OK!");
-  	    Serial.println("SEND 'RUN \n' for start the production");
-  	    BOOT = false;
-  	}
-     }
-
-    // PRODUCTION CODE
-    //-------------------------------------------------------------------------//
-    if(production && !emgStop)  //-
-    {
-    	enMotAB = true;
- 	enMotXY = true;
- 	enMotZ  = true;
-
-    	//======================================================================
-    	//        d8888
-    	//       d88888
-     	//	d88P888
-    	//     d88P 888
-   	//    d88P  888
-  	//   d88P   888
- 	//  d8888888888
-	// d88P     888
-	//======================================================================
-    	// MOTOR A (Left)
-
-	// Run the motor
-	if(speedA > 0) runA = true;
-	else runA = false;
-	speedA = 1000 / speedA;
+
+		// SEND STATUT
+		// ON SERIAL USB
+		Serial.print("STAT x");
+		Serial.print(x);
+		Serial.print(" y");
+		Serial.print(y);
+		Serial.print(" i");
+		Serial.print(INVERT_XY);
+		Serial.print(" j");
+		Serial.print(INVERT_X);
+		Serial.print(" k");
+		Serial.print(INVERT_XY);
+		Serial.print(" m");
+		Serial.print(multiplier);
+		Serial.print(" z");
+		Serial.print(Zangle);
+
+		Serial.println(" ");
+
+		// SEND STATUT
+		// ON CONTROLER RF433
+				// ON SERIAL USB
+		controler.print("STAT x");
+		controler.print(x);
+		controler.print(" y");
+		controler.print(y);
+		controler.print(" i");
+		controler.print(INVERT_XY);
+		controler.print(" j");
+		controler.print(INVERT_X);
+		controler.print(" k");
+		controler.print(INVERT_Y);
+		controler.print(" m");
+		controler.print(multiplier);
+		controler.print(" z");
+		controler.print(Zangle);

-	// Motor direction / With inversion
-	if(invertA)
-  	{
-    	    if(dirA) dirA = false;
-	    else dirA = true;
-	}
-	digitalWrite(pinDirA, dirA); // Set the direction

-	// Send Step inpultion to the motor
-	unsigned long currentA = millis(); // millis();
-	if (currentA - previousMillisA >= speedA)
-	{
-	    previousMillisA = currentA;
-
-	    if(runA)
-	    {
-	        digitalWrite(pinStepA, 1);
-	        delayMicroseconds( 500 );
-	        digitalWrite(pinStepA, 0);
-	        delayMicroseconds( 500 );
-	    }
-	}
-
-    	//======================================================================
-	// 888888b.
-	// 888  "88b
-	// 888  .88P
-	// 8888888K.
-	// 888  "Y88b
-	// 888    888
-	// 888   d88P
-	// 8888888P"
-	//======================================================================
-	// MOTOR B (Right)
-
-	// Run the motor
-	if(speedB > 0) runB = true;
-	else runB = false;
-	speedB = 1000 / speedB;
-
-	// Motor direction / With inversion
-	if(invertB)
- 	{
-	    if(dirB) dirB = false;
-	    else dirB = true;
-	}
-	digitalWrite(pinDirB, dirB); // Set the direction
-
-	// Send Step inpultion to the motor
-	unsigned long currentB = millis(); // millis();
-	if (currentB - previousMillisB >= speedB)
-	{
-	    previousMillisB = currentB;
-
-	    if(runB)
-	    {
-	        digitalWrite(pinStepB, 1);
-	        delayMicroseconds( 500 );
-	        digitalWrite(pinStepB, 0);
-	        delayMicroseconds( 500 );
-	     }
-	}
-
-    	//======================================================================
-        // Y88b   d88P
-	//  Y88b d88P
-	//   Y88o88P
-	//    Y888P
-	//    d888b
-	//   d88888b
-	//  d88P Y88b
-	// d88P   Y88b
-	//======================================================================
-
-	// Direction
-  	if(x < 90) directX = false;
-  	else directX = true;
-
-  	if(invertX)
-  	{
-    	    if(directX) directX = false;
-    	    else directX = true;
-  	}
-  	digitalWrite(pinDirX, directX); // dirX
-
-  	// Si ont doit demarer le moteur
-  	if(x > (setpointX + hysteresis) || (x < setpointX - hysteresis ))
-  	{
-    	    if(x > minX && x < maxX) runX = true;
-    	    else runX = false;
-  	}
-  	else runX = false;
-
-  	// Calcul du PID X
-  	if(x < setpointX) vx = (setpointX - x);
-  	if(x == 0) vx = 0;
-  	if(x > setpointX) vx = (x - setpointX);
-
-  	speedX = 1000 / (vx);
-  	speedX = speedX * multiplier; // DEL
-  	if(speedX < 15) speedX = 15;
-
-	// Mise en route du moteur
-  	unsigned long currentX = millis();
-
-    	if (currentX - previousMillisX >= speedX)
-    	{
-      	    previousMillisX = currentX;
-
-	    if(runX)
-      	    {
-                digitalWrite(pinStepX, 1);
-        	delayMicroseconds( 500 );
-        	digitalWrite(pinStepX, 0);
-    	 	delayMicroseconds( 500 );
-            }
-  	}
-
-    	//======================================================================
-	// Y88b   d88P
-	//  Y88b d88P
-  	//   Y88o88P
-   	//    Y888P
-    	//     888
-    	//     888
-        //     888
-        //     888
-	//======================================================================
-
-	// Direction
-  	if(y < 90) directY = false;
-  	else directY = true;
-  	if(invertY)
-  	{
-    	    if(directY) directY = false;
-    	    else directY = true;
-  	}
-  	digitalWrite(pinDirY, directY);
-
-	// Si ont doit demarer le moteur
-  	if(y > (setpointY + hysteresis) || (y < setpointY - hysteresis ))
-  	{
-    	    if(y > minY && y < maxY) runY = true;
-    	    else runY = false;
-  	}
-  	else runY = false;
-
-  	// Calcul du PID Y
-  	if(y < setpointY) vy = (setpointY - y);
-  	if(y == 0) vy = 0;
-  	if(y > setpointY) vy = (y - setpointY);
-
-  	speedY = 1000 / (vy);
-  	speedY = speedY * multiplier; // DEL
-  	if(speedY < 15) speedY = 15;
-
-	// Mise en route du moteur
-  	unsigned long currentY = millis(); // millis();
-
-    	if (currentY - previousMillisY >= speedY)
-    	{
-      	    previousMillisY = currentY;
-
-            if(runY)
-      	    {
-        	digitalWrite(pinStepY, 1);
-        	delayMicroseconds( 500 );
-        	digitalWrite(pinStepY, 0);
-        	delayMicroseconds( 500 );
-            }
-  	}
-
-    	//======================================================================
-	// 8888888888P
-        //       d88P
-        //      d88P
-    	//     d88P
-        //    d88P
-        //   d88P
-        //  d88P
-        // d8888888888
-	//======================================================================
-
-	digitalWrite(pinDirZ, directZ);
-	if(speedZ != 0)
-  	{
-  	    unsigned long currentZ = millis();
-
-	    if (currentZ - previousMillisZ >= speedZ)
-    	    {
-      		previousMillisZ = currentZ;
-
-		digitalWrite(pinStepY, 1);
-    	    	delayMicroseconds( 500 );
-    	    	digitalWrite(pinStepY, 0);
-    	    	delayMicroseconds( 500 );
-    	    	if(directZ) Zangle++;
-    	    	else Zangle--;
-  	    }
-  	}
-
-	if(Zangle == 201) Zangle = 0;
-  	if(Zangle == -1)  Zangle = 0;
-
-    }
-
-    // TRIGGER / SEC
-    //-------------------------------------------------------------------------//
-    unsigned long currentS = millis(); // millis();
-
-    if (currentS - trigS  >= trigSec)
-    {
-    	trigS = currentS;
-
-    	// PING
-    	if(LED_PING) LED_PING = false;
-    	else LED_PING = true;
-    	digitalWrite(PING, LED_PING);
-
-	// IF THE MPU6050 ARE ALWAYS CONNECTED, IF NOT, HE RECONNECT AUTOMATICLY
-    	if(!accelgyro.testConnection());
-    	{
-    	    production = false;
-    	    emgStop = true;
-    	    accelgyro.initialize();
-    	    if(accelgyro.testConnection())
-    	    {
-    		production = true;
-    	    }
-    	}
-
-    	/*
-
-    	// SEND STATUT
-    	Serial.print("STAT x");
-    	Serial.print(x);
-    	Serial.print(" y");
-    	Serial.print(y);
-    	Serial.print(" i");
-    	Serial.print(invertXY);
-    	Serial.print(" j");
-    	Serial.print(invertX);
-    	Serial.print(" k");
-    	Serial.print(invertY);
-    	Serial.print(" m");
-    	Serial.print(multiplier);
-    	Serial.print(" z");
-    	Serial.print(Zangle);
-
-    	Serial.println(" ");
-
-    	*/
-    } // ENF OF PRODUCTION
+	} // ENF OF PRODUCTION
 } // END OF LOOP

 // VOID FOR TAKE THE CURRENT
 int current(int Cpin)
 {
-    int mVperAmp = 185; // use 100 for 20A Module and 66 for 30A Module
-    int RawValue= 0;
-    int ACSoffset = 2500;
-    double Voltage = 0;
-    double Amps = 0;
-
-    RawValue = analogRead(Cpin);
-    Voltage = (RawValue / 1024.0) * 5000; // Gets you mV
-    Amps = ((Voltage - ACSoffset) / mVperAmp);
-
-    return(Amps);
+	int mVperAmp = 185; // use 100 for 20A Module and 66 for 30A Module
+	int RawValue = 0;
+	int ACSoffset = 2500;
+	double Voltage = 0;
+	double Amps = 0;
+
+	RawValue = analogRead(Cpin);
+	Voltage = (RawValue / 1024.0) * 5000; // Gets you mV
+	Amps = ((Voltage - ACSoffset) / mVperAmp);
+
+	return(Amps);
 }

 // VOID FOR TAKE THE BATTERY VOLTAGE
 int voltage(int Vpin)
 {
-    float vout = 0.0;
-    float vin = 0.0;
-    float R1 = 100000.0; // resistance of R1 (100K) -see text!
-    float R2 = 10000.0; // resistance of R2 (10K) - see text!
-    int value = 0;
-
-    value = analogRead(Vpin);
-    vout = (value * 5.0) / 1024.0;
-    vin = vout / (R2/(R1+R2));
-    if (vin<0.09) vin=0.0;
-
-    return(vin);
+	float vout = 0.0;
+	float vin = 0.0;
+	float R1 = 100000.0; // resistance of R1 (100K) -see text!
+	float R2 = 10000.0; // resistance of R2 (10K) - see text!
+	int value = 0;
+
+	value = analogRead(Vpin);
+	vout = (value * 5.0) / 1024.0;
+	vin = vout / (R2 / (R1 + R2));
+	if (vin < 0.09) vin = 0.0;
+
+	return(vin);
 }


Fix Minor bug with MQTT_ENABLE False condition (#654)

* Fix Minor bug with MQTT_ENABLE False condition

If  MQTT_ENABLE is set false, the sketch does not compile.
Fixed minor bugs regarding the same

* Fix linter issues.

examples/IRMQTTServer/IRMQTTServer.ino:1328:  Weird number of spaces at line-start.  Are you using a 2-space indent?  [whitespace/indent] [3]
examples/IRMQTTServer/IRMQTTServer.ino:1330:  Weird number of spaces at line-start.  Are you using a 2-space indent?  [whitespace/indent] [3]

--- examples/IRMQTTServer/IRMQTTServer.ino
+++ examples/IRMQTTServer/IRMQTTServer.ino
@@ -287,6 +287,12 @@
 uint32_t lastSendTime = 0;
 int8_t offset;  // The calculated period offset for this chip and library.

+#ifdef IR_RX
+String lastIrReceived = "None";
+uint32_t lastIrReceivedTime = 0;
+uint32_t irRecvCounter = 0;
+#endif  // IR_RX
+
 #if MQTT_ENABLE
 String lastMqttCmd = "None";
 uint32_t lastMqttCmdTime = 0;
@@ -294,12 +300,6 @@
 uint32_t lastDisconnectedTime = 0;
 uint32_t mqttDisconnectCounter = 0;
 bool wasConnected = true;
-#ifdef IR_RX
-String lastIrReceived = "None";
-uint32_t lastIrReceivedTime = 0;
-uint32_t irRecvCounter = 0;
-#endif  // IR_RX
-

 // MQTT client parameters
 void callback(char* topic, byte* payload, unsigned int length);
@@ -1325,7 +1325,9 @@
     // If it isn't an AC code, add the bits.
     if (!hasACState(capture.decode_type))
       lastIrReceived += "," + String(capture.bits);
+#if MQTT_ENABLE
     mqtt_client.publish(MQTTrecv, lastIrReceived.c_str());
+#endif
     irRecvCounter++;
     debug("Incoming IR message sent to MQTT: " + lastIrReceived);
   }


Fix RGBCalibrate example

Fix RGBCalibrate example

--- examples/RGBCalibrate/RGBCalibrate.ino
+++ examples/RGBCalibrate/RGBCalibrate.ino
@@ -65,9 +65,6 @@
    leds[3] = CRGB(0,0,255);
    leds[4] = CRGB(0,0,255);
    leds[5] = CRGB(0,0,255);
-   leds[random8()%NUM_LEDS] = CRGB(0,0,0);
-   // leds[10] = CRGB(0,0,0);
    FastLED.show();
-   // delay(1000);
-   FastLED.showColor(CRGB::Black);
+   delay(1000);
 }


Fields change

Fields change

Update results URL that gets generated to use new field IDs

--- examples/XLR8SelfTest/XLR8SelfTest.ino
+++ examples/XLR8SelfTest/XLR8SelfTest.ino
@@ -73,7 +73,7 @@
 uint16_t highXrefl = 0;
 uint16_t lowXrefl = 1023;

-#define INCLUDE_DEBUG
+//#define INCLUDE_DEBUG
 #ifdef INCLUDE_DEBUG
 const uint8_t numTestDebug = 40;
 uint8_t testDebug[numTestDebug];
@@ -365,29 +365,30 @@
   Serial.print(F("&entry.1215707535="));Serial.print("XLR8SelfTest"); // Notes
   Serial.print(F("&entry.545646289="));Serial.print(intOscSpeed); // Speed Test
   Serial.print(F("&entry.1561823473="));Serial.print(vccRead); // 5V supply measurement
-  Serial.print(F("&entry.882185102=Yes")); // Add test results
-  Serial.print(F("&entry.566710584=")); // Pass/Fail/Status
+  Serial.print(F("&entry.882185102=Record Test Results")); // Add test results
+  Serial.print(F("&entry.1879785912=")); // Pass/Fail/Status
   if (failnum) {Serial.print("FAIL");}
   else if (passnum == testnum) {Serial.print("PASS");}
   else {Serial.print("INCOMPLETE");}
-  Serial.print(F("&entry.893422998=("));Serial.print(fastPinD); // Port D measurements
+  Serial.print(F("&entry.1656234522=("));Serial.print(fastPinD); // Port D measurements
   Serial.print(",");Serial.print(fastValD);
   Serial.print(",");Serial.print(slowPinD);
   Serial.print(",");Serial.print(slowValD);Serial.print(")");
-  Serial.print(F("&entry.1229366360=("));Serial.print(fastPinB); // Port B measurements
+  Serial.print(F("&entry.1272501077=("));Serial.print(fastPinB); // Port B measurements
   Serial.print(",");Serial.print(fastValB);
   Serial.print(",");Serial.print(slowPinB);
   Serial.print(",");Serial.print(slowValB);Serial.print(")");
-  Serial.print(F("&entry.2038080670=("));Serial.print(highPinC); // Port C measurements
+  Serial.print(F("&entry.525544221=("));Serial.print(highPinC); // Port C measurements
   Serial.print(",");Serial.print(highValC);
   Serial.print(",");Serial.print(lowPinC);
   Serial.print(",");Serial.print(lowValC);Serial.print(")");
-  Serial.print(F("&entry.1025676851=("));Serial.print(highXrefh); // Ext Ref measurements
+  Serial.print(F("&entry.51020830=("));Serial.print(highXrefh); // Ext Ref measurements
   Serial.print(",");Serial.print(lowXrefh);
   Serial.print(",");Serial.print(highXrefl);
   Serial.print(",");Serial.print(lowXrefl);Serial.print(")");
   Serial.println();
   Serial.flush();
+

  #ifdef INCLUDE_DEBUG
   for (uint8_t i = 0; i<numTestDebug && i<numFailFlags; i++) {


'ID;' command returns program name and version

--- DigitalVFO.ino
+++ DigitalVFO.ino
@@ -623,7 +623,9 @@
     return "ERROR";

   // generate ID string and return
-  strcpy(answer, Version);
+  strcpy(answer, ProgramName);
+  strcat(answer, " ");
+  strcat(answer, Version);
   strcat(answer, MinorVersion);
   return answer;
 }


Comment

Comment

--- test/test.ino
+++ test/test.ino
@@ -17,7 +17,10 @@
                            Damon Hart-Davis 2015--2016
 */

-/*Unit test routines for library code.
+/**
+ *  Test stack usage of OTAESGCM functions
+ *  - No function should use more than 50 bytes of stack.
+ *
  */

 // Include the library under test.


end of setup print statement

end of setup print statement

--- SmartAlarm.ino
+++ SmartAlarm.ino
@@ -444,6 +444,8 @@

   // begin the rest server
   restServer.begin();
+
+  Serial.println(F("Setup complete!"));
 }

 void loop() {


Make intention more clear.

Make intention more clear.

--- tfttask.ino
+++ tfttask.ino
@@ -377,7 +377,7 @@
     }

     // if the temperature changed update the display
-    if ( tftClearScreen || displayedTemp[num] != logger.sensorTemp( num ) )
+    if ( tftClearScreen || ( displayedTemp[num] != logger.sensorTemp( num ) ) )
     {
       snprintf( tempArea[num].text, sizeof( tempArea[num].text ), " %.1f%c ", logger.sensorTemp( num ), char(247) );
       button.updateText( tempArea[num] );


Change print to println for better example

--- firmware/examples/SparkTimeExample.ino
+++ firmware/examples/SparkTimeExample.ino
@@ -28,13 +28,13 @@
 	timeStr += rtc.dayString(currentTime);
 	timeStr += ", ";
 	timeStr += rtc.yearString(currentTime);
-	Serial.print(timeStr);
+	Serial.println(timeStr);
       } else if (sec == 40) {
 	// Including current timezone
 	Serial.print(rtc.ISODateString(currentTime));
       } else if (sec == 50) {
 	// UTC or Zulu time
-	Serial.print(rtc.ISODateUTCString(currentTime));
+	Serial.println(rtc.ISODateUTCString(currentTime));
       } else {
 	// Just the time in 12 hour format
 	timeStr = "";
@@ -45,7 +45,7 @@
 	timeStr += rtc.secondString(currentTime);
 	timeStr += " ";
 	timeStr += rtc.AMPMString(currentTime);
-	Serial.print(timeStr);
+	Serial.println(timeStr);
       }
       lastTime = currentTime;
     }


Arduino slave code that works with raspberry pi.

--- SensorSeed/Arduino/ArduinoWindRainI2cSlave/ArduinoWindRainI2cSlave.ino
+++ SensorSeed/Arduino/ArduinoWindRainI2cSlave/ArduinoWindRainI2cSlave.ino
@@ -1,5 +1,5 @@
 #include <Wire.h>
-#include <avr/dtostrf.h>
+#include <stdlib.h>

 volatile byte* Float1ArrayPtr;

@@ -151,7 +151,7 @@
 }

 void setup() {
- Wire.begin(2);
+ Wire.begin(6);
  Wire.onRequest(requestEvent);
  Wire.onReceive(receiveEvent);
  //Serial.begin(9600);
@@ -201,11 +201,11 @@
   } else if(c == 3) { // rain
      // dataToSend = 5.6;
     dataToSend = getUnitRain();
-  } else if(c == 3) { // wind direction
+  } else if(c == 4) { // wind direction
     dataToSend = getDirection();
-  } else if(c == 4) { // solar
+  } else if(c == 5) { // solar
     dataToSend = getSolar();
-  } else if(c == 5) { // battery
+  } else if(c == 6) { // battery
     dataToSend = getBattery();
   }
   previousMillis = millis();


Update simpleWebServer.ino

Update simpleWebServer.ino

Added `INPUT_PULLUP` to PUSH1 and PUSH2
Added `WLAN_SSID` and `WLAN_PASS` for the WiFi LAN

--- libraries/SimplelinkWifi/examples/simpleWebServer/simpleWebServer.ino
+++ libraries/SimplelinkWifi/examples/simpleWebServer/simpleWebServer.ino
@@ -1,3 +1,8 @@
+// Enter here the name (=SSID) and password of your WiFi LAN
+
+#define WLAN_SSID       "energia"        // cannot be longer than 32 characters!
+#define WLAN_PASS       "supersecret"
+
  /*
   Web  Server

@@ -18,8 +23,8 @@
 #include "SPI.h"
 #include "WiFi.h"

-char ssid[] = "energia";     //  your network SSID (name)
-char pass[] = "supersecret";     //  your network SSID (name)
+char ssid[] = WLAN_SSID;     //  your network SSID (name)
+char pass[] = WLAN_PASS;     //  your network SSID (name)

 WiFiServer server(80);
 WiFiClient client;
@@ -35,8 +40,8 @@

   pinMode(RED_LED, OUTPUT);
   pinMode(GREEN_LED, OUTPUT);
-  pinMode(PUSH1, INPUT);
-  pinMode(PUSH2, INPUT);
+  pinMode(PUSH1, INPUT_PULLUP); // released = HIGH, pressed = LOW
+  pinMode(PUSH2, INPUT_PULLUP);

   delay(10);


Added led strip logic

Added led strip logic

--- frontdesk/frontdesk.ino
+++ frontdesk/frontdesk.ino
@@ -1,15 +1,19 @@
 #include <SoftwareSerial.h>
+#include <LPD8806.h>
 #include "RFID.h"

 #define FRONTDESK

 SoftwareSerial RFID(RFID_RX, RFID_TX);
 SoftwareSerial WIFI(WIFI_RX, WIFI_TX);
+// nLEDs, dataPin, clockPin
+LPD8806 LED = LPD8806(4, 10, 11);

-int scannedID, prevID = 0;
+int j, scannedID, prevID = 0;
 int coinNotes[] = { 988, 1319 };
 int coinNoteDurations[] = { 125, 400 };
 int numCoinNotes = sizeof(coinNotes) / sizeof(coinNotes[0]);
+unsigned long lastLEDchange = 0;
 unsigned char readData[bufferSize];
 volatile bool isValidResponse = false;
 volatile char characterRead[bufferSize];
@@ -18,12 +22,13 @@
 void setup() {
 	Serial.begin(moduleBaud);
 	WIFI.begin(moduleBaud);
-
+  	LED.begin();
 	pinMode(ledPin, OUTPUT);
 	pinMode(wifi_rst, OUTPUT);
 	pinMode(speakerPin, OUTPUT);
 	connectWIFI();

+  	LED.show();
 	RFID.begin(moduleBaud);
 }

@@ -46,8 +51,12 @@
 			Serial.write(ERROR_CHAR);
 			Serial.write(END_CHAR);
 		}
+
+		redBeat(10);
+		//colorWipe(LED.Color(127, 0, 0), 0);
 	}

+	colorWipe(LED.Color(0, 0, 127), 0);
 	// card detected, get user data
 	digitalWrite(ledPin, HIGH);
 	sendCommand(CMD_READ, blockID, userData);
@@ -141,3 +150,34 @@
 	strcpy_P(stringBuffer, (char*)pgm_read_word( &(message[index]) ));
 	Serial.print(stringBuffer);
 }
+
+void redBeat(uint8_t wait) {
+	int i = 0;
+
+	if (timeSince(lastLEDchange) > wait) {
+		j++;
+		for (i = 0; i < LED.numPixels(); i++) {
+			if (j < 16) {
+				LED.setPixelColor(i, LED.Color(j, 0, 0));
+			}
+			else {
+				LED.setPixelColor(i, LED.Color(32 - j, 0, 0));
+			}
+		}
+		if (j == 32) {
+			j = 0;
+		}
+		LED.show();
+		lastLEDchange = millis();
+	}
+}
+
+void colorWipe(uint32_t c, uint8_t wait) {
+	int i;
+
+	for (i=0; i < LED.numPixels(); i++) {
+		LED.setPixelColor(i, c);
+		LED.show();
+		delay(wait);
+	}
+}


add learn guide URL

add learn guide URL

--- examples/ttn-otaa-feather-us915-dht22/ttn-otaa-feather-us915-dht22.ino
+++ examples/ttn-otaa-feather-us915-dht22/ttn-otaa-feather-us915-dht22.ino
@@ -4,7 +4,7 @@
  * Example of sending a valid LoRaWAN packet with DHT22 temperature and
  * humidity data to The Things Networ using a Feather M0 LoRa.
  *
- * Learn Guide:
+ * Learn Guide: https://learn.adafruit.com/the-things-network-for-feather
  *
  * Copyright (c) 2015 Thomas Telkamp and Matthijs Kooijman
  * Copyright (c) 2018 Terry Moore, MCCI


Add the switches to the payload

Add the switches to the payload

--- transmitter/TX/TX.ino
+++ transmitter/TX/TX.ino
@@ -157,6 +157,7 @@
   tx_payload.yaw      = joystickMapValues(analogRead(PIN_YAW), 10, 521, 1000);
   tx_payload.pitch    = joystickMapValues(analogRead(PIN_PITCH), 0, 511, 1023);
   tx_payload.roll     = joystickMapValues(analogRead(PIN_ROLL), 0, 511, 1023);
+  tx_payload.switches = switches;

   if (DEBUG) {
     printf("val: %d\n\r ",tx_payload.throttle);


Second Strip

Second Strip

--- sketch/sketch.ino
+++ sketch/sketch.ino
@@ -59,11 +59,14 @@
     -----------------------------------------------------------------------*/
     #define FACTORYRESET_ENABLE     1

-    #define PIN                     5
+    #define PIN_1                    5
+    #define PIN_2                    6
     #define NUMPIXELS               150
+
 /*=========================================================================*/

-Adafruit_NeoPixel pixel = Adafruit_NeoPixel(NUMPIXELS, PIN);
+Adafruit_NeoPixel pixel1 = Adafruit_NeoPixel(NUMPIXELS, PIN_1);
+Adafruit_NeoPixel pixel2 = Adafruit_NeoPixel(NUMPIXELS, PIN_2);

 // Create the bluefruit object, either software serial...uncomment these lines
 /*
@@ -103,9 +106,11 @@
 void setAllPixel(int r, int g, int b){
   Serial.println( F("setAllPixel") );
   for(uint8_t i=0; i<NUMPIXELS; i++) {
-    pixel.setPixelColor(i, pixel.Color(r,g,b));
-  }
-  pixel.show();
+    pixel1.setPixelColor(i, pixel1.Color(r,g,b));
+    pixel2.setPixelColor(i, pixel2.Color(r,g,b));
+  }
+  pixel1.show();
+  pixel2.show();
 }

 /**************************************************************************/
@@ -120,7 +125,8 @@
   //delay(500);

   // turn off neopixel
-  pixel.begin(); // This initializes the NeoPixel library.
+  pixel1.begin(); // This initializes the NeoPixel library.
+   pixel2.begin(); // This initializes the NeoPixel library.

   Serial.begin(115200);
   Serial.println(F("Adafruit Bluefruit Neopixel Color Picker Example"));
@@ -202,9 +208,11 @@
     Serial.println(blue, HEX);

     for(uint8_t i=0; i<NUMPIXELS; i++) {
-      pixel.setPixelColor(i, pixel.Color(red,green,blue));
+      pixel1.setPixelColor(i, pixel1.Color(red,green,blue));
+      pixel2.setPixelColor(i, pixel2.Color(red,green,blue));
     }
-    pixel.show(); // This sends the updated pixel color to the hardware.
-  }
-
-}
+    pixel1.show(); // This sends the updated pixel color to the hardware.
+    pixel2.show(); // This sends the updated pixel color to the hardware.
+  }
+
+}


clean up

clean up

--- module/module.rfid.ino
+++ module/module.rfid.ino
@@ -57,11 +57,10 @@
 		// timeByte is in format { 0xAA, 0xBB, 0xCC }
 		// in the first iteration, time gets shifted 2 bytes to get 0x000000AA
 		// then bitwise AND operation with 0xFF, then store in timeByte
-		int i = 0;
 		int j = 2 * eightBits; // only need to shift 2 times, 1 byte == 8 bits
 		unsigned char timeByte[numTimeBytes];

-		for(i = 0; i < numTimeBytes; i++) {
+		for(int i = 0; i < numTimeBytes; i++) {
 			timeByte[i] = (time >> j) & MSB;
 			j -= eightBits;
 		}


reset to restart

reset to restart

--- _47-esp-dht22-2AA-deepsleep-test/_47-esp-dht22-2AA-deepsleep-test.ino
+++ _47-esp-dht22-2AA-deepsleep-test/_47-esp-dht22-2AA-deepsleep-test.ino
@@ -143,7 +143,7 @@
     if (Attempt == 300)
     {
       // if fail
-      ESP.reset();;
+      ESP.restart();;
     }
   }
 }
@@ -170,7 +170,7 @@
     Serial.println(h);
   } else {
     pinMode(DHTPIN, INPUT);
-    ESP.reset();
+    ESP.restart();
   }

   delay(2100);
@@ -184,7 +184,7 @@
     Serial.println(h);
   } else {
     pinMode(DHTPIN, INPUT);
-    ESP.reset();
+    ESP.restart();
   }

   Serial.println("wifi on");


Move code to Pi

Move code to Pi

Code is not complete, I just need to program from the Pi

--- Arduino_Code/Arduino_Code.ino
+++ Arduino_Code/Arduino_Code.ino
@@ -1,3 +1,8 @@
+/*
+Created by Geoff Spielman on 2016-06-25.
+Copyright (c) 2016 Geoff Spielman. All rights reserved.
+*/
+
  // put your setup code here, to run once:
   const int btn0 = 2;
   const int btn1 = 7;
@@ -11,6 +16,9 @@
  int btn[] = {btn0, btn1, btn2, btn3};
  int led[] = {led0, led1, led2, led3};

+ String recString = "";
+ boolean newAvail = false;
+
 void setup() {
  Serial.begin(9600);
  pinMode(btn0, INPUT);
@@ -21,8 +29,8 @@
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
-
- Serial.println("Starting Program");
+ recString.reserve(200);
+ Serial.println("-----Start-----");

 }

@@ -31,18 +39,25 @@
   for (int i = 0; i < 4; i ++) {
     if (digitalRead(btn[i]) == 1) {
       digitalWrite(led[i], HIGH);
-      Serial.print("LED ");
-      Serial.print(i);
-      Serial.print(" on    ");
+      //Serial.print("LED ");
+      //Serial.print(i);
+      //Serial.print(" on    ");
     }
     else {
       digitalWrite(led[i], LOW);
-      Serial.print("LED ");
-      Serial.print(i);
-      Serial.print(" off    ");
+      //Serial.print("LED ");
+      //Serial.print(i);
+      //Serial.print(" off    ");
     }

   }
+  if (newAvail) {
+    //DO SOMETHING
+    recString = "";
+    newAvail = false;
+
+  }
+  /*
   Serial.println(" ");
   Serial.print("Button0: ");
   Serial.print(digitalRead(btn0));
@@ -53,5 +68,98 @@
   Serial.print("   Button3: ");
   Serial.print(digitalRead(btn3));
   Serial.println(" ");
+  */

 }
+
+void serialEvent()
+{
+  while (Serial.available())
+  {
+    char inChar = (char)Serial.read();
+    recString += inChar;
+    Serial.print("inChar: ");
+    Serial.println(inChar);
+
+    if (inChar == '|')
+    {
+      Serial.print("Char at 0: ");
+      Serial.println(recString.charAt(0));
+      int endIndex = recString.indexOf("|");
+      if (endIndex == -1)
+      {
+        endIndex = recString.indexOf("/n");
+      }
+      //PROCESS STRING
+      if (recString.charAt(0) == 'm') {
+        //Message Processing
+        Serial.println("I have recieved a message");
+      }
+      if (recString.charAt(0) == 's') {
+        //Sequence Processing
+        Serial.println("I have received a sequence");
+      }
+
+
+      newAvail = true;
+    }
+  }
+}
+
+/*
+const int led = 13;
+const int mtrL = 6;
+const int mtrR = 5;
+
+int mL = 0, mR = 0;
+
+String inputString = "";
+boolean needChange = false;
+
+void setup() {
+  Serial.begin(9600);
+  pinMode(led, OUTPUT);
+  inputString.reserve(200);
+  Serial.println("-----Start-----");
+}
+
+void loop() {
+
+  if (needChange)
+  {
+    //Serial.print("Arduino rec: ");
+    //Serial.println(inputString);
+    Serial.print("Left Motor: ");
+    Serial.print(mL);
+    Serial.print("   Right Motor: ");
+    Serial.println(mR);
+
+    analogWrite(mtrL, mL);
+    analogWrite(mtrR, mR);
+    inputString = "";
+    needChange = false;
+  }
+}
+
+void serialEvent()
+{
+  while (Serial.available())
+  {
+    char inChar = (char)Serial.read();
+    inputString += inChar;
+    if (inChar == '\n' || inChar == '!') //if 'end with newline' is not enabled on serial monitor, end with !
+    {
+      int commaIndex = inputString.indexOf(",");
+      int endIndex = inputString.indexOf("!");
+      if (endIndex == -1)
+      {
+        endIndex = inputString.indexOf("/n");
+      }
+      mL = inputString.substring(0, commaIndex).toInt();
+      mR = inputString.substring(commaIndex + 1, endIndex).toInt();
+      needChange = true;
+    }
+  }
+}
+*/
+


Cleanup modes

Cleanup modes

--- AudioLights2/AudioLights2.ino
+++ AudioLights2/AudioLights2.ino
@@ -1,19 +1,20 @@
 #include <EEPROM.h>

-#define PARTYMODE 0
-#define SLOW 1
-#define SINGLE 2
-#define SINGLE_WHITE 3
-#define BASSFADE 4
-#define AMBIENT_GREEN 5
-#define NIGHT_VISION 6
-#define WHITE 7
-#define OFF 8
-#define MODE_MAX 8
+#define MODE_OFF 0
+#define MODE_PARTY 1
+#define MODE_SLOW 2
+#define MODE_GREENPULSE 3
+#define MODE_MODE_WHITEPULSE 4
+#define MODE_BASSFADE 5
+#define MODE_GREEN 6
+#define MODE_RED 7
+#define MODE_WHITE 8
+
+#define NUM_MODES 9

 bool isChanging = false;
 volatile unsigned long timer_start;
-int mode = PARTYMODE;
+int mode = MODE_PARTY;
 int strobe = 4; // strobe pins on digital 4
 int res = 5; // reset pins on digital 5
 int ledPin = 9;
@@ -66,10 +67,7 @@
     if (digitalRead(2) == 1) return;
     Serial.print("");
   }
-  mode++;
-  if (mode > MODE_MAX) {
-    mode = 0;
-  }
+  mode = (mode + 1) % NUM_MODES;
   EEPROM.write(0, mode);
   rawWriteColor(0, 0, 0, 0);
   timer_start = micros();
@@ -192,7 +190,7 @@

   double intensity = map(avgleft, 0, 700, 0, 100);

-  if (mode == PARTYMODE || mode == SLOW) {
+  if (mode == MODE_PARTY || mode == MODE_SLOW) {
     while (abs(led1Value-out) > 1.0 || abs(led2Value-out2) > 1.0 || abs(led3Value-out3) > 1.0 || abs(led4Value-out4) > 1.0) {
       globalRed = 0;
       globalBlue = 0;
@@ -208,18 +206,18 @@
       analogWrite(ledPin3,led3Value);
       led4Value += sign(out4-led4Value);
       int delayMS = 200;
-      if(mode == SLOW) delayMS = 1000;
+      if(mode == MODE_SLOW) delayMS = 1000;
       delayMicroseconds(delayMS * pow(timeMultiplier,1));
     }
   //  writeColor(102,255,0,60);
-  } else if(mode == AMBIENT_GREEN){
+  } else if (mode == MODE_GREEN){
     rawWriteColor(102,255,0,60);
-  } else if(mode == NIGHT_VISION){
+  } else if (mode == MODE_RED){
     rawWriteColor(255,0,0,100);
-  } else if(mode == WHITE){
+  } else if (mode == MODE_WHITE){
     rawWriteColor(255,255,255,100);
-  } else if(mode == SINGLE){
-    while(abs(allLedValue-intensity)>1.0) {
+  } else if (mode == MODE_GREENPULSE){
+    while (abs(allLedValue-intensity) > 1.0) {
       allLedValue += 0.4*sign(intensity-allLedValue);
       // writeColor(0,0,255,led1Value);
       rawWriteColor(102,255,0,allLedValue);
@@ -227,10 +225,10 @@
       int delayMS = 3000 / pow((abs(lastUpdate-intensity) + 1), 1);
       //  Serial.println(delayMS);

-      delayMicroseconds(1000*pow(timeMultiplier,1));
+      delayMicroseconds(1000 * pow(timeMultiplier, 1));
     }
     lastUpdate = intensity;
-  } else if (mode == SINGLE_WHITE) {
+  } else if (mode == MODE_MODE_WHITEPULSE) {
     while (abs(allLedValue-intensity) > 1.0) {
       allLedValue += 0.4 * sign(intensity-allLedValue);
       // writeColor(0,0,255,led1Value);
@@ -242,7 +240,7 @@
       delayMicroseconds(1000*pow(timeMultiplier,1));
     }
     lastUpdate = intensity;
-  } else if (mode == BASSFADE) {
+  } else if (mode == MODE_BASSFADE) {
     if (out < 15) out = 0;
     while (abs(allLedValue-out) > 1.0) {
       allLedValue += 2*sign(out-allLedValue);
@@ -257,8 +255,8 @@
     }
     Serial.println(out);
     lastUpdate = out;
-  } else if(mode == OFF){
-    rawWriteColor(0,0,0,0);
+  } else if (mode == MODE_OFF){
+    rawWriteColor(0, 0, 0, 0);
   }
   // Serial.println("RNNING");
 }


adding back SETUP_DATA

adding back SETUP_DATA

--- BiblioPixelSerialReceiver.ino
+++ BiblioPixelSerialReceiver.ino
@@ -152,6 +152,12 @@
                 Serial.write(RETURN_CODES::SUCCESS);
             }
         }
+        else if (cmd == CMDTYPE::SETUP_DATA)
+        {
+            for(int i=0; i<size; i++) Serial.read();
+            // Just succeed. Config is hardcoded at compile time
+            Serial.write(RETURN_CODES::SUCCESS);
+        }
         else if (cmd == CMDTYPE::BRIGHTNESS)
         {
             uint8_t result = RETURN_CODES::SUCCESS;


No new functionalities but restructure the code, clear dead code, add comments, and correct the bug which appeared on newer arduino version

--- Arduino/Complete/src/src.ino
+++ Arduino/Complete/src/src.ino
@@ -1,218 +1,176 @@
-
 // Copyright (c) 2013 Nautilabs
 // https://github.com/baptistelabat/robokite

-// This file used SoftwareSerial example (Copyright (c) 2012 Dimension Engineering LLC) for Sabertooth http://www.dimensionengineering.com/software/SabertoothSimplifiedArduinoLibrary/html/index.html
+// This file used SoftwareSerial example (Copyright (c) 2012 Dimension Engineering LLC)
+// for Sabertooth http://www.dimensionengineering.com/software/SabertoothSimplifiedArduinoLibrary/html/index.html
 // See license.txt in the Sabertooth arduino library for license details.
-// It is as well derived from HBridgePWM.ino from robokite project
-// https://github.com/baptistelabat/robokite/blob/master/HBridgePWM/HBridgePWM.ino
-// The selector 1 3 5 6 have to be on on.
+//
 //
 // Using example in http://code.google.com/p/arduino-pinchangeint/wiki/Usage
 // Parts of code taken from http://playground.arduino.cc/Main/RotaryEncoders J.Carter(of Earth)
-
+//
+// The Sabertooth selector 1 3 5 6 have to be on on.
+
+// Includes
 #define NO_PORTB_PINCHANGES // PortB used for mySofwareSerial
-#include <mySoftwareSerial.h>
-#include <SabertoothSimplified.h>
-#include <TinyGPS++.h>
-#include <PID_v1.h>
-#include <PinChangeInt.h>
-
-mySoftwareSerial SWSerial(NOT_A_PIN, 8); // RX on no pin (unused), TX on pin 11 (to S1).
+#include <mySoftwareSerial.h> // This is a modified version of SoftwareSerial to be able to use interrupt pin as well
+#include <SabertoothSimplified.h> // From http://www.dimensionengineering.com/software/SabertoothSimplifiedArduinoLibrary/html/_sabertooth_simplified_8h_source.html
+#include <TinyGPS++.h>    // From https://github.com/mikalhart/TinyGPSPlus
+#include <PID_v1.h>       // From https://github.com/br3ttb/Arduino-PID-Library/tree/master/PID_v1
+#include <PinChangeInt.h> // From http://code.google.com/p/arduino-pinchangeint/
+
+// Port definition
+#define   POT_PIN  1 // Potentiometer
+#define     A_PIN  2 // Linear encoder one
+#define     B_PIN  3 // Linear encoder other one
+#define RESET_PIN  4 // Linear encoder absolute reference
+#define    TX_PIN  8 // Plug to Sabertooth RX
+#define    RX_PIN 10 // Do not plug
+#define   LED_PIN 13 // Built-in led
+const int LINE_TENSION_PIN = A2; // For line tension measurement
+
+// String management
+String inputString = "";         // a string to hold incoming data
+boolean stringComplete = false;  // whether the string is complete
+
+// Sabertooth connection
+// Note: NOT_A_PIN (0) was previously used for RX which is not used, but this was causing problems
+mySoftwareSerial SWSerial(RX_PIN, TX_PIN); // RX, TX. RX on no pin (unused), TX on pin 8 (to S1).
 SabertoothSimplified ST(SWSerial); // Use SWSerial as the serial port.
-
-const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
-const int tensionPin = A2;
-const int ledPin = 13;
-
-int sensorValue = 0;        // Value read from the potentiometer
-int initialSensorValue = 0;
-double alphaSigned1 = 0;
-double alphaSigned2 = 0;
-String inputString = "";         // A string to hold incoming data
-boolean stringComplete = false;  // Whether the string is complete
-boolean isSerialControl = true;
-boolean isManualControl = false;
-boolean isFeedbackRequested = false;
-// Read the analog in value
-// The range was reduced
-double sensorValueMin = 200;//0
-double sensorValueMax = 800;//1023
-double deadBand = 0.1; // Use to ensure zero speed. Should not be zero
-double serialFrequency = 1;
-long lastSerialInputTime = 0;
-long lastWriteTime = 0;
-
+int power1, power2;
+
+// NMEA protocol for robust messages
 TinyGPSPlus nmea;
 // O stands for Opensource, R for Robokite
 // The index is the place of the field in the NMEA message
+TinyGPSCustom feedback_request      (nmea, "ORFBR", 1);  // Feedback request
 TinyGPSCustom pwm1     (nmea, "ORPW1", 1);  // Dimentionless voltage setpoint (Pulse Width Modulation) for Sabertooth output 1
 TinyGPSCustom pwm2     (nmea, "ORPW2", 1);  // Dimentionless voltage setpoint (Pulse Width Modulation) for Sabertooth output 2
-TinyGPSCustom setss1   (nmea, "ORSS1", 1);  // Set speed for Sabertooth output 1
-TinyGPSCustom setss2   (nmea, "ORSS2", 1);  // Set speed for Sabertooth output 2
 TinyGPSCustom setpos1  (nmea, "ORSP1", 1);  // Position setpoint for Sabertooth output 1
 TinyGPSCustom setpos2  (nmea, "ORSP2", 1);  // Position setpoint for Sabertooth output 2
-TinyGPSCustom roll     (nmea, "ORKST", 1);  // Kite STate roll (rotation in camera frame)
-TinyGPSCustom elevation(nmea, "ORKST", 2);  // Kite STate elevation
-TinyGPSCustom bearing  (nmea, "ORKST", 3);  // Kite STate bearing
-TinyGPSCustom kpm1      (nmea, "ORKP1", 1);  // Proportional coefficient multiplicator
-TinyGPSCustom kim1      (nmea, "ORKI1", 1);  // Integral coefficient multiplicator
-TinyGPSCustom kdm1      (nmea, "ORKD1", 1);  // Derivative coefficient multiplicator
-TinyGPSCustom kpm2      (nmea, "ORKP2", 1);  // Proportional coefficient multiplicator
-TinyGPSCustom kim2      (nmea, "ORKI2", 1);  // Integral coefficient multiplicator
-TinyGPSCustom kdm2      (nmea, "ORKD2", 1);  // Derivative coefficient multiplicator
-TinyGPSCustom kpmr      (nmea, "ORKPR", 1);  // Proportional coefficient multiplicator
-TinyGPSCustom kimr      (nmea, "ORKIR", 1);  // Integral coefficient multiplicator
-TinyGPSCustom kdmr      (nmea, "ORKDR", 1);  // Derivative coefficient multiplicator
-TinyGPSCustom feedback_request      (nmea, "ORFBR", 1);  // Feedback request
-
+boolean isFeedbackRequested = false;
+
+// PID for robust control
 // Define Variables we'll be connecting to
 double Setpoint1, Input1, Output1;
 double Setpoint2, Input2, Output2;
 double Input3;
-double SetpointRoll, InputRoll, OutputRoll;
-
 // Specify the links and initial tuning parameters (Kp, Ki, Kd)
 PID myPID1(&Input1, &Output1, &Setpoint1, 1, 0, 0, DIRECT);
 PID myPID2(&Input2, &Output2, &Setpoint2, 1, 0, 0, DIRECT);
-PID myPIDRoll(&InputRoll, &OutputRoll, &SetpointRoll, 1, 0, 0, DIRECT);
-
-
-//*****************************************************************************//
-// 'threshold' is the De-bounce Adjustment factor for the Rotary Encoder. halfSteps
-volatile unsigned long threshold = 1000;
-
-// 'halfSteps' is the counter of half-steps. The actual
-// number of steps will be equal to halfSteps / 2
-//
-volatile long halfSteps = 0;
-long halfStepsCorrection = 0;
-
-// Working variables for the interrupt routines
-//
+
+// Define global variables to deal with encoder interrupt
+volatile unsigned long threshold = 1000;// 'threshold' is the De-bounce Adjustment factor for the Rotary Encoder. halfSteps
 volatile unsigned long int0time = 0;
 volatile unsigned long int1time = 0;
 volatile uint8_t int0signal = 0;
 volatile uint8_t int1signal = 0;
 volatile uint8_t int0history = 0;
 volatile uint8_t int1history = 0;
-
-uint8_t latest_interrupted_pin;
-uint8_t interrupt_count[20] = {0}; // 20 possible arduino pins
-
-int pinA = 2;
-int pinB = 3;
-int pinReset = 4;
-
-boolean isAbsoluteReference = false;
-boolean isConnectionAlive = false;
-
-// These constants won't change.  They're used to give names
-// to the pins used:
-const int potPin = 1;  // Analog input pin that the potentiometer is attached to
-
-int barrePotentiometerValue = 0;        // value read from the pot
-
-double linearResolution = 0.005; //Resolution of the linear encoder (in meters)
-double linearRange = 0.05; //Range of the sensor to normalize data (+/- linearRange/2)
-
-double pi = 3.1415;
-double potentiometerRangeDeg = 300;
-double potentiometerMaxRange = potentiometerRangeDeg * pi/180;
-double potentiometerUsedRange = pi/3;
-double potentiometerDistance = 0.05; //Distance from rotation axis to lever arm
-//*********************************************************************************************
+// 'halfSteps' is the counter of half-steps. The actual
+// number of steps will be equal to halfSteps / 2
+volatile long halfSteps = 0;
+long halfStepsCorrection = 0;
+boolean isAbsoluteReferenceAvailable = false;
+
+// Hardware specific parameters
+// Potentiometer
+#define POT_RANGE_DEG      300 // 300 is the value for standard potentiometer
+#define POT_USED_RANGE_DEG  60 // To
+#define POT_OFFSET        0.05 // Distance from rotation axis to lever arm
+#define NEUTRAL_ANGLE_DEG  225
+// Linear encoder
+#define LINEAR_RESOLUTION 0.005
+#define LINEAR_USED_RANGE 0.05

 void setup()
 {
+  pinMode(LED_PIN, OUTPUT);
+
   // Initialize software serial communication with Sabertooth
   SWSerial.begin(9600);

-  // Initialize serial communications at 9600 bps:
-  Serial.begin(19200);
-  Serial.println("Connected");
+  // Initialize serial communications with computer
+  Serial.begin(57600);
+
+  // Reserve bytes for the inputString:
+  inputString.reserve(200);

   // Initialize input and setpoint
   Input1 = 0;
   Input2 = 0;
-  InputRoll = 0;
+  Input3 = 0;
+
   Setpoint1 = 0;
   Setpoint2 = 0;
-  SetpointRoll = 0;
-
-  //turn the PID on
+
+  // Turn the PID on
   myPID1.SetMode(MANUAL);
   myPID2.SetMode(MANUAL);
-  myPIDRoll.SetMode(MANUAL);
   myPID1.SetOutputLimits(-1, 1);
   myPID2.SetOutputLimits(-1, 1);
-  myPIDRoll.SetOutputLimits(-1, 1);
-
-  //*****************************************************
-  pinMode(pinA, INPUT);
-  digitalWrite(pinA, HIGH);
+
+    //*****************************************************
+  pinMode(A_PIN, INPUT);
+  digitalWrite(A_PIN, HIGH);
   attachInterrupt(0, int0, CHANGE);
   //PCintPort::attachInterrupt(pinA, &int0, CHANGE);
-  pinMode(pinB, INPUT);
-  digitalWrite(pinB, HIGH);
+  pinMode(B_PIN, INPUT);
+  digitalWrite(B_PIN, HIGH);
   attachInterrupt(1, int1, CHANGE);
   //PCintPort::attachInterrupt(pinB, &int1, CHANGE);

   // Pin used to get absolute position
-  pinMode(pinReset, INPUT);
-  digitalWrite(pinReset, HIGH);
-  PCintPort::attachInterrupt(pinReset, &reset, CHANGE);
-
-  pinMode(ledPin, OUTPUT);
-
-}
-
-void serialEvent() {
-  isConnectionAlive = true;
-  inputString="";
-  Serial.flush();
+  pinMode(RESET_PIN, INPUT);
+  digitalWrite(RESET_PIN, HIGH);
+  PCintPort::attachInterrupt(RESET_PIN, &reset, CHANGE);
+}
+
+/*
+  SerialEvent occurs whenever a new data comes in the
+ hardware serial RX.  This routine is run between each
+ time loop() runs, so using delay inside loop can delay
+ response.  Multiple bytes of data may be available.
+ */
+void serialEvent()
+{
   while (Serial.available()) {
     // Get the new byte:
-    char inChar = (char)Serial.read();
+    char inChar = (char)Serial.read();
     // Add it to the inputString:
     inputString += inChar;
     // If the incoming character is a newline, set a flag
     // so the main loop can do something about it:
     if (inChar == '\n') {
       stringComplete = true;
-    }
-  }
-  if (inputString[0] == 'i')
-  {
-    Serial.flush();
-    isSerialControl = true;
-    initialSensorValue = analogRead(analogInPin);// Read the joystick position to overide if joystick is moved
-    if (inputString.substring(1)=="")
+    }
+  }
+}
+
+void loop()
+{
+   processSerialInput();
+   computeFeedback();
+   sendFeedback();
+   computeOrder();
+   sendOrder();
+   delay(10);
+}
+
+void processSerialInput()
+{
+  // Print the string when a newline arrives:
+  if (stringComplete)
+  {
+    // Serial.println(inputString);
+    char ctab[inputString.length()+1];
+    inputString.toCharArray(ctab, sizeof(ctab));
+    char *gpsStream = ctab;
+
+    while (*gpsStream)
     {
-      serialFrequency = 0;
-    }
-    else
-    {
-      serialFrequency = StrToFloat(inputString.substring(1));
-    }
-  }
-  else
-  {
-    if (inputString == "o")
-    {
-      isSerialControl = false;
-    }
-    else
-    {
-      char c[50];
-      inputString.toCharArray(c, 50);
-      char *gpsStream = c;
-
-      while (*gpsStream)
-        if (nmea.encode(*gpsStream++))
-      {
-        //Input1 = StrToFloat(elevation.value());
-        lastSerialInputTime = millis();
+      if (nmea.encode(*gpsStream++))
+      {
         if (pwm1.isUpdated())
         {
           myPID1.SetMode(MANUAL);
@@ -232,138 +190,98 @@
         if (feedback_request.isUpdated())
         {
           isFeedbackRequested = true;
-          digitalWrite(ledPin, HIGH);
-        }
-
+          digitalWrite(LED_PIN, HIGH);
+        }
       }
     }
-  }
-}
-
-
-void loop()
-{
-
-  int power1, power2;
-  sensorValue = analogRead(analogInPin);
-
-  process();
-
-  power1 = alphaSigned1*127;
-  power2 = -alphaSigned2*127;
-  ST.motor(1, power1);
-  ST.motor(2, power2);
-  delay(10);
+    // Clear the string:
+    inputString = "";
+    stringComplete = false;
+  }
+}
+
+#define POT_RANGE_DEG      300
+#define POT_USED_RANGE_DEG  60
+#define POT_OFFSET        0.05 //Distance from rotation axis to lever arm
+
+// Linear encoder
+#define LINEAR_RESOLUTION 0.005
+#define LINEAR_USED_RANGE 0.05
+void computeFeedback()
+{
+
+  // Feedbacks are normalized between -1 and 1
+
+  // Potentiomete angle
+  float rawAngle_deg = analogRead(POT_PIN)/1024.0*POT_RANGE_DEG;
+  Input1 = (rawAngle_deg - NEUTRAL_ANGLE_DEG)/POT_USED_RANGE_DEG;
+
+  // Linear encoder position
+  Input2 = halfSteps*LINEAR_RESOLUTION/2/LINEAR_USED_RANGE;
+  // Correct for lever arm (potentiometer not on axis)
+  Input2+= Input1* POT_OFFSET;
+
+  // Line tension
+  Input3 = analogRead(LINE_TENSION_PIN)/512 - 1;
+}
+
+void sendFeedback()
+{
   if (isFeedbackRequested)
   {
-    //lastWriteTime = millis();
-
-    Serial.print((alphaSigned1+1)*512);
+    Serial.print((power1+128)*4);
     Serial.print(", ");
-    Serial.print((alphaSigned2+1)*512);
+    Serial.print((power2+128)*4);
     Serial.print(", ");
     Serial.print((Input1+1)*512);
     Serial.print(", ");
     Serial.print((Input2+1)*512);
     Serial.print(", ");
-    Serial.print(Input3);
-    Serial.print(", ");
-    Serial.println(Input3);
-
-    //isConnectionAlive = false;
+    Serial.print((Input3+1)*512);
+    Serial.println("");
     isFeedbackRequested = false;
-    digitalWrite(ledPin, LOW);
-    if (isSerialControl)
-    {
-      //Serial.println("S");
-    }
-    else
-    {
-      if (isManualControl)
-      {
-        //Serial.println("M");
-      }
-    }
-
-  }
-  Serial.flush();
-}
-
-void setMode()
-{
-  // If the analog value is changed, it means that the user wants to take control with the joystick
-  // so fallback to joystick control
-  if (fabs(initialSensorValue-sensorValue) > 10)
-  {
-    isSerialControl = false;
-  }
-
-  // Fallback to manual control if the analog voltage is close to zero (probably unplugged)
-  // Place after hardware limit if possible
-  // This avoids to go to full speed if one cable in the potentiometer is unplugged
-  // Warning: if the midle cable of the potentiometer is unplugged, the signal is free, and the fault can not be detected
-  // \todo invert polarity to be able to detect floating pin.
-  isManualControl = false;//(sensorValue < 5)|(sensorValue >1023-5);
-}
-
-float StrToFloat(String str){
-  char carray[str.length() + 1]; // Determine the size of the array
-  str.toCharArray(carray, sizeof(carray)); // Put str into an array
-  return atof(carray);
-}
-
-void computeAlphaSigned()
-{
-  if (serialFrequency != 0)
-  { // Fallbacks to zero as we received no message in the expected time (twice the time)
-    if ((millis()-lastSerialInputTime) > 2*1/serialFrequency*1000)
-    {
-      alphaSigned1 = 0;
-      alphaSigned2 = 0;
-    }
-  }
-
-  // If not in Serial control overwrite the value
-  if (false == isSerialControl)
-  {
-    // Compute the value corresponding to the deadband
-    double sensorDeadBandMax = sensorValueMin + (deadBand/2.0+0.5)*(sensorValueMax - sensorValueMin);
-    double sensorDeadBandMin = sensorValueMin + (-deadBand/2.0+0.5)*(sensorValueMax - sensorValueMin);
-    if (sensorValue < sensorDeadBandMin) //strictly to avoid alphaSigned equals zero
-    {
-      alphaSigned1 = (sensorValue-sensorValueMin)/(sensorDeadBandMax - sensorValueMin)-1;
-      alphaSigned2 = 0;
-    }
-    else
-    {
-      if (sensorValue > sensorDeadBandMax)
-      {
-        alphaSigned1 = (sensorValue-sensorDeadBandMax)/(sensorValueMax - sensorDeadBandMax);
-        alphaSigned2 = 0;
-      }
-      else
-      {
-        alphaSigned1 = 0;
-        alphaSigned2 = 0;
-      }
-    }
-    if (isManualControl)
-    {
-      alphaSigned1 = 0;
-      alphaSigned2 = 0;
-    }
-  }
-  alphaSigned1 = min(1, max(-1, alphaSigned1));
-  alphaSigned2 = min(1, max(-1, alphaSigned2));
-}
-
+  }
+}
+
+void computeOrder()
+{
+  if (myPID1.GetMode() == MANUAL)
+  {
+    power1 = atoi(pwm1.value());
+  }
+  if (myPID2.GetMode() == MANUAL)
+  {
+    power2 = atoi(pwm2.value());
+  }
+  if (myPID1.GetMode() == AUTOMATIC)
+  {
+    Setpoint1 = atoi(setpos1.value())/127.;
+    myPID1.Compute();
+    power1 = Output1*127;
+  }
+  if (myPID2.GetMode() == AUTOMATIC)
+  {
+    Setpoint2 = atoi(setpos2.value())/127.;
+    Serial.println(Input2);
+    myPID2.Compute();
+    Serial.println(Output2);
+    power2 = Output2*127;
+  }
+}
+
+void sendOrder()
+{
+  // Order in the range -127/127
+   ST.motor(1, power1);
+   ST.motor(2, power2);
+}

 void int0()
 {
   if ( micros() - int0time < threshold )
     return;
   int0history = int0signal;
-  int0signal = bitRead(PIND, pinA);
+  int0signal = bitRead(PIND, A_PIN);
   if ( int0history==int0signal )
     return;
   int0time = micros();
@@ -378,77 +296,14 @@
   if ( micros() - int1time < threshold )
     return;
   int1history = int1signal;
-  int1signal = bitRead(PIND, pinB);
+  int1signal = bitRead(PIND, B_PIN);
   if ( int1history==int1signal )
     return;
   int1time = micros();
 }
-
 void reset()
 {
   halfStepsCorrection = halfSteps;
-  isAbsoluteReference = true;
+  isAbsoluteReferenceAvailable = true;
  }

-void computeFeedback()
-{
-  long steps = (halfSteps / 2);
-  //Serial.print("T");
-  //Serial.println(steps);
-  double relative_position_m = (halfSteps)*linearResolution/2;
-  double absolute_position_m = (halfSteps-halfStepsCorrection)*linearResolution/2;
-
-  // read the analog in value:
-  double raw_angle = analogRead(potPin)/1024.0*potentiometerMaxRange;
-  double neutralAngle = 0.75*potentiometerMaxRange;
-  double angle = raw_angle - neutralAngle;
-  double correction_m = angle*potentiometerDistance;
-  Input1 = angle/potentiometerUsedRange;
-  Input2 = relative_position_m/linearRange;
-  Input3 = analogRead(tensionPin);
-  //Serial.print("P");
-  //Serial.println(Input1);
-  //Serial.print("A");
-  //Serial.println(Input2);
-
-  InputRoll = StrToFloat(roll.value());
-
-}
-
-void process()
-{
-  //setMode();
-  computeFeedback();
-  if (myPID1.GetMode() ==MANUAL)
-  {
-    alphaSigned1 = StrToFloat(pwm1.value());
-  }
-  if (myPID1.GetMode() ==AUTOMATIC)
-  {
-    Setpoint1 = StrToFloat(setpos1.value());
-    myPID1.Compute();
-    alphaSigned1 = Output1;
-  }
-  if (myPID2.GetMode() ==MANUAL)
-  {
-    alphaSigned2 = StrToFloat(pwm2.value());
-  }
-  if (myPID2.GetMode() ==AUTOMATIC)
-  {
-    double offset_m = -0.0;
-    Setpoint2 = StrToFloat(setpos2.value()) + offset_m/linearRange;
-    myPID2.Compute();
-    alphaSigned2 = Output2;
-  }
-}
-
-void computePIDTuning()
-{
-  myPID1.SetTunings(StrToFloat(kpm1.value()), StrToFloat(kim1.value()), StrToFloat(kdm1.value()));
-  myPID2.SetTunings(StrToFloat(kpm2.value()), StrToFloat(kim2.value()), StrToFloat(kdm2.value()));
-  myPIDRoll.SetTunings(StrToFloat(kpmr.value()), StrToFloat(kimr.value()), StrToFloat(kdmr.value()));
-
-}
-
-
-


Add tag for Vim

Add tag for Vim

--- sketch/sketch.ino
+++ sketch/sketch.ino
@@ -2,7 +2,7 @@
 #include <Servo.h>

 /* サーボモータの制御クラス */
-class ServoIO{
+class ServoIO{ //{{{

   Servo servo; /* サーボのピン */

@@ -32,10 +32,10 @@
     void servoPin(int pin){
       servo.attach(pin);
     }
-};
+}; //}}}

 /* モータの制御クラス */
-class MotorIO{
+class MotorIO{ //{{{

   /* モータの状態を表す型 */
   struct MotorState{
@@ -105,10 +105,10 @@
     void updateMotorState(){
       motor();
     }
-};
+};//}}}

 /* 制御のクラス */
-class Control: public ServoIO, public MotorIO{
+class Control: public ServoIO, public MotorIO{ //{{{
   int errorPinNum; /* エラーピンの番号を表す */
   void error(void){
     digitalWrite(errorPinNum,HIGH);
@@ -134,7 +134,7 @@
       errorPinNum = pin;
       pinMode(pin,OUTPUT);
     }
-};
+};//}}}

 Control ctrl;


Update McLighting.ino

Update McLighting.ino

--- Arduino/McLighting/McLighting.ino
+++ Arduino/McLighting/McLighting.ino
@@ -112,7 +112,7 @@
   #include <NeoPixelBus.h>
   NeoEsp8266Uart1800KbpsMethod dma = NeoEsp8266Uart1800KbpsMethod(NUMLEDS, 3);
 #endif
-#if defined(USE_WS2812FX_DMA) or defined(USE_WS2812FX_UART)
+#if defined(USE_WS2812FX_DMA) or defined(USE_WS2812FX_UART1) or defined(USE_WS2812FX_UART2)
   void DMA_Show(void) {
     if(dma.IsReadyToUpdate()) {
       memcpy(dma.getPixels(), strip.getPixels(), dma.getPixelsSize());


Added delay after write before reading

Added delay after write before reading

--- examples/usage.ino
+++ examples/usage.ino
@@ -16,6 +16,10 @@
 	// Random write command
 	eeprom.write( 0, (long)0x1234567 );

+	// Need to wait some time before reading after a write
+	while( !eeprom.isReady() )
+		delay(2);
+
 	// Random read command
 	long rd;
 	eeprom.read(0,&rd);
@@ -26,6 +30,10 @@
 	eeprom.write( (int)20 );
 	eeprom.write( (int)30 );
 	eeprom.endWrite();
+
+	// Need to wait some time before reading after a write
+	while( !eeprom.isReady() )
+		delay(2);

 	// Sequential read
 	int a, b, c;
@@ -39,6 +47,10 @@
 	int data[5] = { 10, 20, 30, 40, 50 };
 	eeprom.writeArray( 0, data, 5 );

+	// Need to wait some time before reading after a write
+	while( !eeprom.isReady() )
+		delay(2);
+
 	// Array read
 	eeprom.readArray( 0, data, 5 );
 }


Examples: Earpieces: EarpieceManualMixing: replace serviceSD with built-in one

--- examples/09-Earpieces/EarpieceManualMixing_wSD/EarpieceManualMixing_wSD.ino
+++ examples/09-Earpieces/EarpieceManualMixing_wSD/EarpieceManualMixing_wSD.ino
@@ -207,7 +207,7 @@
   //while (Serial1.available()) serialManager.respondToByte((char)Serial1.read()); //BT Serial

   //service the SD recording
-  serviceSD();
+  audioSDWriter.serviceSD_withWarnings(i2s_in); //For the warnings, it asks the i2s_in class for some info

   //service the LEDs...blink slow normally, blink fast if recording
   myTympan.serviceLEDs(millis(),audioSDWriter.getState() == AudioSDWriter::STATE::RECORDING);
@@ -255,53 +255,6 @@
 } //end servicePotentiometer();

-#define PRINT_OVERRUN_WARNING 1   //set to 1 to print a warning that the there's been a hiccup in the writing to the SD.
-void serviceSD(void) {
-  static int max_max_bytes_written = 0; //for timing diagnotstics
-  static int max_bytes_written = 0; //for timing diagnotstics
-  static int max_dT_micros = 0; //for timing diagnotstics
-  static int max_max_dT_micros = 0; //for timing diagnotstics
-
-  unsigned long dT_micros = micros();  //for timing diagnotstics
-  int bytes_written = audioSDWriter.serviceSD();
-  dT_micros = micros() - dT_micros;  //timing calculation
-
-  if ( bytes_written > 0 ) {
-
-    max_bytes_written = max(max_bytes_written, bytes_written);
-    max_dT_micros = max((int)max_dT_micros, (int)dT_micros);
-
-    if (dT_micros > 10000) {  //if the write took a while, print some diagnostic info
-      max_max_bytes_written = max(max_bytes_written,max_max_bytes_written);
-      max_max_dT_micros = max(max_dT_micros, max_max_dT_micros);
-
-      Serial.print("serviceSD: bytes written = ");
-      Serial.print(bytes_written); Serial.print(", ");
-      Serial.print(max_bytes_written); Serial.print(", ");
-      Serial.print(max_max_bytes_written); Serial.print(", ");
-      Serial.print("dT millis = ");
-      Serial.print((float)dT_micros/1000.0,1); Serial.print(", ");
-      Serial.print((float)max_dT_micros/1000.0,1); Serial.print(", ");
-      Serial.print((float)max_max_dT_micros/1000.0,1);Serial.print(", ");
-      Serial.println();
-      max_bytes_written = 0;
-      max_dT_micros = 0;
-    }
-
-    //print a warning if there has been an SD writing hiccup
-    if (PRINT_OVERRUN_WARNING) {
-      //if (audioSDWriter.getQueueOverrun() || i2s_in.get_isOutOfMemory()) {
-      if (i2s_in.get_isOutOfMemory()) {
-        float approx_time_sec = ((float)(millis()-audioSDWriter.getStartTimeMillis()))/1000.0;
-        if (approx_time_sec > 0.1) {
-          Serial.print("SD Write Warning: there was a hiccup in the writing.");//  Approx Time (sec): ");
-          Serial.println(approx_time_sec );
-        }
-      }
-    }
-    i2s_in.clear_isOutOfMemory();
-  }
-}

 // ////////////// Change settings of system


Update BotBoarduino_LIDAR_Lite_Sweep_Scan.ino

--- BotBoarduino/BotBoarduino_LIDAR_Lite_Sweep_Scan/BotBoarduino_LIDAR_Lite_Sweep_Scan.ino
+++ BotBoarduino/BotBoarduino_LIDAR_Lite_Sweep_Scan/BotBoarduino_LIDAR_Lite_Sweep_Scan.ino
@@ -5,7 +5,7 @@
 /* Date: 2015-03-31
 /*
 /* Short example based on the Servo library example "Sweep" example and the Pulsed Light 3D examples.
-/* The servo motor is attached to pin 5 and rotates from 0-180 degrees continuously by 1 degree increments.
+/* The servo motor* is attached to pin 5 and rotates from 0-180 degrees continuously by 1 degree increments.
 /* The LIDAR lite is attached to VCC (+5 V DC), GND, SDA and SCL.
 /*
 /* This examples uses the Wire library.
@@ -13,9 +13,12 @@
 /* Hardware used:
 /* BotBoarduino: http://www.robotshop.com/en/lynxmotion-botboarduino-robot-controller.html?product-code=RB-Lyn-363
 /* LIDAR-Lite Laser Rangefinder: http://www.robotshop.com/en/lidar-lite-laser-rangefinder-pulsedlight.html?product-code=RB-Pli-01
-/* HS-422 servo motor: http://www.robotshop.com/en/hitec-hs422-servo-motor.html?product-code=RB-Hit-27
+/* HS-645MG servo motor: http://www.robotshop.com/en/hitec-hs645mg-servo-motor.html?product-code=RB-Hit-29
+/* (alternative) HS-422 servo motor: http://www.robotshop.com/en/hitec-hs422-servo-motor.html?product-code=RB-Hit-27
 /* Bracket to hold the LIDAR: http://www.robotshop.com/en/aluminum-l-connector-bracket-asb-06.html?product-code=RB-Lyn-83
 /* Bracket to hold the servo motor: http://www.robotshop.com/en/lynxmotion-aluminum-multi-purpose-servo.html?product-code=RB-Lyn-81
+/*
+/* *: Please note that while we used a HS-645MG in our example, the HS-422 and almost any other standard RC servo motor could perform this task.
 /*
 /**********************************************************************************************************/


Update to gucci_motor_testing.ino

Update to gucci_motor_testing.ino

--- Kirbi/testing/gucci_motor_testing/gucci_motor_testing.ino
+++ Kirbi/testing/gucci_motor_testing/gucci_motor_testing.ino
@@ -27,10 +27,29 @@
       }
     }
   }
-
   ESC_L_SERIAL.write(bytes[0]);
   ESC_L_SERIAL.write(bytes[1]);
   ESC_L_SERIAL.write(bytes[2]);
   ESC_L_SERIAL.write(crc);
-
+  delay(100);
+
+  bytes[0] = ESC_L_ADDRESS;
+  bytes[1] = 0; //0 is drive forward
+  bytes[2] = 0; //drive motor at half speed
+  crc = 0;
+  for(int i = 0; i < 3; i++) {
+    crc = crc ^ (bytes[i] << 8);
+    for (int j = 0; j < 8; j++) {
+      if (crc & 0x8000) {
+        crc = (crc << 1) ^ 0x1021;
+      } else {
+        crc = crc << 1;
+      }
+    }
+  }
+  ESC_L_SERIAL.write(bytes[0]);
+  ESC_L_SERIAL.write(bytes[1]);
+  ESC_L_SERIAL.write(bytes[2]);
+  ESC_L_SERIAL.write(crc);
+  delay(100);
 }


Use only RMC

Use only RMC

--- src/src.ino
+++ src/src.ino
@@ -43,7 +43,7 @@
     /* Configure GPS - 1Hz update frequency, full NMEA output */
     Adafruit_GPS gps(&GPSSerial);
     gps.begin(9600);
-    gps.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
+    gps.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
     gps.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ) ;
     gps.sendCommand(PGCMD_ANTENNA);
     gps.sendCommand(PMTK_Q_RELEASE);


recursive directory listing at start

recursive directory listing at start

--- src/src.ino
+++ src/src.ino
@@ -167,19 +167,28 @@
   Serial.println(F("SD initialized"));

   File root = SD.open(F("/"));
+  printDirectory(root, 0);
+  root.close();
+}
+
+void printDirectory(File dir, int numTabs) {
   while (true) {
-    File entry = root.openNextFile();
+    File entry = dir.openNextFile();
     if (!entry) break;
+    for (uint8_t i = 0; i < numTabs; i++) {
+      Serial.print('\t');
+    }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println(F("/"));
+      printDirectory(entry, numTabs+1);
     } else {
       Serial.print(F("\t\t"));
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
-  root.close();
+
 }

 void initializePlayer() {


bit of cleanup

bit of cleanup

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -1,13 +1,13 @@
 //#include "DataInterpretor.h"
 #include <ComData.h>
 #include <StringEater.h>
-
 #include <DataInterpretor.h>

 #define MAX_COMMANDS 2
 #define MAX_PARAM 2

-void(*CommandList[MAX_COMMANDS])(const String[MAX_PARAM], const unsigned int number_params);
+void(*CommandList[MAX_COMMANDS])
+		(const String[MAX_PARAM], const unsigned int number_params);

 int registerd_commands = 0;

@@ -114,4 +114,4 @@

 		Serial.println(value+"}");
 	}
-}+}


BearSSL Max Fragment Length Negotation and Node.js server (#5929)

* Minor bug fixes in Maximum Fragment Length Negotation example, mainly giving background processes some time in fetch()

* Minor layout changes to pass travis tests

* Use PolledTimeout for timeout

--- libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino
+++ libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino
@@ -5,6 +5,7 @@
 // Released to the public domain

 #include <ESP8266WiFi.h>
+#include <PolledTimeout.h>

 #ifndef STASSID
 #define STASSID "your-ssid"
@@ -17,17 +18,22 @@
 void fetch(BearSSL::WiFiClientSecure *client) {
   client->write("GET / HTTP/1.0\r\nHost: tls.mbed.org\r\nUser-Agent: ESP8266\r\n\r\n");
   client->flush();
-  uint32_t to = millis() + 5000;
+  using oneShot = esp8266::polledTimeout::oneShot;
+  oneShot timeout(5000);
   do {
     char tmp[32];
-    memset(tmp, 0, 32);
     int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1);
     yield();
     if (rlen < 0) {
       break;
     }
+    if (rlen == 0) {
+      delay(10); // Give background processes some time
+      continue;
+    }
+    tmp[rlen] = '\0';
     Serial.print(tmp);
-  } while (millis() < to);
+  } while (!timeout);
   client->stop();
   Serial.printf("\n-------\n");
 }
@@ -73,11 +79,11 @@

   BearSSL::WiFiClientSecure client;
   client.setInsecure();
-  bool mfln = client.probeMaxFragmentLength("tls.mbed.org", 443, 1024);
+  bool mfln = client.probeMaxFragmentLength("tls.mbed.org", 443, 512);
   Serial.printf("\nConnecting to https://tls.mbed.org\n");
   Serial.printf("MFLN supported: %s\n", mfln ? "yes" : "no");
   if (mfln) {
-    client.setBufferSizes(1024, 1024);
+    client.setBufferSizes(512, 512);
   }
   client.connect("tls.mbed.org", 443);
   if (client.connected()) {
@@ -125,6 +131,6 @@
   yield();

   Serial.printf("\n\n");
-  Serial.printf("Default SSL:        %d bytes used\n", a);
-  Serial.printf("1024 byte MFLN SSL: %d bytes used\n", b);
+  Serial.printf("Default SSL:       %d bytes used\n", a);
+  Serial.printf("512 byte MFLN SSL: %d bytes used\n", b);
 }


API prototype for basic movement

API prototype for basic movement

--- tankbot.ino
+++ tankbot.ino
@@ -1,4 +1,6 @@
 #include <FiniteStateMachine.h>
+#include <SPI.h>
+#include <aREST.h>
 #include "LogHelpers.h"
 #include "TimingHelpers.h"

@@ -8,15 +10,20 @@
 // FSM states
 State startupState = State(enterStartupState,updateStartupState,leaveStartupState);
 State idleState = State(enterIdleState,updateIdleState,leaveIdleState);
+State forwardState = State(enterForwardState, updateForwardState, leaveForwardState);
+State backwardState = State(enterBackwardState, updateBackwardState, leaveBackwardState);

-FSM stateMachine = FSM(startupState);
+FSM stateMachine = FSM(startupState);
+
+aREST rest = aREST();

 void setup() {
-  startLog();
+  startLog(); // starts Serial, and prints a message if DEBUG is enabled
 }

 void loop() {
   stateMachine.update();
+  rest.handle(Serial);
 }

 // ******************* FSM state callback methods *******************
@@ -25,6 +32,13 @@
   info(F("Booting up..."));
 }
 void updateStartupState() {
+  // set up the REST listener
+  rest.function("tb", setControlState);
+
+  // get the REST service registered
+  rest.set_id("001");
+  rest.set_name("tankbot");
+
   stateMachine.transitionTo(idleState);
 }
 void leaveStartupState() {
@@ -34,13 +48,72 @@
 // -------------- Idle State ---------------
 void enterIdleState() {
   info(F("Idling, ready for commands..."));
-  digitalWrite(13, HIGH);
+  allStop();
 }
-void updateIdleState() {
+void updateIdleState() {}
+void leaveIdleState() {}

+// -------------- Forward State ---------------
+
+// Move the bot forward at full speed
+void enterForwardState() {
+  allStart();
+  allSpeedAhead();
 }
-void leaveIdleState() {
+void updateForwardState() {}
+void leaveForwardState() {
+  allStop();
+}

+// -------------- Backward State ---------------
+
+// Move the bot backward at full speed
+void enterBackwardState() {
+  allStart();
+  allSpeedReverse();
+}
+void updateBackwardState() {}
+void leaveBackwardState() {
+  allStop();
+}
+
+
+// ******************* HELPERS *******************
+
+// aREST API listener
+int setControlState(String command) {
+  info(F("Handling a REST request"));
+  info(command);
+  if (command.startsWith("stop")) {
+     stateMachine.transitionTo(idleState);
+     return 2;
+  }
+  if (command.startsWith("forward")) {
+     stateMachine.transitionTo(forwardState);
+     return 3;
+  }
+  if (command.startsWith("backward")) {
+     stateMachine.transitionTo(backwardState);
+     return 4;
+  }
+  return 1;
 }

 // ******************* HELPERS *******************
+
+// -------------- Motor Driver Helpers ---------------
+// disable the motors via the motor driver STANDBY
+void allStop() {
+  warn(F("enabling STANDBY"));
+}
+// disable the motors via the motor driver STANDBY
+void allStart() {
+  warn(F("disabling STANDBY"));
+}
+void allSpeedAhead() {
+  warn(F("moving forward"));
+}
+void allSpeedReverse() {
+  warn(F("moving backward"));
+}
+


nefunguje detekce string0

nefunguje detekce string0

--- guitar-arduino.ino
+++ guitar-arduino.ino
@@ -40,10 +40,11 @@
 #define VELOCITY_MIN 74 //bylo 80
 #define EFFECT_THOLD_MS 5000 //[ms] how often to effect setting
 #define VIBRATO_THOLD_MS 5 //[ms] how often send vibrato events, real event sent only if not 0
+#define NO_FRETS 13
 //#define DBG 1
 //#define DBG2 1

-int fret_pins[13] = {47,43,25,41,27,23,35,37,45,29,31,33,39};
+int fret_pins[NO_FRETS] = {47,43,25,41,27,23,35,37,45,29,31,33,39};
 int string_pins[6]= {32,30,28,26,24,22};
 int laser_pins[6] = {A0,A2,A4,A3,A6,A5};  //bpw34 photodiode
 int emphasis_pin  = A1;
@@ -52,7 +53,7 @@
 int effect_pin = A8;
 uint8_t pitch = 0;

-boolean fret_status[13][6];
+boolean fret_status[NO_FRETS][6];
 int fret_status_last_f = UNDEF;
 int fret_status_last_used = UNDEF;
 unsigned long fret_status_last_f_us = 0;
@@ -150,17 +151,14 @@
 #endif

   //check for sliding
-  if (s ==0) {  //jen pro vybrnkavani
+  if (s ==0 ) {  //jen pro vybrnkavani
     unsigned long diff_us = micros() - fret_status_last_f_us;
     if (diff_us < FRET_SLIDING_THOLD) {
       int dir = f - fret_status_last_used; //0: no sliding, -1:sliding outward: 1: sliding inward
       send_fret_sliding_event(dir, f);
-    }
-    else {
-      send_fret_sliding_event(0, f);  //reset pitch
-    }
-    fret_status_last_used = f;
-    fret_status_last_f_us = micros();
+      fret_status_last_used = f;
+      fret_status_last_f_us = micros();
+    }
   }

   //set status
@@ -184,21 +182,27 @@
   Serial.println(l_idx);
 #endif

-  bool sp = is_string_pressed_on_active_fret(0);
-  if (laser_blocked && sp) {
-    for (int i = 0; i < 6; i++) { //mute all strings if vybrnkavaci struna is pressed
-      midiEventPacket_t packet0 = {0x08, 0x80 | 0, played_notes[i], 0};
+  if (laser_blocked) {
+    int s0p = 1;
+    for (int fr = 0; fr < NO_FRETS; fr++) {
+      s0p += (fret_status[fr][0]) ? 1 : 0;
+    }
+    if (s0p > 0) {
+      for (int i = 0; i < 6; i++) { //mute all strings if vybrnkavaci struna is pressed
+        midiEventPacket_t packet0 = {0x08, 0x80 | 0, played_notes[i], 0};
+        MidiUSB.sendMIDI(packet0);
+        MidiUSB.flush();
+        delay(2);
+      }
+    }
+    if (s0p == 0) {  // finger is muting current laser
+      midiEventPacket_t packet0 = {0x08, 0x80 | 0, played_notes[l_idx], 0};
       MidiUSB.sendMIDI(packet0);
       MidiUSB.flush();
       delay(2);
     }
-  }
-  if (laser_blocked && !sp) {  // finger is muting current laser
-    midiEventPacket_t packet0 = {0x08, 0x80 | 0, played_notes[l_idx], 0};
-    MidiUSB.sendMIDI(packet0);
-    MidiUSB.flush();
-    delay(2);
-  }
+  }  //end of laser_blocked
+
   if (!laser_blocked) {  //finger is releasing string(laser)
     if (pitch != 0) {
       send_fret_sliding_event(0, 0);  //reset pitch
@@ -268,7 +272,7 @@

   if (!skip_setup) {
     //find if instrument selection is pressed (top string), fret selects instrument
-    for (int i = 0; i < 13; i++) {
+    for (int i = 0; i < NO_FRETS; i++) {
       if ((fret_status[i][5] == true)) {
         midiEventPacket_t special = {0x0C, 0xC0, instruments[i], 0};
         MidiUSB.sendMIDI(special);
@@ -277,7 +281,7 @@
     }

     //find if capo selection is requested (bottom string), max 8th fret, 9-13 fret means remove capo
-    for (int i = 0; i < 13; i++) {
+    for (int i = 0; i < NO_FRETS; i++) {
       if ((fret_status[i][0] == true)) {
         selected_capo_id = (i < 8) ? i + 1 : 0;  //frets 9 and more removes capo
       }
@@ -463,18 +467,8 @@
     laser_status[l] = 0;
     laser_status_last_update_us[l] = 0;
     last_alaser_status[l] = false;
-//    pinMode(laser_pins[l], INPUT);  //neni treba pro analog read
-  }
-
-//  attachInterrupt(digitalPinToInterrupt(laser_pins[0]), laser0_ISR, RISING);
-//  attachInterrupt(digitalPinToInterrupt(laser_pins[1]), laser1_ISR, CHANGE);  //there is some HW difference, does not jitter that much
-//  attachInterrupt(digitalPinToInterrupt(laser_pins[2]), laser2_ISR, RISING);
-//  attachInterrupt(digitalPinToInterrupt(laser_pins[3]), laser3_ISR, RISING);
-//  attachInterrupt(digitalPinToInterrupt(laser_pins[4]), laser4_ISR, RISING);
-//  attachInterrupt(digitalPinToInterrupt(laser_pins[5]), laser5_ISR, RISING);
-
-//  pinMode(emphasis_pin, INPUT);  //neni treba pro analog read
-//  attachInterrupt(digitalPinToInterrupt(emphasis_pin), laseremphasis_ISR, RISING);
+  }
+
   last_alaser_status[6] = false;  //emhasis

   //init input pins with internal pullup resistors
@@ -490,7 +484,7 @@
 {
   bool narazil_na_prst = false;
   //scan fret by fret
-  for (int f = 0; f <= 12; f++) { //f<=12
+  for (int f = 0; f <= (NO_FRETS-1); f++) { //f<=12

     set_fret(f);
     //scan strings for this fret