Calibrated and tested program with AL5D robot arm

Found the pulse lengths associated to minimum and maximum angles for
each servo for calibration.

Added new function to sent pulse length data to servos directly.

Changed map function to algebraic formulae to cope with double
precision.

--- AL5D/al5d.ino
+++ AL5D/al5d.ino
@@ -1,5 +1,5 @@
 /*********************************************************************************************************/
-/* File: AL5D.ino                                                                                */
+/* File: al5d.ino                                                                                */
 /* Author: Darren McMorran                                                                               */
 /* Date Started: 28/05/2015                                                                              */
 /*                                                                                */
@@ -98,9 +98,9 @@
 #define WRI_H_REF 362

 // Gripper positions
-#define GRI_OPEN 100
-#define GRI_MICROPLATE 160
-#define GRI_MICROSLIDE 110
+#define GRI_OPEN 90
+#define GRI_MICROPLATE 150 //500 PulseLength
+#define GRI_MICROSLIDE 150 //500 PulseLength
 #define GRI_CLOSED 180

 // Directional definitions for controlling slider
@@ -121,27 +121,31 @@
 // want these to be as small/large as possible without hitting the hard stop
 // for max range. You'll have to tweak them as necessary to match the servos you
 // have!
-#define BAS_MIN_D  0   // this is the 'minimum' angle in base servo range, 0 = -y direction
+#define BAS_MIN_D  90   // this is the 'minimum' angle in base servo range, 0 = -y direction
 #define BAS_MAX_D  180 // this is the 'maximum' angle in base servo range, 180 = +y direction
-#define SHL_MIN_D  0   // 0 = horizontal in +x direction
-#define SHL_MAX_D  180 // 180 = horizontal in -x direction
-#define ELB_MIN_D  0   // 0 = elbow closed
+#define SHL_MIN_D  16   // 0 = horizontal in +x direction
+#define SHL_MAX_D  165.762 // 180 = horizontal in -x direction
+#define ELB_MIN_D  11.5385   // 0 = elbow closed
 #define ELB_MAX_D  180 // 180 = elbow open, ulna parallel to humerus
-#define WRI_MIN_D  0   // 0 = wrist closed
+#define WRI_MIN_D  43.125 // 0 = wrist closed
 #define WRI_MAX_D  180 // 180 = wrist open, hand parallel to ulna
-#define GRI_MIN_D  100 // 100 = gripper fully open
+#define GRI_MIN_D  90 // 100 = gripper fully open
 #define GRI_MAX_D  180 // 180 = gripper fully closed

-#define BAS_MIN    146 // this is the pulse length count (out of 4096) that corresponds to BAS_MIN_D
-#define BAS_MAX    590 // this is the pulse length count (out of 4096) that corresponds to BAS_MAX_D
-#define SHL_MIN    186 // this is the pulse length count (out of 4096) that corresponds to SHL_MIN_D
-#define SHL_MAX    612 // this is the pulse length count (out of 4096) that corresponds to SHL_MAX_D //HS805BB 186-612
-#define ELB_MIN    590 // this is the pulse length count (out of 4096) that corresponds to ELB_MIN_D
-#define ELB_MAX    146 // this is the pulse length count (out of 4096) that corresponds to ELB_MAX_D
-#define WRI_MIN    146 // this is the pulse length count (out of 4096) that corresponds to WRI_MIN_D
-#define WRI_MAX    590 // this is the pulse length count (out of 4096) that corresponds to WRI_MAX_D
-#define GRI_MIN    382 // this is the pulse length count (out of 4096) that corresponds to GRI_MIN_D
+#define BAS_MIN    383 // this is the pulse length count (out of 4096) that corresponds to BAS_MIN_D
+#define BAS_MAX    160 // this is the pulse length count (out of 4096) that corresponds to BAS_MAX_D
+#define SHL_MIN    200 // this is the pulse length count (out of 4096) that corresponds to SHL_MIN_D
+#define SHL_MAX    540 // this is the pulse length count (out of 4096) that corresponds to SHL_MAX_D //HS805BB 186-612
+#define ELB_MIN    540 // this is the pulse length count (out of 4096) that corresponds to ELB_MIN_D
+#define ELB_MAX    175 // this is the pulse length count (out of 4096) that corresponds to ELB_MAX_D
+#define WRI_MIN    500 // this is the pulse length count (out of 4096) that corresponds to WRI_MIN_D
+#define WRI_MAX    135 // this is the pulse length count (out of 4096) that corresponds to WRI_MAX_D
+#define GRI_MIN    320 // this is the pulse length count (out of 4096) that corresponds to GRI_MIN_D
 #define GRI_MAX    590 // this is the pulse length count (out of 4096) that corresponds to GRI_MAX_D
+//WRI 375 = 90
+//ELB 370 = 90
+//SHL 368 = 90
+//BAS 383 = 90

 #define BAS_PARK 90
 #define SHL_PARK 90
@@ -463,17 +467,33 @@
 // Write angle to servo using microseconds for added precision
 int servoWrite( int id, double angle_d )
 {
-//   DEBUG("servoWrite("); DEBUG(id); DEBUG(", "); DEBUG(angle_deg); DEBUGln(")");
+   //DEBUG("servoWrite("); DEBUG(id); DEBUG(", "); DEBUG(angle_deg); DEBUGln(")");
    if (angle_d < SERVO_MIN_D[id]) { DEBUG(angle_d); DEBUG("<"); DEBUGln(SERVO_MIN_D[id]); return -1; }
    if (angle_d > SERVO_MAX_D[id]) { DEBUG(angle_d); DEBUG(">"); DEBUGln(SERVO_MAX_D[id]); return -2; }

-   double pulseLength = map(angle_d, 0, 180, SERVO_MIN[id], SERVO_MAX[id]);
-
+   double gradient = (SERVO_MAX[id]-SERVO_MIN[id])/(SERVO_MAX_D[id]-SERVO_MIN_D[id]);
+   double pulseLength = angle_d*gradient + SERVO_MIN[id] - gradient*SERVO_MIN_D[id];// + map(angle_d, SERVO_MIN_D[id], SERVO_MAX_D[id], SERVO_MIN[id], SERVO_MAX[id]);
+
    pwm.setPWM(id, 0, pulseLength);

+   DEBUG("pwm.setPWM("); DEBUG(id); DEBUG(", 0, "); DEBUG(pulseLength); DEBUGln(")");
+
    g_angle_d[id] = angle_d;

    return 0;
+}
+
+// Write to servo using pulse length, USE ONLY FOR TESTING
+int servoWritePulse( int id, double pulseLength)
+{
+  if (pulseLength < min(SERVO_MIN[id], SERVO_MAX[id])) { DEBUGln(min(SERVO_MIN[id], SERVO_MAX[id])); return -1; }
+  if (pulseLength > max(SERVO_MIN[id], SERVO_MAX[id])) { DEBUGln(max(SERVO_MIN[id], SERVO_MAX[id])); return -2; }
+
+  pwm.setPWM(id, 0, pulseLength);
+
+  DEBUG("pwm.setPWM("); DEBUG(id); DEBUG(", 0, "); DEBUG(pulseLength); DEBUGln(")");
+
+  return 0;
 }

 // Calculates the cylindrical coordinates of the wrist from the servo angles
@@ -604,7 +624,8 @@
             buf[i] = '\0';
             number[0] = atof(buf);
             g_moveDelay = 50;
-            Serial.println(slowMoveArm(number[0],g_angle_d[SHL],g_angle_d[ELB],g_angle_d[WRI]));
+            Serial.println(servoWrite(BAS, number[0]));
+            //Serial.println(slowMoveArm(number[0],g_angle_d[SHL],g_angle_d[ELB],g_angle_d[WRI]));
             break;

          case '<': // start of coordinate move packet


Update dragino_sht11_mqtt.ino

Update dragino_sht11_mqtt.ino

--- rr/dragino_sht11_mqtt.ino
+++ rr/dragino_sht11_mqtt.ino
@@ -59,7 +59,8 @@

  sensors.requestTemperatures();

- tempC2 = sensors.getTempCByIndex(0),4 * 100;
+ tempC2 = sensors.getTempCByIndex(0),4;
+ tempC3 = tempC2 * 100;

  //tempC2 = sensors.getTempC(probe01);

@@ -89,7 +90,7 @@
    if (millis() > (time + 15000)) {
        time = millis();

- String pubString = "" + String(t) + "," + String(tempC2) + "," + String(h) + "," + id_sensor + "";
+ String pubString = "" + String(t) + "," + String(tempC3) + "," + String(h) + "," + id_sensor + "";
    pubString.toCharArray(message_buff, pubString.length()+1);
    mqtt.publish("rr/temp",message_buff );


only send changes

only send changes

--- examples/RF12/otRelay/otRelay.ino
+++ examples/RF12/otRelay/otRelay.ino
@@ -9,7 +9,14 @@
 // buffer to collect last data received
 byte lastChars[9], lastFill;

+// the last values received, one entry for each ID 0..255
+struct { byte values[2]; } history [256];
+
 static bool shouldSend (const byte* payload) {
+  byte id = payload[0];
+  if (memcmp(payload + 1, history[id].values, 2) == 0)
+    return false;
+  memcpy(history[id].values, payload + 1, 2);
   return true;
 }


[Firmware] Use serveStatic from HTTPServer

--- firmware/lm-wifilamp/x60_server.ino
+++ firmware/lm-wifilamp/x60_server.ino
@@ -4,18 +4,12 @@
 #define SERVER_AUTH_REQUIRED if (!serverAuthenticateUser()) return;

 void serverSetup() {
-  server.on("/", []() {
-    serverSendFile("/web/index.html", "text/html");
-  });
-  server.on("/bundle.js", []() {
-    serverSendFile("/web/bundle.js.gz", "application/javascript");
-  });
-  server.on("/style.css", []() {
-    serverSendFile("/web/style.css.gz", "text/css");
-  });
-  server.on("/favicon.ico", []() {
-    serverSendFile("/web/favicon.ico", "image/x-icon");
-  });
+  server.serveStatic("/", SPIFFS, "/web/index.html");
+  server.serveStatic("/settings", SPIFFS, "/web/index.html");
+  server.serveStatic("/bundle.js", SPIFFS, "/web/bundle.js");
+  server.serveStatic("/style.css", SPIFFS, "/web/style.css");
+  server.serveStatic("/favicon.ico", SPIFFS, "/web/favicon.ico");
+  server.serveStatic("/header.png", SPIFFS, "/web/header.png");

 #if LOG_ENABLED
   server.on("/log", HTTP_GET, []() {
@@ -46,19 +40,8 @@
     return true;
   } else {
     server.sendHeader("WWW-Authenticate", "Basic realm=\"Login Required\"");
-    server.send(401, "text/plain", "Login required\n");
+    server.send(401, "text/json", "{\"error\":\"Login required\"}\n");
     return false;
   }
 }

-void serverSendFile(const String& path, const String& ct) {
-  File file = SPIFFS.open(path, "r");
-  size_t s = file.size();
-  size_t sent = server.streamFile(file, ct);
-  if (s != sent) {
-    logValue("Sent less bytes: ", path);
-  }
-  file.close();
-}
-
-


apply changes in frequency and buffer limit to execution

--- ble_heart_rate_template.ino
+++ ble_heart_rate_template.ino
@@ -48,9 +48,13 @@

 const int analogInPin = I0;

+uint16_t connection_interval = 798;
+uint16_t slave_latency = 0;
+uint16_t sampling_rate = 1;
+
 int sensorValue = 200;
 int buffer_limit = 19;
-int sleep_time = 1000;
+unsigned long sleep_time = 1000000;

 void printData(aci_evt_t * aci_evt) {
 	int i = 0;
@@ -89,6 +93,17 @@
 	lib_aci_init(&aci_state);
 	heart_rate_init();
 	buffer_init();
+	Serial.println(F("----- Setup -----"));
+	Serial.print(F("Connection Interval: "));
+	Serial.println(connection_interval);
+	Serial.print(F("Slave Latency: "));
+	Serial.println(slave_latency);
+	Serial.print(F("Buffer Limit: "));
+	Serial.println(buffer_limit);
+	Serial.print(F("Sleeping Time : "));
+	Serial.println(sleep_time);
+	Serial.println(F("----------------"));
+
 }

 void aci_loop()
@@ -224,40 +239,62 @@
 				break;
 	 	    case ACI_EVT_DATA_RECEIVED:
 		        Serial.println(F("DATA RECEIVED"));
-		        Serial.print(F("Pipe #: 0x"));
-		        Serial.println(aci_evt->params.data_received.rx_data.pipe_number, HEX);
+		        // Serial.print(F("Pipe #: 0x"));
+		        // Serial.println(aci_evt->params.data_received.rx_data.pipe_number, HEX);

 				uint16_t value;
 		        switch(aci_evt->params.data_received.rx_data.pipe_number) {
 		        	case PIPE_CONNECTIONCONTROL_CONNECTIONINTERVAL_RX_ACK_AUTO:
-		        		Serial.println(F("CONNECTION_INTERVAL: "));
+		        		Serial.print(F("CONNECTION_INTERVAL: "));
 		        		// printData(aci_evt);

 		        		// Two bytes
  						// big-endian !!!!
 						value = aci_evt->params.data_received.rx_data.aci_data[1] + ((uint16_t)aci_evt->params.data_received.rx_data.aci_data[0] << 8);
-		        		Serial.print(F("Value: "));
+						connection_interval = value;
 		        		Serial.println(value);
 		        		break;
 		        	case PIPE_CONNECTIONCONTROL_SLAVELATENCY_RX_ACK_AUTO:
-		        		Serial.println(F("SLAVELATENCY: "));
+		        		Serial.print(F("SLAVELATENCY: "));
 		        		// printData(aci_evt);

 		        		// One byte
  						// big-endian !!!!
-						value = aci_evt->params.data_received.rx_data.aci_data[1];
-						Serial.print(F("Value: "));
+						value = aci_evt->params.data_received.rx_data.aci_data[0];
+						slave_latency = value;
 		        		Serial.println(value);
 		        		break;
 		        	case PIPE_CONNECTIONCONTROL_SAMPLINGRATE_RX_ACK_AUTO:
-		        		Serial.println(F("SAMPLING_RATE: "));
+		        		Serial.print(F("SAMPLING_RATE: "));
 		        		// printData(aci_evt);

 						// 4 Bytes
  						// big-endian !!!!
-						value = aci_evt->params.data_received.rx_data.aci_data[1] + ((uint16_t)aci_evt->params.data_received.rx_data.aci_data[0] << 8);
-		        		Serial.print(F("Value: "));
+ 						if(aci_evt->len - 2 > 1) {
+							value = aci_evt->params.data_received.rx_data.aci_data[1] + ((uint16_t)aci_evt->params.data_received.rx_data.aci_data[0] << 8);
+ 						} else {
+							value = aci_evt->params.data_received.rx_data.aci_data[0];
+ 						}
+						sampling_rate = value;
 		        		Serial.println(value);
+
+						Serial.print(F("SLEEPING_TIME: "));
+						sleep_time = ((1/ (double) sampling_rate) * 1000000);
+		        		Serial.println(sleep_time);
+		        		break;
+		        	case PIPE_CONNECTIONCONTROL_BUFFERLIMIT_RX_ACK_AUTO:
+						Serial.print(F("BUFFER_LIMIT: "));
+		        		// printData(aci_evt);
+
+						// 1 Byte
+ 						// big-endian !!!!
+						value = aci_evt->params.data_received.rx_data.aci_data[0];
+						if(value > 0) {
+							buffer_limit = value;
+		        			Serial.println(value);
+						} else {
+							Serial.println(F("<invalid>"));
+						}
 		        		break;
 		        	default:
 		        		printData(aci_evt);
@@ -394,13 +431,15 @@

 	if (isChannelOpen())
 	{
-		Serial.println("Channel open");
 		handleCommands();
 		if(checkTransmissionCriteria()) {
 			sendData();
 		}
 	}
-
-	delay(sleep_time);
-}
-
+	if(sleep_time < 16383) {
+		delayMicroseconds(sleep_time);
+	} else {
+		delay(sleep_time / 1000);
+	}
+}
+


Change set point to reference velocity. (#35)

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -74,8 +74,8 @@
 double samples_wl[NUM_VEL_SAMPLES];
 double samples_wr[NUM_VEL_SAMPLES];
 int samples_w_index = 0;
-double set_point_wl;
-double set_point_wr;
+double reference_wl;
+double reference_wr;
 float motor_controller_p = 5.0;

 // IMU and Magnetometer
@@ -226,8 +226,8 @@
   encoder_right_pos = 0.0;
   motor_left_speed = 0.0;
   motor_right_speed = 0.0;
-  set_point_wl = 0.0;
-  set_point_wr = 0.0;
+  reference_wl = 0.0;
+  reference_wr = 0.0;
   pose.x = 0.0;
   pose.y = 0.0;
   pose.theta = 0.0;
@@ -246,13 +246,13 @@
   // If no cmd_vel messages withing threshold time, something is wrong, stop the robot.
   cmd_vel_timeout_stop = (current_time.toSec() - last_cmd_vel_time.toSec()) > cmd_vel_timeout_threshold;
   if (cmd_vel_timeout_stop) {
-    setSetPoint(0, 0);
-  }
-}
-
-void setSetPoint(double new_set_point_wl, double new_set_point_wr) {
-  set_point_wl = new_set_point_wl;
-  set_point_wr = new_set_point_wr;
+    setReferenceVelocity(0, 0);
+  }
+}
+
+void setReferenceVelocity(double new_wl, double new_wr) {
+  reference_wl = new_wl;
+  reference_wr = new_wr;
 }

 /*
@@ -266,8 +266,8 @@
   double vl = cmd_vel_msg.linear.x - (cmd_vel_msg.angular.z * track_radius);
   double vr = cmd_vel_msg.linear.x + (cmd_vel_msg.angular.z * track_radius);

-  // Calculate wheel angular velocity
-  setSetPoint(vl / wheel_radius, vr / wheel_radius);
+  // Calculate and set  refrence wheel angular velocity
+  setReferenceVelocity(vl / wheel_radius, vr / wheel_radius);
 }

 void doMotorController() {
@@ -275,8 +275,8 @@
   double sensed_wl = getAngularVelocityFromSamples(samples_wl);
   double sensed_wr = getAngularVelocityFromSamples(samples_wr);

-  double wl = motor_controller_p * (set_point_wl - sensed_wl);
-  double wr = motor_controller_p * (set_point_wr - sensed_wr);
+  double wl = motor_controller_p * (reference_wl - sensed_wl);
+  double wr = motor_controller_p * (reference_wr - sensed_wr);

   // Calculate motor speed between -1 and 1
   double new_left_speed = max(-1, min(1, wl / max_speed));


Remove pH measurement functionality

Remove pH measurement functionality

The focus is not to have a lot of sensors at the moment. Building for
d1_mini got errors for eeprom so this is the perfect time to remove some
unused code. Later in the project I will re-add the functionality.

Signed-off-by: Robin Hagman <a0ad21b4a5c77bde0f74c8a70cf9b810eabd0434@gmail.com>

--- arduino_sketch/arduino_sketch.ino
+++ arduino_sketch/arduino_sketch.ino
@@ -1,11 +1,7 @@
-/*
- * Work in progress
- */
+#include <Arduino.h>
 #include <DHT.h>        // For the DHT11 temperature and humidity sensor
 #include <Time.h>       // For timekeeping
 #include <Wire.h>       // For I2C
-#include <avr/eeprom.h> // For storing calibration and configration in EEPROM
-

 //Define LED pins (PWM pins: 3,5,6,9,10,11 on arduino UNO)
 const int RED   = 11;
@@ -24,28 +20,6 @@
 #define DHTPIN 8         // what pin we're connected to
 #define DHTTYPE DHT11    // DHT 11
 DHT dht(DHTPIN, DHTTYPE);// make the object
-
-
-//----- pH probe code
-#define Write_Check      0x1234
-#define ADDRESS 0x4C // MCP3221 A5 in Dec 77 A0 = 72 A7 = 79)
-                     // A0 = x48, A1 = x49, A2 = x4A, A3 = x4B,
-                     // A4 = x4C, A5 = x4D, A6 = x4E, A7 = x4F
-// Our parameter, for ease of use and eeprom access lets use a struct
-struct parameters_T
-{
-  unsigned int WriteCheck;
-  int pH7Cal, pH4Cal;
-  float pHStep;
-}
-params;
-
-float pH;
-int adc_result;           // Used in function phProbe and case C for calibration of the probe
-const float vRef = 4.096; // Our vRef into the ADC wont be exact Since you can run VCC lower than Vref its best to measure and adjust here
-const float opampGain = 5.25; // What is our Op-Amps gain (stage 1)
-//----- End pH probe code
-

 /**
  * User schedule of all settings
@@ -99,7 +73,7 @@
 time_t tDelayMin = measureInterval;

 // Sensor data
-int sensorTempData[] = {0,0,0,0,0}; // temp, humid, light, ph, phTwoDecPlaces
+int sensorTempData[] = {0,0,0}; // temp, humid, light

 void setup() {
   Wire.begin();       // conects I2C
@@ -118,12 +92,6 @@
   pinMode(FAN, OUTPUT);
   pinMode(BOARDLED, OUTPUT);
   digitalWrite(BOARDLED, LOW);
-
-  // Read info from eeprom, contains calibration values from before. If this is the first run time, use default probe settings.
-  eeprom_read_block(&params, (void *)0, sizeof(params));
-  if (params.WriteCheck != Write_Check) {
-    reset_Params();
-  }
 }

 void loop() {
@@ -277,32 +245,6 @@
         }
         break;
       }
-      case 'P':
-      {
-        //Lets read in our parameters and spit out the info!
-         eeprom_read_block(&params, (void *)0, sizeof(params));
-         Serial.print("pH 7 cal: ");
-         Serial.print(params.pH7Cal);
-         Serial.print(" | ");
-         Serial.print("pH 4 cal: ");
-         Serial.print(params.pH4Cal);
-         Serial.print(" | ");
-         Serial.print("pH probe slope: ");
-         Serial.print(params.pHStep);
-         Serial.print(" | ");
-         Serial.print("pH: ");
-         Serial.println(pH);
-         break;
-      }
-      case 'C':
-      {
-        //Which range?
-        int calrange;
-        calrange = Serial.parseInt();
-        if( calrange == 4 ) calibratepH4(adc_result);
-        if( calrange == 7 ) calibratepH7(adc_result);
-        break;
-      }
     }
 }

@@ -340,8 +282,7 @@
   reportValues = reportValues + fanStatus;

   reportValues = timeReport() + "S" + sensorTempData[0] + "," + sensorTempData[1] + ","
-                                    + sensorTempData[2] + "," + sensorTempData[3] + ","
-                                    + sensorTempData[4] + reportValues;
+                                    + sensorTempData[2] + reportValues;
   Serial.println(reportValues);
 }

@@ -404,69 +345,7 @@
 {
   dhtSensor();
   lightSensor();
-  phProbe();
-}
-
-//----- pH functions
-void phProbe()
-{
-  //This is our I2C ADC interface section
-  //We'll assign 2 BYTES variables to capture the LSB and MSB(or Hi Low in this case)
-  byte adc_high;
-  byte adc_low;
-
-  Wire.requestFrom(ADDRESS, 2);        //requests 2 bytes
-  if(Wire.available())
-  {
-  while(Wire.available() < 2);         //while two bytes to receive
-  //Set em
-  adc_high = Wire.read();
-  adc_low = Wire.read();
-  //now assemble them, remembering our byte maths a Union works well here as well
-  adc_result = (adc_high * 256) + adc_low;
-  //We have a our Raw pH reading fresh from the ADC now lets figure out what the pH is
-  calcpH(adc_result);
-
-  sensorTempData[3] = (int) pH;
-  sensorTempData[4] = ((int) (pH*100) - sensorTempData[3]*100); // Calculate the two decimals
-  }
-}
-
-void calibratepH7(int calnum)
-{
-  params.pH7Cal = calnum;
-  calcpHSlope();
-  //write these settings back to eeprom
-  eeprom_write_block(&params, (void *)0, sizeof(params));
-}
-void calibratepH4(int calnum)
-{
-  params.pH4Cal = calnum;
-  calcpHSlope();
-  //write these settings back to eeprom
-  eeprom_write_block(&params, (void *)0, sizeof(params));
-}
-void calcpHSlope ()
-{
-  //RefVoltage * our deltaRawpH / 12bit steps *mV in V / OP-Amp gain /pH step difference 7-4
-  params.pHStep = ((((vRef*(float)(params.pH7Cal - params.pH4Cal))/4096)*1000)/opampGain)/3;
-}
-void calcpH(int raw)
-{
-  float miliVolts = (((float)raw/4096)*vRef)*1000;
-  float temp = ((((vRef*(float)params.pH7Cal)/4096)*1000)- miliVolts)/opampGain;
-  pH = 7-(temp/params.pHStep);
-}
-void reset_Params(void)
-{
-  //Restore to default set of parameters!
-  params.WriteCheck = Write_Check;
-  params.pH7Cal = 2048; //assume ideal probe and amp conditions 1/2 of 4096
-  params.pH4Cal = 1286; //using ideal probe slope we end up this many 12bit units away on the 4 scale
-  params.pHStep = 59.16;//ideal probe slope
-  eeprom_write_block(&params, (void *)0, sizeof(params)); //write these settings back to eeprom
-}
-//----- End pH functions
+}

 void lightSensor()
 {


implementando ciclo dinâmico das funções

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -21,8 +21,13 @@
 // SAÍDAS
 const byte geral = 23;                 // Saída Geral
 const byte dosador = 25;               // Saída do Dosador
-const byte datador = 27;               // Saída do Datador
+const byte led_datador = 27;               // Saída do Datador
 const byte mandibula = 40;
+const byte faca = 42;
+const byte refrigeracao = 44;
+const byte datador = 46;
+const byte soldas = 48;
+
 const byte solda_vertical_PWM = 33;        // Saída da Solda Vertical
 const byte solda_horizontal_PWM = 35;      // Saída da Solda Horizontal
 const byte solda_datador_PWM = 37;         // Saída da Solda do Datador
@@ -47,6 +52,9 @@
 #define NomeDosador "Dosador"
 #define NomeDatador "Datador"
 #define NomeMandibula "Mandibula"
+#define NomeFaca "Faca"
+#define NomeRefrigeracao "Refrigeracao"
+#define NomeSoldas "Soldas"
 #define NomeSoldaVertical "Solda Vertical"
 #define NomeSoldaHorizontal "Solda Horizontal"
 #define NomeSoldaDatador "Solda Datador"
@@ -83,7 +91,7 @@
 // TEMPOS DE CICLO
 // CONTROLE DE CICLO
 unsigned long tempo_atual = millis();
-unsigned long ciclo_padrao = 1500;
+unsigned long ciclo_padrao = 2000;
 unsigned long ciclo_padrao_anterior = ciclo_padrao;
 unsigned long inicio_ciclo = 0;
 unsigned long ciclo_minimo = 900;
@@ -111,11 +119,11 @@
 unsigned long fim_refrigeracao = 1450;

 // DATADOR
-unsigned long inicio_datador = 0;
+unsigned long inicio_datador = 1;
 unsigned long fim_datador = 400;

 // SOLDAS VERTICAL E HORIZONTAL
-unsigned long inicio_soldas = 0;
+unsigned long inicio_soldas = 1;
 unsigned long fim_soldas = 400;

 void setup() {
@@ -141,11 +149,16 @@

   // REMOVER
   pinMode(saida_teste, SAIDA);
+  pinMode(entrada_teste, SENSOR);

   pinMode(geral, SAIDA);
   pinMode(dosador, SAIDA);
+  pinMode(led_datador, SAIDA);
+  pinMode(faca, SAIDA);
+  pinMode(refrigeracao, SAIDA);
   pinMode(datador, SAIDA);
+  pinMode(soldas, SAIDA);

   // ESTADO INICIAL DAS SAÍDAS
   resetCompleto();
@@ -191,7 +204,11 @@
   }
   if (conta_ciclos >= 3) {
     funcaoSimples(mandibula, NomeMandibula, inicio_mandibula, fim_mandibula);
-    funcaoSimples(saida_teste, "Teste", 1500, 1501);
+    funcaoSimples(faca, NomeFaca, inicio_faca, fim_faca);
+    funcaoSimples(refrigeracao, NomeRefrigeracao, inicio_refrigeracao, fim_refrigeracao);
+    // funcaoSimples(datador, NomeDatador, inicio_datador, fim_datador);
+    // funcaoSimples(soldas, NomeSoldas, inicio_soldas, fim_soldas);
+    // funcaoSimples(saida_teste, "Teste", 1500, 1600);
   }
   funcaoReset();
 }
@@ -246,14 +263,15 @@
   }

   if (tempo_atual >= minimo) {
-    if (ativo(sensor_reset) || tempo_atual == maximo) {
+    if (ativo(sensor_reset) || inativo(entrada_teste) || tempo_atual == maximo) {
       conta_ciclos++;
-      escreveSerial((String)conta_ciclos + " " +
-                    (String)(tempo_atual - inicio_ciclo) + " " +
+      unsigned long ciclo_temp = inicio_ciclo;
+      soma_ciclos += (tempo_atual - inicio_ciclo);
+      reiniciaCiclo(tempo_atual);
+      escreveSerial("\t" + (String)conta_ciclos + " " +
+                    (String)(tempo_atual - ciclo_temp) + " " +
                     (String)ciclo_padrao + " " + (String)tempo_atual + " " +
                     (String)millis());
-      soma_ciclos += (tempo_atual - inicio_ciclo);
-      reiniciaCiclo(tempo_atual);
     }
   }
 }
@@ -270,21 +288,31 @@
   if (conta_ciclos > 0) {
     ciclo_padrao_anterior = ciclo_padrao;
     ciclo_padrao = soma_ciclos / conta_ciclos;
-    inicio_mandibula *= (long)((float)ciclo_padrao_anterior / (float)ciclo_padrao);
+    // AJUSTE DINÂMICO DOS TEMPOS DAS FUNÇÕES
+    inicio_mandibula = (inicio_mandibula * ciclo_padrao) / ciclo_padrao_anterior;
+    fim_mandibula = (fim_mandibula * ciclo_padrao) / ciclo_padrao_anterior;
+    inicio_faca = (inicio_faca * ciclo_padrao) / ciclo_padrao_anterior;
+    fim_faca = (fim_faca * ciclo_padrao) / ciclo_padrao_anterior;
+    inicio_refrigeracao = (inicio_refrigeracao * ciclo_padrao) / ciclo_padrao_anterior;
+    fim_refrigeracao = (fim_refrigeracao * ciclo_padrao) / ciclo_padrao_anterior;
+    inicio_datador = (inicio_datador * ciclo_padrao) / ciclo_padrao_anterior;
+    fim_datador = (fim_datador * ciclo_padrao) / ciclo_padrao_anterior;
+    inicio_soldas = (inicio_soldas * ciclo_padrao) / ciclo_padrao_anterior;
+    fim_soldas = (fim_soldas * ciclo_padrao) / ciclo_padrao_anterior;
   }
 }

 void geraPWM(byte pot, unsigned long *inicio, byte saida) {
-  unsigned long ativo = map(analogRead(pot), 0, 1023, 0, ciclo_PWM);
+  unsigned long ativo = *inicio + map(analogRead(pot), 0, 1023, 0, ciclo_PWM);
   unsigned long inativo = ciclo_PWM - ativo;
+  unsigned long pwm = *inicio + ciclo_PWM;
   if (maquina_ligada && !alarme_ativo) {
-    if (millis() > *inicio && millis() <= (*inicio + ativo)) {
+    if (tempo_atual > *inicio && tempo_atual <= ativo) {
       liga(saida);
-    } else if (millis() > (*inicio + ativo) &&
-               millis() < (*inicio + ciclo_PWM)) {
+    } else if (tempo_atual > ativo && tempo_atual < pwm) {
       desliga(saida);
-    } else if (millis() >= (*inicio + ciclo_PWM)) {
-      *inicio = millis();
+    } else if (tempo_atual >= pwm) {
+      *inicio = tempo_atual;
     }
   } else {
     desliga(saida);
@@ -296,8 +324,10 @@
 void funcaoSimples(const byte saida, String nome, unsigned long inicio, unsigned long fim) {
   inicio += inicio_ciclo;
   fim += inicio_ciclo;
-  if ((tempo_atual >= inicio) && (tempo_atual < fim) && desligado(saida)) {
-    ligaFuncao(saida, nome);
+  if (desligado(saida)){
+    if (tempo_atual >= inicio && tempo_atual < fim) {
+      ligaFuncao(saida, nome);
+    }
   } else if (tempo_atual >= fim) {
     desligaFuncao(saida, nome);
   }
@@ -313,7 +343,7 @@
   if (desligado(saida)) {
     liga(saida);
     if (ligado(saida)){
-      escreveSerial(nome + " Ligado.");
+      escreveSerial(">> " + nome + " Ligado.");
     } else {
       escreveSerial("Ocorreu um erro ao ligar " + nome);
     }
@@ -322,10 +352,10 @@

 void desliga(byte saida) { digitalWrite(saida, DESLIGA); }

-void desligaFuncao(byte saida, String texto) {
+void desligaFuncao(byte saida, String nome) {
   if (ligado(saida)) {
     desliga(saida);
-    escreveSerial(texto + " Desligado.");
+    escreveSerial("<< " + nome + " Desligado.");
   }
 }

@@ -387,8 +417,12 @@

 void reiniciaSaidas() {
   desligaFuncao(dosador, NomeDosador);
+  desligaFuncao(led_datador, NomeDatador);
+  desligaFuncao(mandibula, NomeMandibula);
+  desligaFuncao(faca, NomeFaca);
+  desligaFuncao(refrigeracao, NomeRefrigeracao);
   desligaFuncao(datador, NomeDatador);
-  desligaFuncao(mandibula, NomeMandibula);
+  desligaFuncao(soldas, NomeSoldas);
 }

 void resetCompleto() {
@@ -397,8 +431,12 @@
   conta_ciclos = 0;
   desliga(geral);
   desliga(dosador);
+  desliga(led_datador);
+  desliga(mandibula);
+  desliga(faca);
+  desliga(refrigeracao);
   desliga(datador);
-  desliga(mandibula);
+  desliga(soldas);

   desliga(solda_vertical_PWM);
   desliga(solda_horizontal_PWM);
@@ -417,7 +455,7 @@
     desligaFuncao(dosador, NomeDosador);
   }
   if (datador_ligado) {
-    ligaFuncao(datador, NomeDatador);
+    ligaFuncao(led_datador, NomeDatador);
   } else {
     desligaFuncao(datador, NomeDatador);
   }


[Arduino] Remove obsolete detection code

--- arduino/temphum/temphum.ino
+++ arduino/temphum/temphum.ino
@@ -39,12 +39,6 @@

 //When application asked if this is the correct arduino
 void serialCheck() {
-  if (readString == usb_name) {
-    Serial.print("OK");
-    serial_check = true;
-    delay(1000);
-  }
-
   if (readString == "/info") {
     Serial.println(usb_name);
     serial_check = true;


Improve SPI clock configuration.

Improve SPI clock configuration.

--- build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
+++ build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
@@ -38,14 +38,16 @@

 #define PROG_FLICKER true

-// Configure SPI clock.
-//   E.g. for an attiny @128 kHz:
-//   (pulseWidth should be > 2 cpu cycles, so take 3 cycles:)
-//   #define SPI_CLOCK            (128000/3)
-//
-//   A clock slow enough for an attiny85 @ 1MHz, is a reasonable default:
-
-#define SPI_CLOCK 		(1000000/3)
+// Configure SPI clock (in Hz).
+// E.g. for an attiny @128 kHz: the datasheet states that both the high
+// and low spi clock pulse must be > 2 cpu cycles, so take 3 cycles i.e.
+// divide target f_cpu by 6:
+//     #define SPI_CLOCK            (128000/6)
+//
+// A clock slow enough for an attiny85 @ 1MHz, is a reasonable default:
+
+#define SPI_CLOCK 		(1000000/6)
+

 // Select hardware or software SPI, depending on SPI clock.
 // Currently only for AVR, for other archs (Due, Zero,...),
@@ -161,7 +163,7 @@
   }

   void beginTransaction(SPISettings settings) {
-    pulseWidth = 1000 / (settings.clock / 1000);
+    pulseWidth = (500000 + settings.clock - 1) / settings.clock;
     if (pulseWidth == 0)
       pulseWidth = 1;
   }


Cleaning code

Cleaning code

Delete static network configuration

--- ArduinoFirmwareEsp/WBServer.ino
+++ ArduinoFirmwareEsp/WBServer.ino
@@ -265,8 +265,7 @@
    WiFi.hostname(HOSTNAME);

-   WiFi.begin("DHLabs", "dhlabsrfid01");
-//   WiFi.begin(getNetworkConfig("ssid").c_str(), getNetworkConfig("password").c_str() );
+   WiFi.begin(getNetworkConfig("ssid").c_str(), getNetworkConfig("password").c_str() );

     server.serveStatic("/fs", SPIFFS, "/");


Turn off the motor pins after stepping to save power & heat.

--- WhereDial.ino
+++ WhereDial.ino
@@ -20,7 +20,8 @@
 #include "WhereDial_Local.h"

 const int stepsPerRevolution = 2048;
-Stepper myStepper(stepsPerRevolution, A2,A5,A3,A4);
+int motorPins[] = {A2,A5,A3,A4};
+Stepper myStepper(stepsPerRevolution, motorPins[0],motorPins[1],motorPins[2],motorPins[3]);

 byte mac[] = WHEREDIAL_LOCAL_MAC;
 char *userAgent = "WhereDial/1.0";
@@ -365,5 +366,10 @@
   }
   /* OK - TURN DOWN LED  05 */
   digitalWrite(errorLeds[0],LOW);
-}
-
+
+  /* TURN OFF THE MOTOR PINS, SAVE POWER & HEAT */
+  for (int i = 0; i < 4; ++i) {
+    digitalWrite(motorPins[i],LOW);
+  }
+}
+


Changin #defines to const char *

Changin #defines to const char *


extract basic instruction set command to its own function to be self explanatory

--- Nokia_5110/Nokia_5110.ino
+++ Nokia_5110/Nokia_5110.ino
@@ -41,6 +41,10 @@
     execute(0x21);
 }

+void basicInstruction(){
+    execute(0x20);
+}
+
 void setup() {
     pinMode(RST, OUTPUT);
     pinMode(CE, OUTPUT);
@@ -57,7 +61,8 @@
     extendedInstruction();
     execute(0x04); // set temp coefficent
     execute(0x14); // LCD bias mode 1:40
-    execute(0x20); // LCD basic commands
+
+    basicInstruction();
     execute(0x09); // LCD all segments on
 }


Last version of ino script.

Last version of ino script.

--- skypointer.ino
+++ skypointer.ino
@@ -3,8 +3,8 @@
 --------------------------
 [ ] When target is negative rotation is along the long path
 [ ] Rethink the calculation of speed for Timer1 interrupts
-[ ] Function for turning laser on
-[ ] Feedback to the server with rotated distance for alignment
+[X] Function for turning laser on
+[X] Feedback to the server with rotated distance for alignment
 [X] Implement rotation direction in ISR_rotate
 [X] Calculate relative movement in the GOTO processor, equals target - currPos
 [X] Function for remapping currPos to [0, 3200] in microstep() function
@@ -116,7 +116,7 @@
   motor1 -> setTarget(tgt1);
   motor2 -> setTarget(tgt2);

-  Serial.print("OK\r\n");
+  Serial.print("OK\r");
   Timer1.attachInterrupt(ISR_rotate);  // Enable TimerOne interrupt
 }

@@ -154,6 +154,12 @@
 }

+// Get ID
+void ProcessID() {
+  Serial.print("SkyPointer 1.0\r");
+}
+
+
 // Handles unknown commands
 void Unrecognized() {
   Serial.print("NK\r");
@@ -172,6 +178,7 @@
   sCmd.addCommand("S", ProcessStop);    // S\r
   sCmd.addCommand("P", ProcessGetPos);  // P\r
   sCmd.addCommand("L", ProcessLaser);   // L enable\r
+  sCmd.addCommand("I", ProcessID);      // I\r
   sCmd.addDefaultHandler(Unrecognized);	// Unknown commands

   // Configure interrupt speed (microseconds)
@@ -181,8 +188,6 @@
   MS.begin();
   motor1->setSpeed(RPM);
   motor2->setSpeed(RPM);
-
-  Serial.print("Waiting for commands...");
 }


typo...

typo...

--- arduino/ws2812_controller_esp32/ws2812_controller_esp32.ino
+++ arduino/ws2812_controller_esp32/ws2812_controller_esp32.ino
@@ -1,7 +1,7 @@
 /*
 * This example works for ESP32 and uses the NeoPixelBus library instead of the one bundle
 * Sketch Written by Joey Babcock - https://joeybabcock.me/blog/
-* Codebase cretaed by ScottLawsonBC - https://github.com/scottlawsonbc
+* Codebase created by ScottLawsonBC - https://github.com/scottlawsonbc
 */

 #include <Arduino.h>


updated serial output

updated serial output

--- jenny5-firmware/jenny5-firmware.ino
+++ jenny5-firmware/jenny5-firmware.ino
@@ -22,7 +22,7 @@

 char is_command_running;

-char firmware_version[] = "2015.12.26.0";// year.month.day.build number
+char firmware_version[] = "2015.12.26.1";// year.month.day.build number

 char current_buffer[65];

@@ -40,18 +40,18 @@
   Serial.println();

   Serial.println(F("Commands are:"));
-  Serial.println(F("Mx y# // Moves motor x with y steps. If y is negative the motor runs in the opposite direction. The motor remains locked at the end of the movement."));
+  Serial.println(F("Mx y# // Moves motor x with y steps. If y is negative the motor runs in the opposite direction. The motor remains locked at the end of the movement. Outputs Mx# when motor rotation is over."));
   Serial.println(F("Dx#  // Disables motor x."));
   Serial.println(F("Lx#  // Lock motor x."));
   Serial.println(F("SMx s a# // Sets speed of motor x to s and the acceleration to a."));
   Serial.println(F("SPx min max home# // Sets the parameters of a potentiometer. Min and Max are the limits where it can move and home is from where we start."));
   Serial.println(F("Ax n Py Bz ... # // Attach to motor x a list of n sensors (like Potentiometer y, Button z etc)."));
-  Serial.println(F("Ux# // Gets the distance as measured by the ultrasonic sensor x."));
-  Serial.println(F("Bx# // Gets the status of the button x."));
-  Serial.println(F("Px# // Gets the position of the potentiometer x."));
-  Serial.println(F("Ix# // Gets the value of infrared sensor x."));
-  Serial.println(F("GMx# // Gets the parameters for motor x: speed acceleration num_sensors sensor index1, sensor type1 sensor index1, sensor type1"));
-  Serial.println(F("GPx# // Gets the parameters for potentiometer x: min max home"));
+  Serial.println(F("Ux# // Gets the distance as measured by the ultrasonic sensor x. Outputs Ux d#."));
+  Serial.println(F("Bx# // Gets the status of the button x. Outputs Bx s#"));
+  Serial.println(F("Px# // Gets the position of the potentiometer x. Outputs Px p#"));
+  Serial.println(F("Ix# // Gets the value of infrared sensor x. Outputs Ix v#"));
+  Serial.println(F("GMx# // Gets the parameters for motor x: speed acceleration num_sensors sensor_index1, sensor_type1 sensor_index1, sensor_type1. Outputs MPx s a 1 0 0#"));
+  Serial.println(F("GPx# // Gets the parameters for potentiometer x: min max home. Outputs Px l u h#"));

   Serial.println(F("Motor index is between 0 and num_motors - 1"));
@@ -127,6 +127,8 @@
             int sensor_index;
             sscanf(tmp_str + i + 1, "%d", &sensor_index);
             Serial.write('U');
+            Serial.print(sensor_index);
+            Serial.write(' ');
             Serial.print(ultrasonic_sensors_controller.getDistanceForSensor(sensor_index));
             Serial.write('#');
             i++;
@@ -137,6 +139,8 @@
             int sensor_index;
             sscanf(tmp_str + i + 1, "%d", &sensor_index);
             Serial.write('P');
+            Serial.print(sensor_index);
+            Serial.write(' ');
             Serial.print(potentiometers_control.get_position(sensor_index));
             Serial.write('#');
             i++;
@@ -146,13 +150,15 @@
             int sensor_index;
             sscanf(tmp_str + i + 1, "%d", &sensor_index);
             Serial.write('I');
+            Serial.print(sensor_index);
+            Serial.write(' ');
             Serial.print(infrared_sensors_control.get_distance(sensor_index));
             Serial.write('#');
             i++;
           }
         else
           if (tmp_str[i] == 'G' || tmp_str[i] == 'g'){// for debugging purpose
-                        if (tmp_str[i + 1] == 'M' || tmp_str[i + 1] == 'm'){ // get motor speed and acceleration
+            if (tmp_str[i + 1] == 'M' || tmp_str[i + 1] == 'm'){ // get motor speed and acceleration
               int motor_index, motor_speed, motor_acceleration;
               sscanf(tmp_str + i + 2, "%d", &motor_index);
               motors_control.get_motor_speed_and_acceleration(motor_index, &motor_speed, &motor_acceleration);
@@ -162,24 +168,23 @@
               Serial.print(motor_speed);
               Serial.write(' ');
               Serial.print(motor_acceleration);
-                        }
-                        else
-                        if (tmp_str[i + 1] == 'P' || tmp_str[i + 1] == 'p'){ // get potentiometer min max home
+            }
+            else
+              if (tmp_str[i + 1] == 'P' || tmp_str[i + 1] == 'p'){ // get potentiometer min max home
                 int pot_index, pot_min, pot_max, pot_home;
                 sscanf(tmp_str + i + 2, "%d", &pot_index);
                 potentiometers_control.get_limits(pot_index, &pot_min, &pot_max, &pot_home);
-                              Serial.write("PP"); // potentiometer parameters
-              Serial.print(pot_index);
-              Serial.write(' ');
-              Serial.print(pot_min);
-              Serial.write(' ');
-              Serial.print(pot_max);
-              Serial.write(' ');
-              Serial.print(pot_home);
-              Serial.write('#');
-                        }
-                        else
-                        {
+                Serial.write("PP"); // potentiometer parameters
+                Serial.print(pot_index);
+                Serial.write(' ');
+                Serial.print(pot_min);
+                Serial.write(' ');
+                Serial.print(pot_max);
+                Serial.write(' ');
+                Serial.print(pot_home);
+                Serial.write('#');
+              }
+              else{
                           // for all motors, unformated data
             int index;
             for(index = 0; index < motors_control.num_motors; index++) {


Delete 7_Codice_Dataphys_Pneuma.ino

Delete 7_Codice_Dataphys_Pneuma.ino

--- 3_dataphys/7_Codice_Dataphys_Pneuma.ino
+++ 3_dataphys/7_Codice_Dataphys_Pneuma.ino
@@ -1,71 +0,0 @@
-///// ------ ARDUINO ------///////
-/*
-The MIT License (MIT)
- Copyright (c) 2015 Federico Lo Porto for the course ID2-2015 @ UnirSM
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE.
-
- Lo sketch fa muovere il pistone dell'installazione Pneuma.
- E' collegato a processing da cui riceve i valori.
-
-
-*/
-
-
-#include <Servo.h>
-Servo myservo1;
-char tastiera = 0;
-int incomingByte;
-float tempo;
-
-void setup() {
-  myservo1.attach (3);
-  Serial.begin(9600);
-}
-
-void loop() {
- // if (Serial.available() > 0) {
-    incomingByte = Serial.read();
-Serial.print(incomingByte);
-if(incomingByte=='A')
-{
-  tempo=500;
-}
-if(incomingByte=='B')
-{
-  tempo=1000;
-}
-if(incomingByte=='C')
-{
-  tempo=2500;
-}
-if(incomingByte=='D')
-{
-  tempo=2000;
-}
-
-      myservo1.writeMicroseconds (1500);   //dietro
-      delay(tempo);
-
-      myservo1.writeMicroseconds (1480);   //fermo
-      delay(tempo/2);
-
-      myservo1.writeMicroseconds (1460);   //dietro
-      delay(tempo);
-
-      myservo1.writeMicroseconds (1480);   //fermo
-      delay(tempo/2);
-    }


1 parte logica

1 parte logica

--- TesteMotor/TesteMotor.ino
+++ TesteMotor/TesteMotor.ino
@@ -40,15 +40,21 @@

 void loop() {
   if(!carrinho->livreAFrente() && !carrinho->livreAEsquerda()) {
-
+    carrinho->parar();
+    carrinho->direita();
+    carrinho->parar();
   }
   else if(!carrinho->livreAFrente() && carrinho->livreAEsquerda()) {
-
+    carrinho->parar();
+    carrinho->esquerda();
+    carrinho->parar();
   }
   else if(carrinho->livreAFrente() && !carrinho->livreAEsquerda()) {
-
+    carrinho->andar();
   }
   else if(carrinho->livreAFrente() && carrinho->livreAEsquerda()) {
-
+    carrinho->parar();
+    carrinho->esquerda();
+    carrinho->andar();
   }
 }


Added new servo params + GPG test

Added new servo params + GPG test

--- firmware/servo_ctl.ino
+++ firmware/servo_ctl.ino
@@ -8,8 +8,12 @@

 #define RUDDER_MIN 50
 #define RUDDER_MAX 125
-#define WINCH_MIN 60
-#define WINCH_MAX 110
+
+// absolute max: 155
+// absolute min: 20
+
+#define WINCH_MIN 80
+#define WINCH_MAX 117

 // degrees per second
 #define RUDDER_SPEED 300.0
@@ -35,7 +39,7 @@
 }

 void centerWinch() {
-    winchTo(115);
+    winchTo(WINCH_MAX);
 }

 void centerRudder() {


fixed displays after round ends

fixed displays after round ends

fixed play button increment after round is over

--- MorraGame/MorraGame.ino
+++ MorraGame/MorraGame.ino
@@ -23,10 +23,11 @@

 // result of round
 String strRoundResult = "";
+String strWinner = "";

 // keep track of button changes
 int oldBtnStateHand, oldBtnStateGuess, oldBtnStatePlay;
-int displayState = 0;                     // state of display (Stage: 0, 1 Results: 2, 3, 4, 5, 6)
+int displayState = 0;                     // state of display (Stage: 0, 1 Results: 2, 3, 4, 5, 6, 7)
 int roundsToPlay = 1;                     // number of rounds to play this game
 int roundsPlayed = 0;                     // number of rounds played so far
 int winsNeeded = 1;                       // number of round wins needed to win game
@@ -49,26 +50,37 @@
   int btnStateGuess = digitalRead(btnGuess);
   int btnStatePlay = digitalRead(btnPlay);

-  if (btnStatePlay != oldBtnStatePlay && displayState == 6) {
-    resetScore();
+  if (btnStatePlay != oldBtnStatePlay && displayState == 7) {
+    // game is over, so reset
+	resetScore();
     showRoundsToPlay();
     displayState = 0;
   }
+  else if (btnStatePlay != oldBtnStatePlay && displayState == 6) {
+    // wait for next play button press after showing game winner
+	displayState = 7;
+  }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 5) {
-    updateLCD();
-    displayState = 1;
+    // show game winner and wait for next play button press
+	showHeaderNoScore();
+    mySerial.print(strWinner);
+    displayState = 6;
   }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 4) {
-    displayGameWinner();
+    // determine if the game is over and wait for next play button press
+	displayState = getGameWinner();
   }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 3) {
-    displayResultOfRound();
+    // show round results and wait for next play button press
+	displayResultOfRound();
     displayState = 4;
   }
   else if (btnStatePlay != oldBtnStatePlay && displayState == 2) {
+	// wait for next play button press after showing round stats
     displayState = 3;
   }
   else if (displayState == 1) {
+	// handle hand, guess, and play buttons during a round
     if (btnStateHand == HIGH && btnStateHand != oldBtnStateHand) {
       nextHand();
       updateLCD();
@@ -82,6 +94,7 @@
     }
   }
   else if (displayState == 0) {
+	// determine rounds to play
     if (btnStateHand == HIGH && btnStateHand != oldBtnStateHand && roundsToPlay > 1) {
       roundsToPlay -= 2;
       showRoundsToPlay();
@@ -97,6 +110,8 @@
     }
   }

+  // update button states
+
   if (btnStateHand != oldBtnStateHand) {
     oldBtnStateHand = btnStateHand;
   }
@@ -108,6 +123,8 @@
   if (btnStatePlay != oldBtnStatePlay) {
     oldBtnStatePlay = btnStatePlay;
   }
+
+  delay(100);
 }

 // increment player hand
@@ -172,6 +189,7 @@
     }
   }

+  // increment rounds played and display stats
   roundsPlayed++;
   displayRoundStats(compHand, compGuess);
 }
@@ -224,22 +242,20 @@
 }

 // check if the game is over
-void displayGameWinner() {
-  int tempState = 6;   // assume winner
+int getGameWinner() {
+  int tempState = 5;   // assume winner

   if (playerScore == winsNeeded) {
-    showHeaderNoScore();
-    mySerial.print("Player Won " + String(playerScore) + "-" + String(compScore));
+    strWinner = "Player Won " + String(playerScore) + "-" + String(compScore);
   }
   else if (compScore == winsNeeded) {
-    showHeaderNoScore();
-    mySerial.print("CPU won " + String(compScore) + "-" + String(playerScore));
+    strWinner = "CPU won " + String(compScore) + "-" + String(playerScore);
   }
   else {
-    tempState = 5;    // no winner
-  }
-
-  displayState = tempState;
+    tempState = 0;    // no winner
+  }
+
+  return tempState;
 }

 // display header with score
@@ -266,4 +282,3 @@
   playerScore = 0;
   compScore = 0;
 }
-


Added volume control and stop buttons to web interface

Fixed webinterface with esp8266 2.4.2

--- RfidShelf/RfidShelf.ino
+++ RfidShelf/RfidShelf.ino
@@ -38,7 +38,7 @@
 MFRC522::MIFARE_Key key;

 #define MAJOR_VERSION 1
-#define MINOR_VERSION 1
+#define MINOR_VERSION 3

 // Init array that will store new card uid
 byte lastCardUid[4];
@@ -46,6 +46,7 @@
 bool playingByCard = true;
 bool pairing = false;
 String currentFile = "";
+uint8_t volume = 10;

 SdFat SD;
 SdFile uploadFile;
@@ -129,7 +130,7 @@
   Serial.print(F("SampleRate "));
   Serial.println(musicPlayer.sciRead(VS1053_REG_AUDATA));

-  musicPlayer.setVolume(10, 10);
+  musicPlayer.setVolume(volume, volume);

   musicPlayer.dumpRegs();

@@ -145,7 +146,6 @@
   Serial.print("Connected! IP address: ");
   Serial.println(WiFi.localIP());

-  server.on("/stopMp3", HTTP_GET, handleStopMp3);
   server.on("/", HTTP_POST, handleNotFound, handleFileUpload);
   server.onNotFound(handleNotFound);

@@ -414,6 +414,22 @@
   }
 }

+void volumeUp() {
+  volume -= 5;
+  if(volume < 0) {
+    volume = 0;
+  }
+  musicPlayer.setVolume(volume, volume);
+}
+
+void volumeDown() {
+  volume += 5;
+  if(volume > 50) {
+    volume = 50;
+  }
+  musicPlayer.setVolume(volume, volume);
+}
+
 bool isMP3File(String &filename) {
   return filename.endsWith(".mp3");
 }
@@ -442,14 +458,18 @@
       "var formData = new FormData(); for(var i = 0; i < fileInput.files.length; i++) { formData.append('data', fileInput.files[i], folder.concat(fileInput.files[i].name)); }; xhr.open('POST', '/'); xhr.send(formData); }"
       "function writeRfid(url){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { location.reload(); }}; xhr.open('POST', url); var formData = new FormData(); formData.append('write', 1); xhr.send(formData);}"
       "function play(url){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { location.reload(); }}; xhr.open('POST', url); var formData = new FormData(); formData.append('play', 1); xhr.send(formData);}"
+      "function rootAction(action){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { location.reload(); }}; xhr.open('POST', '/'); var formData = new FormData(); formData.append(action, 1); xhr.send(formData);}"
       "function mkdir() { var folder = document.getElementById('folder'); if(folder != ''){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { location.reload(); }}; xhr.open('POST', '/'); var formData = new FormData(); formData.append('newFolder', folder.value); xhr.send(formData);}}"
-      "function ota() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { document.write('Please wait and do NOT turn of the power!'); location.reload(); }}; xhr.open('POST', '/'); var formData = new FormData(); formData.append('ota', 1); xhr.send(formData);}"
+      "function ota() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { document.write('Please wait and do NOT turn off the power!'); location.reload(); }}; xhr.open('POST', '/'); var formData = new FormData(); formData.append('ota', 1); xhr.send(formData);}"
       "</script><link rel=\"icon\" href=\"data:;base64,iVBORw0KGgo=\">"));

   String output;
   if (path == "/") {
-    output = F("
Currently playing: {currentFile}
<form><input type=\"text\" name=\"folder\" id=\"folder\"><input type=\"button\" value=\"mkdir\" onclick=\"mkdir(); return false;\"></form>");
+    output = F("
Currently playing: {currentFile} (■)
"
+      "
Volume: {volume} + / -
"
+      "<form><input type=\"text\" name=\"folder\" id=\"folder\"><input type=\"button\" value=\"mkdir\" onclick=\"mkdir(); return false;\"></form>");
     output.replace("{currentFile}", currentFile);
+    output.replace("{volume}", String(50-volume));
     output.replace("{folder}", path);
     server.sendContent(output);
   } else {
@@ -514,7 +534,6 @@
     server.sendContent(output);
   }
   server.sendContent(F(""));
-  server.client().stop();
 }

 bool loadFromSdCard(String &path) {
@@ -552,11 +571,6 @@
   } else {
     returnHttpStatus((uint8_t)404, "Not found");
   }
-}
-
-void handleStopMp3() {
-  stopMp3();
-  returnOK();
 }

 void handleFileUpload() {
@@ -642,7 +656,7 @@
       switch (ret) {
         case HTTP_UPDATE_FAILED:
           Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
-          returnHttpStatus(200, "Update failed, please try again");
+          returnHttpStatus((uint8_t)500, "Update failed, please try again");
           return;
         case HTTP_UPDATE_NO_UPDATES:
           Serial.println(F("HTTP_UPDATE_NO_UPDATES"));
@@ -652,6 +666,18 @@
           Serial.println(F("HTTP_UPDATE_OK"));
           break;
       }
+      returnOK();
+      return;
+    } else if (server.hasArg("stop")) {
+      stopMp3();
+      returnOK();
+      return;
+    } else if (server.hasArg("volumeUp")) {
+      volumeUp();
+      returnOK();
+      return;
+    } else if (server.hasArg("volumeDown")) {
+      volumeDown();
       returnOK();
       return;
     } else if (server.uri() == "/") {


abandoning DS18B20 library

abandoning DS18B20 library

--- cmdMULTIsens/src/sketch.ino
+++ cmdMULTIsens/src/sketch.ino
@@ -6,7 +6,8 @@
 #include <VBAT.h>
 #include <TMP36.h>
 #include <DHT.h>
-#include <DS18B20.h>
+#include <OneWire.h>
+//#include <DS18B20.h>

 // An LED is connected to pin 3
 #define ActivityLED 3
@@ -41,10 +42,13 @@
 TMP36 tmp36(Tmp36Pin, Tmp36Samples, 5.06);

 // Initialise DS18B20 library: measurement pin, number of samples to average
-DS18B20 ds1w(DS18Pin, DS18Samples);
+//DS18B20 ds1w(DS18Pin, DS18Samples);
+OneWire ds1w(DS18Pin);

 float h;  // used for calculating dewpoint
 float t;  // used for calculating dewpoint
+byte ds1w_addr[8];
+byte ds1w_data[12];

 void setup()
 {
@@ -55,7 +59,10 @@
   tmp36.begin();                    // Initialise TMP36 sensor
   vbat.begin();                     // Initialise VBAT sensor
   dht.begin();                      // Initialise DHT22 sensor
-  ds1w.begin();                     // Initialise DS18B20/1-wire sensor
+  if ( !ds1w.search(ds1w_addr))
+  {
+    Serial.println("No sensor.");
+  }
   delay(2000);                      // Wait 2s for all sensors to come online
   Serial.println("cmdMULTIsens ready !");   // Print banner
   digitalWrite(ActivityLED, LOW);   // Turn off the LED at end of setup()
@@ -64,6 +71,73 @@
 int serialRX()
 {
   return Serial.read();             // read a byte from the serialbuffer
+}
+
+float readDSTemperature(void)
+{
+  int cntSamples = 0;
+  int sumSamples = 0;
+  float measurement = 0.0;
+  int i = 0;
+  int type_s = 0;
+
+  ds1w.reset();
+  ds1w.select(ds1w_addr);
+  ds1w.write(0x44, 1);        // start conversion, with parasite power on at the end
+
+  delay(1000);     // maybe 750ms is enough, maybe not
+  byte present = ds1w.reset();
+  ds1w.select(ds1w_addr);
+  ds1w.write(0xBE);         // Read Scratchpad
+
+  //Serial.print("  Data = ");
+  //Serial.print(present, HEX);
+  //Serial.print(" ");
+  for ( i = 0; i < 9; i++) {           // we need 9 bytes
+    ds1w_data[i] = ds1w.read();
+    //Serial.print(ds1w_data[i], HEX);
+    //Serial.print(" ");
+  }
+  //Serial.print(" CRC=");
+  //Serial.print(OneWire::crc8(ds1w_data, 8), HEX);
+  //Serial.println();
+
+  // Convert the data to actual temperature
+  // because the result is a 16 bit signed integer, it should
+  // be stored to an "int16_t" type, which is always 16 bits
+  // even when compiled on a 32 bit processor.
+  int16_t raw = (ds1w_data[1] << 8) | ds1w_data[0];
+  if (type_s) {
+    raw = raw << 3; // 9 bit resolution default
+    if (ds1w_data[7] == 0x10) {
+      // "count remain" gives full 12 bit resolution
+      raw = (raw & 0xFFF0) + 12 - ds1w_data[6];
+    }
+  } else {
+    byte cfg = (ds1w_data[4] & 0x60);
+    // at lower res, the low bits are undefined, so let's zero them
+    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
+    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
+    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
+    //// default is 12 bit resolution, 750 ms conversion time
+  }
+  float celsius = (float)raw / 16.0;
+  //Serial.print("  Temperature = ");
+  //Serial.print(celsius);
+  //Serial.println(" Celsius, ");
+
+  // add up the pre-defined number of _samples for Sample Averaging
+  for (cntSamples = 0; cntSamples < _samples; cntSamples++)
+  {
+    //sumSamples += analogRead(_pin);
+    // minimum delay on analog pins is 100ms
+    delay(110);
+  }
+  //measurement = (float)sumSamples * _invsamples; // Calculate avg raw value.
+  //measurement = map(measurement * 10, 0, 10230, 0, _ref5v * 10000) * 0.0001;
+  //measurement *= _r12;
+  //return measurement;
+  return celsius;
 }

 void loop()
@@ -131,7 +205,7 @@
           Serial.print(Value);
           Serial.print(", ");
           // DS18B20 temperature
-          Value = ds1w.readTemperature();
+          Value = readDSTemperature();
           Serial.print(Value);
           Serial.print(", ");
         }
@@ -179,7 +253,7 @@
       case 'W':
       case 'w':
         // DS18B20 temperature
-        Value = ds1w.readTemperature();
+        Value = readDSTemperature();
         Serial.print(Value);
         break;
       default:


fixed a missing index increment with G command

--- jenny5-firmware/jenny5-firmware.ino
+++ jenny5-firmware/jenny5-firmware.ino
@@ -22,7 +22,7 @@

 char is_command_running;

-char firmware_version[] = "2016.01.16.0";// year.month.day.build number
+char firmware_version[] = "2016.01.17.0";// year.month.day.build number

 char current_buffer[65];

@@ -84,7 +84,7 @@
         motors_control.move_motor(motor_index, num_steps);
         motors_control.set_motor_running(motor_index, 1);
         is_command_running = 1;
-        i += 3;
+        i += 4;
       }
       else
           if (tmp_str[i] == 'P' || tmp_str[i] == 'p'){// potentiometer
@@ -95,7 +95,7 @@
             Serial.write(' ');
             Serial.print(potentiometers_control.get_position(sensor_index));
             Serial.write('#');
-            i++;
+            i += 2;
           }
         else
           if (tmp_str[i] == 'U' || tmp_str[i] == 'u'){// ultrasonic
@@ -106,7 +106,7 @@
             Serial.write(' ');
             Serial.print(ultrasonic_sensors_controller.getDistanceForSensor(sensor_index));
             Serial.write('#');
-            i++;
+            i += 2;
           }
         else
           if (tmp_str[i] == 'I' || tmp_str[i] == 'i'){// infrared
@@ -117,7 +117,7 @@
             Serial.write(' ');
             Serial.print(infrared_sensors_control.get_distance(sensor_index));
             Serial.write('#');
-            i++;
+            i += 2;
           }
         else
         if (tmp_str[i] == 'D' || tmp_str[i] == 'd'){// disables motor
@@ -127,7 +127,7 @@
           Serial.write("D");
           Serial.print(motor_index);
           Serial.write('#');
-          i++;
+          i += 2;
         }
         else
           if (tmp_str[i] == 'L' || tmp_str[i] == 'l'){// locks motor
@@ -137,7 +137,7 @@
             Serial.write("L");
             Serial.print(motor_index);
             Serial.write('#');
-            i++;
+            i += 2;
           }
         else
           if (tmp_str[i] == 'H' || tmp_str[i] == 'h'){// go home
@@ -167,16 +167,18 @@
             sscanf(tmp_str + i + 1, "%d%d", &motor_index, &num_sensors);
             motors_control.set_num_attached_sensors(motor_index, num_sensors);
             // now I have to add sensors one by one
-            int j = i + 3;
+            int j = i + 4;
+            i += 4;
             while (j < str_length){
               if (tmp_str[j] == 'P' || tmp_str[j] == 'p'){
                 int sensor_index;
                 sscanf(tmp_str + j + 1, "%d", &sensor_index);
                 motors_control.add_sensor(motor_index, POTENTIOMETER, sensor_index);
+                i += 2;
               }
               j++;
             }
-            i += 3;
+            i++;
           }
         else
           if (tmp_str[i] == 'G' || tmp_str[i] == 'g'){// for debugging purpose
@@ -190,6 +192,7 @@
               Serial.print(motor_speed);
               Serial.write(' ');
               Serial.print(motor_acceleration);
+              i += 4;
             }
             else
               if (tmp_str[i + 1] == 'P' || tmp_str[i + 1] == 'p'){ // get potentiometer min max home
@@ -205,6 +208,7 @@
                 Serial.write(' ');
                 Serial.print(pot_home);
                 Serial.write('#');
+                i += 4;
               }
               else{
                           // for all motors, unformated data
@@ -228,7 +232,7 @@
                     }
                 }
                 Serial.write("#");
-                i++;
+                i += 2;
               }
         }
         else


Changing display update condition

Changing display update condition

--- thermostat.ino
+++ thermostat.ino
@@ -355,8 +355,7 @@
 void renderUI() {
   static uint32_t lastUpdate = 0;
   uint32_t t = millis();
-  //if (updateDisplay || t - lastUpdate > 5000L) {
-  if (t - lastUpdate > 5000L) {
+  if (updateDisplay || t - lastUpdate > 5000L) {
     debugln("UPDATE");
     display.clearDisplay(); // start new buffer
     // text display tests
@@ -365,9 +364,9 @@
     int tempInt = (int)temp;
     int tempDec = (int) (temp * 10) - tempInt * 10;
     draw_temp(temp, tempInt, tempDec);
-
+
     draw_desired_temp(desiredTemperature);
-
+
     #if defined(ESP8266)
     drawWifiIcon();
     #endif


Improved serial interface. Mysteriously large error rate, though.

--- src/receiver/receiver.ino
+++ src/receiver/receiver.ino
@@ -21,19 +21,15 @@
 #define CSN_PIN                 8 // Radio chip select pin
 #define INT_PIN                 2 // Radio interrupt pin

-// Serial protocol
-#define MAX_SERIAL_LINE_LEN     20 // Null terminator is already accounted for
-
 // Firmware information
 #define ENDPOINT_ID_LOCATION    0x000 // The address in EEPROM to store the ID

 void initRadio(void);
 uint8_t detectClearestChannel(void);
-// void networkRead(void);
 void radioInterrupt(void);
 void serialRead(void);
-void processSerialCommand(char message[]);
+void processSerialCommand(String message);
 void setRGB(uint8_t red, uint8_t green, uint8_t blue);
 void setEndpointID(uint8_t id);
 void printWelcomeMessage(void);
@@ -51,6 +47,7 @@

     // Initialize serial console
     Serial.begin(115200);
+    Serial.setTimeout(-1);
     printWelcomeMessage();

     // Start the radio
@@ -106,20 +103,10 @@
  */
 void serialRead(void) {

-    static char buffer[MAX_SERIAL_LINE_LEN + 1];
-    static int index = 0;
-
-    if (Serial.available()) {
-
-        buffer[index] = Serial.read();
-
-        if (buffer[index] == '\r' ||  index == MAX_SERIAL_LINE_LEN) {
-            buffer[index] = '\0'; // Terminate the message
-            index = 0; // Reset to the beginning of the buffer
-            processSerialCommand(buffer);
-        } else {
-            index++;
-        }
+    String message = Serial.readStringUntil('\r');
+    if (!message.equals("")) {
+        processSerialCommand(message);
+        Serial.read(); // Clear out the line terminator
     }
 }

@@ -127,22 +114,23 @@
  * Takes action on a command received over serial.
  * @param message The message received
  */
-void processSerialCommand(char message[]) {
+void processSerialCommand(String message) {

     uint8_t id, r, g, b;
-    if (!strcmp(message, "help")) {
+    if (message.equals("help")) {
         printHelpMessage();
-    } else if (!strcmp(message, "getid")) {
+    } else if (message.equals("getid")) {
         Serial.println(endpointID);
         Serial.println(F("OK"));
-    } else if (sscanf(message, "setid %hhu", &id) == 1) {
+    } else if (sscanf(message.c_str(), "setid %hhu", &id) == 1) {
         setEndpointID(id);
         Serial.println(F("OK"));
-    } else if (sscanf(message, "setrgb %hhu %hhu %hhu", &r, &g, &b) == 3) {
+    } else if (sscanf(message.c_str(), "setrgb %hhu %hhu %hhu", &r, &g, &b) == 3) {
         setRGB(r, g, b);
         Serial.println(F("OK"));
     } else {
-        Serial.println(F("Error: unrecognized command or invalid arguments"));
+        Serial.print(F("Error: unrecognized command or invalid arguments: "));
+        Serial.println(message);
     }
 }

@@ -179,6 +167,7 @@
  * Prints the welcome message for the serial console.
  */
 void printWelcomeMessage(void) {
+    Serial.println();
     Serial.println(F("-----------------------------------------"));
     Serial.println(F("ACM@UIUC SIGMusic Lights Serial Interface"));
     Serial.print(F("This light is endpoint "));


changes made to launcher arduino code

changes made to launcher arduino code

--- src/pong_launcher/arduino_code/launcher_arduino/launcher_arduino.ino
+++ src/pong_launcher/arduino_code/launcher_arduino/launcher_arduino.ino
@@ -132,7 +132,7 @@
 ros::NodeHandle  nh;

 std_msgs::String state_msg;
-ros::Publisher pub_state("launcher/state", &state_msg);
+ros::Publisher pub_state("/launcher/state", &state_msg);

 // Takes the current state from the interrupt service routine and
 //  decides on the next commute state
@@ -348,7 +348,7 @@
 	pub_state.publish(&str);
 }

-ros::Subscriber<geometry_msgs::Vector3> motor_sub("launcher/motor_vel/", motor_controls_cb);
+ros::Subscriber<geometry_msgs::Vector3> motor_sub("/launcher/motor_vel", motor_controls_cb);

 void pid_controls_cb(const geometry_msgs::Vector3& pid_msg){

@@ -368,7 +368,7 @@
 	pub_state.publish(&str);
 }

-ros::Subscriber<geometry_msgs::Vector3> pid_sub("launcher/pid_val/", pid_controls_cb);
+ros::Subscriber<geometry_msgs::Vector3> pid_sub("/launcher/pid_val", pid_controls_cb);

 void setup(){
 	//Pinmodes for the motor's PWM


Added Heltec WiFi-Kit-8

Added Heltec WiFi-Kit-8

--- usermods/Wemos_D1_mini+Wemos32_mini_shield/wled06_usermod.ino
+++ usermods/Wemos_D1_mini+Wemos32_mini_shield/wled06_usermod.ino
@@ -14,7 +14,7 @@
 //ESP8266 Wemos D1 mini board use SCL=5 SDA=4 while ESP32 Wemos32 mini board use SCL=22 SDA=21
 #define U8X8_PIN_SCL SCL_PIN
 #define U8X8_PIN_SDA SDA_PIN
-
+//#define U8X8_PIN_RESET RST_PIN // Uncoment for Heltec WiFi-Kit-8
 // Dallas sensor
 DallasTemperature sensor(&oneWire);
 long temptimer = millis();
@@ -30,6 +30,8 @@
 U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA
 // --> Second choise of cheap I2C OLED 128X64 0.96" or 1.3"
 //U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA
+// --> Third choise of Heltec WiFi-Kit-8 OLED 128X32 0.91"
+//U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_RESET, U8X8_PIN_SCL, U8X8_PIN_SDA); // Constracor for Heltec WiFi-Kit-8
 // gets called once at boot. Do all initialization that doesn't depend on
 // network here
 void userSetup() {


move led cmds back to android

move led cmds back to android

--- glass/glass.ino
+++ glass/glass.ino
@@ -82,19 +82,8 @@
       if (XBeeReturnCount > 0) {  //has respondant(s)
         XBeeReturnIDs[XBeeReturnCount*3-1] = '\0';

-        if(XBeeReturnCount > 1) {
-          //get the first ID and ask to blink fast
-          //can pass XBeeReturnIDs since it will only use the first 2 chars
-          sendXBeePacketFromRaw(XBeeReturnIDs, "S", "SEL", "1st");
-        } else {
-          sendXBeePacketFromRaw(XBeeReturnIDs, "C", "SEL", "AON");
-          //auto on means only 1 client responded and is auto selected
-          //" ON" means selected manully among multiple targets by the user
-        }
-
       } else {  //no respondants
         XBeeReturnIDs[0] = '\0';
-        sendXBeePacketFromRaw(XBeeReturnIDs, "S", "SEL", " NA");
       }

       DEBUG_PRINT("IDs list:");
@@ -189,28 +178,3 @@
   return i;
 }

-int sendXBeePacketFromRaw (
-         const char *id,
-         const char *func,
-         const char *var,
-         const char *data) {
-  char str[20];
-  str[0] = '\0';
-  string_concat(str, id, 0);
-  string_concat(str, func, 2);
-  string_concat(str, var, 3);
-  string_concat(str, data, 6);
-  str[9] = '\0';
-  DEBUG_PRINT("(in sendXBeePacketFromRaw) packet being sent: ");
-  DEBUG_PRINTLN(str);
-  XBee.println(str);
-  return 1;
-}
-
-// to guarantee, dst should be longer than end-start+1
-void string_concat(char *dst, const char *src, int pos) {
-  int i = 0;
-  while (src[i] != '\0') {
-    dst[i+pos] = src[i++];
-  }
-}


MultiSerialMega example is now bi-directional

--- build/shared/examples/4.Communication/MultiSerialMega/MultiSerialMega.ino
+++ build/shared/examples/4.Communication/MultiSerialMega/MultiSerialMega.ino
@@ -11,7 +11,8 @@
  * Serial monitor open on Serial port 0:

  created 30 Dec. 2008
- by Tom Igoe
+ modified 20 May 2012
+ by Tom Igoe & Jed Roach

  This example code is in the public domain.

@@ -30,4 +31,10 @@
     int inByte = Serial1.read();
     Serial.write(inByte);
   }
+
+  // read from port 0, send to port 1:
+  if (Serial.available()) {
+    int inByte = Serial.read();
+    Serial1.write(inByte);
+  }
 }


Update BB-UNIT.ino

Update BB-UNIT.ino

--- Firmware/BB-UNIT/BB-UNIT.ino
+++ Firmware/BB-UNIT/BB-UNIT.ino
@@ -1,5 +1,7 @@
-String version = "0.3.1"; // Software Version
-int channel    = 1;       // Remote channel : Put the same of your remote
+String FIRMWARE_VERSION = "0.3.3"; // Software Version
+int channel             = 1;       // Remote channel : Put the same of your remote
+
+
 /*
   - OPEN BB-X -
  A open source BB-8 for create you own BB-8!
@@ -14,6 +16,11 @@
  --------------
  - Change log -
  --------------
+ 12/2016
+ =========
+ - Cleaning variable name
+ - Add RF433Mhz command for the Head and the controller
+ - Add choise the channel

  11/2016
  =========
@@ -42,6 +49,9 @@
   ===============
   EXEMPLE COMMAND
   ===============
+
+  // IT IS MANDATORY TO ADD 'c<YOUR CHANNEL>' for use commands. //
+
   < 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
@@ -55,19 +65,19 @@
 	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
+  'BOOT c1\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
+  'RUN c1\n'   // RUN the code in production mode (Recieved all data, X and Y runing for the SETPOINT poistion and Z folow the remote controll

   < STOP >
-  'STOP \n'  // STOP the production mode. All motors are stopped.
+  'STOP c1\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
+  'ROTATE d1 s100 c1\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
+  'STAT c1\n' // It is all data SENDED to the remote

   < ENABLE >
   'ENABLE a1 x1 z1 \n'    // ENABLE MOTOR AB, XY and Z (a = AB, x=XY, z = Z | 0 = desabled | 1 = enabled )
@@ -88,9 +98,9 @@
 //#include <RF24.h>

-//===================//
-// NOW YOU CAN TOUCH //
-//===================//
+//===============//
+// YOU CAN TOUCH //
+//===============//

 // HC-12
 bool ifHead = false; // True if the head are wireless connected
@@ -102,10 +112,18 @@
 //RF24 radio(54, 55);

 // MPU6050
-MPU6050 accelgyro;
+MPU6050 accelgyroIC1(0x68); // HEAD
+MPU6050 accelgyroIC2(0x69); // BODY
+
+//MPU6050 accelgyro;

 int16_t ax, ay, az;
 int16_t gx, gy, gz;
+
+
+int16_t axb, ayb, azb;
+int16_t gxb, gyb, gzb;
+

 // MOTOR CONFIGURATION // YOU CAN TOUCH THIS

@@ -122,6 +140,8 @@

 int     ETALON_X       = 0;     // AJUSTEMENT FOR X
 int     ETALON_Y       = -6;    // AJUSTEMENT FOR Y
+int     ETALON_B_X     = 0;     // AJUSTEMENT FOR X
+int     ETALON_B_Y     = -6;    // AJUSTEMENT FOR Y

 int     HYSTERESIS     = 1;     // HYSTERESSIS FOR THE ANGLE CALCULATION

@@ -131,89 +151,102 @@

 //PINOUT

-#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
-#define pinDirB          8      // PIN DIRECTION FOR X
-
-#define pinStepX         9      // PIN STEP FOR X
-#define pinDirX          10      // PIN DIRECTION FOR X
-
-#define pinStepY         11      // PIN STEP FOR Y
-#define pinDirY          12      // PIN DIRECTION FOR Y
-
-#define pinStepZ         14      // PIN STEP FOR Y
-#define pinDirZ          15      // PIN DIRECTION FOR Y
-
-#define Z_POSITION       16      // PIN FOR THE DIGITAL INPUT FOR THE HEAD POSITION
+#define PIN_ENABLE_A     33      // Activation off all stepper
+#define PIN_ENABLE_B     27      // Activation off all stepper
+
+#define PIN_STEP_A       31      // PIN STEP FOR X
+#define PIN_DIR_A        29      // PIN DIRECTION FOR X
+
+#define PIN_STEP_B       25      // PIN STEP FOR X
+#define PIN_DIR_B        23      // PIN DIRECTION FOR X
+
+#define pinStepX         26      // PIN STEP FOR X
+#define pinDirX          24      // PIN DIRECTION FOR X
+
+#define pinStepY         4       // PIN STEP FOR Y
+#define pinDirY          3       // PIN DIRECTION FOR Y
+
+#define pinStepZ         8       // PIN STEP FOR Y
+#define pinDirZ          9       // PIN DIRECTION FOR Y
+#define Z_POSITION       35      // PIN FOR THE DIGITAL INPUT FOR THE HEAD POSITION
+
+
+#define TRIGGER_LIGHT    36      // PIN TRIGGER FOR START/STOP THE LIGHTING INSIDE THE BALL
+#define LIGHTING         37      // PIN FOR FEED THE LIGHTING
+
+#define SWITCH_1         34      // TRIGGER NOT USED FOR THE MOMENT
+
+#define LED_1            48      // LED 1
+#define LED_2            44      // LED 2
+#define LED_3            40      // LED 3
+#define LED_4            46      // LED 4
+#define LED_5            42      // LED 5
+

 #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
-#define CurrentBat3      2
-#define CurrentBat4      3
-#define Pinvoltage       6
+
+#define CURRENT          0
+#define VOLTAGE          6

 // I2C
-int adress         = 2;
+int I2C_ADRESS         = 1;

 // MOTOR VARIABLE
-int speedA         = 0;
-int speedB         = 0;
-bool runA          = false;
-bool runB          = false;
-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 speedX         = 0;
-int speedY         = 0;
-int speedZ         = 0;
-int setpointX      = 90;
-int setpointY      = 90;
-
-int Zangle         = 0;
-bool newData       = false;
-
-int multiplier     = 15;
-int emergencyStop  = 11; // PIN
-int eStop          = 12; // PIN
-bool emgStop       = false;
-
-bool runX          = false;
-bool runY          = false;
-bool runZ          = false;
-bool directX       = false; // false = Gauche / true = droite
-bool directY       = false; // false = Gauche / true = droite
-bool directZ       = false; // false = Gauche / true = droite
-
-bool xok           = false;
-bool yok           = false;
-bool zok           = false;
-
-long intX          = 0;
-long intY          = 0;
-
-bool production    = false;
-bool LED_PING      = false;
-bool BOOT          = false;
-
-bool enMotAB       = false;
-bool enMotXY       = false;
-bool enMotZ        = false;
+int SPEED_A            = 0;
+int SPEED_B            = 0;
+bool RUN_A             = false;
+bool RUN_B             = false;
+bool DIRECTION_A       = true;   // true = Front | false = back
+bool DIRECTION_B       = true;   // true = Front | false = back
+
+int x                  = 0;
+int y                  = 0;
+int bx                 = 0;
+int by                 = 0;
+int vx                 = 0;
+int vy                 = 0;
+
+int speedX             = 0;
+int speedY             = 0;
+int speedZ             = 0;
+int setpointX          = 90;
+int setpointY          = 90;
+
+int Zangle             = 0;
+bool newData           = false;
+
+int multiplier         = 15;
+int emergencyStop      = 11; // PIN
+int eStop              = 12; // PIN
+bool emgStop           = false;
+
+int TMP_DATA[30]      ;
+
+bool runX              = false;
+bool runY              = false;
+bool runZ              = false;
+bool directX           = false; // false = Gauche / true = droite
+bool directY           = false; // false = Gauche / true = droite
+bool directZ           = false; // false = Gauche / true = droite
+
+bool xok               = false;
+bool yok               = false;
+bool zok               = false;
+
+long intX              = 0;
+long intY              = 0;
+
+bool production        = false;
+bool LED_PING          = false;
+bool BOOT              = false;
+
+bool enMotAB           = false;
+bool enMotXY           = false;
+bool enMotZ            = false;
+
+

 unsigned long previousMillisX = 0;
 unsigned long previousMillisY = 0;
@@ -235,22 +268,27 @@
 void setup()
 {
 	// PINMODE
-	pinMode( PIN_ENABLE_AB , OUTPUT );
-	pinMode( PIN_ENABLE_XY , OUTPUT );
-	pinMode( PIN_ENABLE_Z  , OUTPUT );
+	pinMode( PIN_ENABLE_A  , OUTPUT );
+	pinMode( PIN_ENABLE_B  , OUTPUT );
 	pinMode( pinDirX       , OUTPUT );
 	pinMode( pinStepX      , OUTPUT );
 	pinMode( pinDirY       , OUTPUT );
 	pinMode( pinStepY      , OUTPUT );
-	pinMode( pinDirA       , OUTPUT );
+	pinMode( PIN_DIR_A     , OUTPUT );
 	pinMode( PIN_STEP_A    , OUTPUT );
-	pinMode( pinDirB       , OUTPUT );
-	pinMode( pinStepB      , OUTPUT );
-	pinMode( PING          , OUTPUT );
-	pinMode( LIGHT         , OUTPUT );
+	pinMode( PIN_DIR_B     , OUTPUT );
+	pinMode( PIN_STEP_B    , OUTPUT );
+	pinMode( LIGHTING      , OUTPUT );
+	pinMode( LED_1         , OUTPUT );
+	pinMode( LED_2         , OUTPUT );
+	pinMode( LED_3         , OUTPUT );
+	pinMode( LED_4         , OUTPUT );
+	pinMode( LED_5         , OUTPUT );

 	pinMode( Z_POSITION    , INPUT  );
-
+	pinMode( TRIGGER_LIGHT , INPUT  );
+	pinMode( SWITCH_1      , INPUT  );
+
 	// SERIAL
 	Serial.begin(9600);

@@ -262,11 +300,19 @@
 	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.println("                                                  ");
+	Serial.println("           > Code by Daniel Mostosi <             ");
+	Serial.println("                                                  ");
+	Serial.println("                Report an issues?                 ");
+	Serial.println("    https://github.com/Gruniek/BB-UNIT/issues     ");
+	Serial.println("                                                  ");
 	Serial.print("           FIRMWARE VERSION : ");
-	Serial.print(version);
+	Serial.print(FIRMWARE_VERSION);
 	Serial.println("               ");
 	Serial.println("==================================================");

@@ -275,14 +321,21 @@

 	// Start of the I2C protocol
 	Serial.print("[2]-Initializing I2C devices...  I2C ADRESS :");
-	Serial.println(adress);
-	Wire.begin(adress);
+	Serial.println(I2C_ADRESS);
+	Wire.begin(I2C_ADRESS);

 	// Start the MPU6050 Gyroscope
-	Serial.print("[3]-Connect to the MPU6050 : ");
-	accelgyro.initialize();
+	Serial.print("[3]-Connect to the MPU6050 HEAD: ");
+	//accelgyro.initialize();
+	accelgyroIC1.initialize();
+	Serial.println(accelgyroIC1.testConnection() ? "Connection successful" : "Connection failed");
+
+	Serial.print("[4]-Connect to the MPU6050 BODY: ");
+    accelgyroIC2.initialize();
+   	Serial.println(accelgyroIC2.testConnection() ? "Connection successful" : "Connection failed");
+
 	//Serial.println(accelgyro.testConnection());
-	Serial.println(accelgyro.testConnection() ? "Connection successful" : "Connection failed");
+	//Serial.println(accelgyro.testConnection() ? "Connection successful" : "Connection failed");

 	// Start the RF24 Radio controll
 	//Serial.println("[4]-Initializing RF24 devices...  ");
@@ -291,19 +344,19 @@
 	//radio.startListening();

 	// Start remote connexion
-	Serial.println("[4]-Initializing HC-12 devices [REMOTE] ");
+	Serial.println("[5]-Initializing HC-12 devices [REMOTE] ");
 	controler.begin(9600);

 	// Start remote connexion
 	if(ifHead)
 	{
-		Serial.println("[5]-Initializing HC-12 devices [ HEAD ] ");
+		Serial.println("[6]-Initializing HC-12 devices [ HEAD ] ");
 		head.begin(9600);
 	}
 	// END OF BOOT/SETUP
-	Serial.println("====================");
-	Serial.println("Booting successful !");
-	Serial.println("====================");
+	Serial.println("=====================");
+	Serial.println("Booting successfull !");
+	Serial.println("=====================");
 }

 //=============================================================================//
@@ -317,9 +370,10 @@
 	{
 		trigG = currentG;

-		// GET MOTION
+		// GET MOTION HEAD
 		//-------------------------------------------------------------------------//
-		accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
+		//accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
+		accelgyroIC1.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
 		if(INVERT_XY)
 		{
 			y = (((ax / 180) + ETALON_X) + 90);
@@ -329,6 +383,22 @@
 		{
 			x = (((ax / 180) + ETALON_X) + 90);
 			y = (((ay / 180) + ETALON_Y) + 90);
+		}
+
+
+		// GET MOTION BODY
+		//-------------------------------------------------------------------------//
+		//accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
+		accelgyroIC2.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
+		if(INVERT_XY)
+		{
+			by = (((axb / 180) + ETALON_B_X) + 90);
+			bx = (((ayb / 180) + ETALON_B_Y) + 90);
+		}
+		else
+		{
+			bx = (((axb / 180) + ETALON_B_X) + 90);
+			by = (((ayb / 180) + ETALON_B_Y) + 90);
 		}
 	}

@@ -349,6 +419,13 @@
 		newData = true;
 	}

+	if (head.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);
@@ -365,54 +442,136 @@
 				switch (*p)
 				{
 					case 'x':
-						setpointX  = val;
+						TMP_DATA[1]  = val; // setpointX #1
 						break;
 					case 'y':
-						setpointY  = val;
+						TMP_DATA[2]  = val; // setpointY #2
 						break;
 					case 'm':
-						multiplier = val;
+						TMP_DATA[3] = val; // multiplier #3
 						break;
 					case 'i':
-						INVERT_XY   = val;
+						TMP_DATA[4]  = val; // INVERT_XY #4
 						break;
 					case 'j':
-						INVERT_X    = val;
+						TMP_DATA[5]   = val; // INVERT_X #5
 						break;
 					case 'k':
-						INVERT_Y    = val;
+						TMP_DATA[6]   = val; // INVERT_Y #6
 						break;
 					case 'h':
-						HYSTERESIS = val;
+						TMP_DATA[7] = val; // HYSTERESIS #7
+						break;
+					case 'c':
+						TMP_DATA[0] = val;
 						break;
 				}
 			}
+
+			if(TMP_DATA[0] == channel )
+			{
+				setpointX  = TMP_DATA[1];
+				setpointY  = TMP_DATA[2];
+				multiplier = TMP_DATA[3];
+				INVERT_XY  = TMP_DATA[4];
+				INVERT_X   = TMP_DATA[5];
+				INVERT_Y   = TMP_DATA[6];
+				HYSTERESIS = TMP_DATA[7];
+			}
+
 		}

 		if (strcmp(strtok(msg, " "), "RUN") == 0)
 		{
-			Serial.println("ROll BB-8 ROLL !");
-			production = true;
+			char *p;
+			while ((p = strtok(NULL, " ")) != NULL)
+			{
+				int val = atoi(p + 1);
+				switch (*p)
+				{
+					case 'c':
+						TMP_DATA[0]  = val;
+						break;
+				}
+			}
+
+			if(TMP_DATA[0] == channel )
+			{
+				Serial.println("ROll BB-8 ROLL !");
+				production = true;
+				TMP_DATA[0] = 0;
+			}
 		}

 		if (strcmp(strtok(msg, " "), "STOP") == 0)
 		{
-			Serial.println("STOP");
-			production = false;
+			char *p;
+			while ((p = strtok(NULL, " ")) != NULL)
+			{
+				int val = atoi(p + 1);
+				switch (*p)
+				{
+					case 'c':
+						TMP_DATA[0]  = val;
+						break;
+				}
+			}
+
+			if(TMP_DATA[0] == channel )
+			{
+				Serial.println("STOP");
+				production = false;
+				TMP_DATA[0] = 0;
+			}
+
 		}

 		if (strcmp(strtok(msg, " "), "RESET") == 0)
 		{
-			Serial.println("RESET");
-			production = false;
-			emgStop    = false;
+			char *p;
+			while ((p = strtok(NULL, " ")) != NULL)
+			{
+				int val = atoi(p + 1);
+				switch (*p)
+				{
+					case 'c':
+						TMP_DATA[0]  = val;
+						break;
+				}
+			}
+
+			if(TMP_DATA[0] == channel )
+			{
+				Serial.println("RESET");
+				production = false;
+				emgStop    = false;
+				TMP_DATA[0] = 0;
+			}
+
 		}

 		if (strcmp(strtok(msg, " "), "BOOT") == 0)
 		{
-			BOOT = true;
-			Serial.println("BOOTING UP...");
-			delay(2000);
+			char *p;
+			while ((p = strtok(NULL, " ")) != NULL)
+			{
+				int val = atoi(p + 1);
+				switch (*p)
+				{
+					case 'c':
+						TMP_DATA[0]  = val;
+						break;
+				}
+			}
+
+			if(TMP_DATA[0] == channel )
+			{
+				BOOT = true;
+				Serial.println("BOOTING UP...");
+				TMP_DATA[0] = 0;
+				delay(2000);
+			}
+
 		}

 		if (strcmp(strtok(msg, " "), "ROTATE") == 0) // ROTATE d1 s100  <-- Rotate Z right, 18c/sec
@@ -425,12 +584,22 @@
 				switch (*p)
 				{
 					case 'd':
-						directZ  = val;
+						TMP_DATA[8]  = val; // directZ #8
 						break;
 					case 's':
-						speedZ   = val;
+						TMP_DATA[9]   = val; // speedZ #9
+						break;
+					case 'c':
+						TMP_DATA[0]   = val; // channel #0
 						break;
 				}
+			}
+
+			if(TMP_DATA[0] == channel )
+			{
+				directZ = TMP_DATA[8];
+				speedZ  = TMP_DATA[9];
+				TMP_DATA[0] = 0;
 			}
 		}

@@ -445,18 +614,30 @@
 				switch (*p)
 				{
 					case 'a':
-						speedA  = val;
+						TMP_DATA[10] = val; // SPEED_A #10
 						break;
 					case 'b':
-						speedB  = val;
+						TMP_DATA[11] = val; // SPEED_B #11
+						break;
+					case 'e':
+						TMP_DATA[12] = val; // DIRECTION_A #12
+						break;
+					case 'd':
+						TMP_DATA[13] = val; // DIRECTION_B #13
 						break;
 					case 'c':
-						dirA    = val;
-						break;
-					case 'd':
-						dirB    = val;
+						TMP_DATA[0]   = val; // channel #0
 						break;
 				}
+			}
+
+			if(TMP_DATA[0] == channel )
+			{
+				SPEED_A     = TMP_DATA[10];
+				SPEED_B     = TMP_DATA[11];
+				DIRECTION_A = TMP_DATA[12];
+				DIRECTION_B = TMP_DATA[13];
+				TMP_DATA[0] = 0;
 			}
 		}

@@ -471,23 +652,33 @@
 				switch (*p)
 				{
 					case 'a':
-						enMotAB  = val;
+						TMP_DATA[14]  = val; // enMotAB #14
 						break;
 					case 'x':
-						enMotXY  = val;
+						TMP_DATA[15]  = val; // enMotXY #15
 						break;
 					case 'z':
-						enMotZ   = val;
+						TMP_DATA[16]   = val; // enMotZ #16
+						break;
+					case 'c':
+						TMP_DATA[0]   = val; // channel #0
 						break;
 				}
 			}
-		}
-
+
+			if(TMP_DATA[0] == channel )
+			{
+				enMotAB     = TMP_DATA[14];
+				enMotXY     = TMP_DATA[15];
+				enMotZ      = TMP_DATA[16];
+				TMP_DATA[0] = 0;
+			}
+		}
 	}

-	digitalWrite( PIN_ENABLE_AB, enMotAB );
-	digitalWrite( PIN_ENABLE_XY, enMotXY );
-	digitalWrite( PIN_ENABLE_Z,  enMotZ  );
+	digitalWrite( PIN_ENABLE_A, enMotAB );
+	digitalWrite( PIN_ENABLE_B, enMotXY );
+

 	if(BOOT)
 	{
@@ -600,25 +791,25 @@
 		// MOTOR A (Left)

 		// Run the motor
-		if(speedA > 0) runA = true;
-		else runA = false;
-		speedA = 1000 / speedA;
+		if(SPEED_A > 0) RUN_A = true;
+		else RUN_A = false;
+		SPEED_A = 1000 / SPEED_A;

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

 		// Send Step inpultion to the motor
 		unsigned long currentA = millis(); // millis();
-		if (currentA - previousMillisA >= speedA)
+		if (currentA - previousMillisA >= SPEED_A)
 		{
 			previousMillisA = currentA;

-			if(runA)
+			if(RUN_A)
 			{
 				digitalWrite(PIN_STEP_A, 1);
 				delayMicroseconds( 500 );
@@ -640,29 +831,29 @@
 		// MOTOR B (Right)

 		// Run the motor
-		if(speedB > 0) runB = true;
-		else runB = false;
-		speedB = 1000 / speedB;
+		if(SPEED_B > 0) RUN_B = true;
+		else RUN_B = false;
+		SPEED_B = 1000 / SPEED_B;

 		// Motor direction / With inversion
 		if(INVERT_B)
 		{
-			if(dirB) dirB = false;
-			else dirB = true;
-		}
-		digitalWrite(pinDirB, dirB); // Set the direction
+			if(DIRECTION_B) DIRECTION_B = false;
+			else DIRECTION_B = true;
+		}
+		digitalWrite(PIN_DIR_B, DIRECTION_B); // Set the direction

 		// Send Step inpultion to the motor
 		unsigned long currentB = millis(); // millis();
-		if (currentB - previousMillisB >= speedB)
+		if (currentB - previousMillisB >= SPEED_B)
 		{
 			previousMillisB = currentB;

-			if(runB)
-			{
-				digitalWrite(pinStepB, 1);
+			if(RUN_B)
+			{
+				digitalWrite(PIN_STEP_B, 1);
 				delayMicroseconds( 500 );
-				digitalWrite(pinStepB, 0);
+				digitalWrite(PIN_STEP_B, 0);
 				delayMicroseconds( 500 );
 			}
 		}
@@ -824,12 +1015,15 @@
 		digitalWrite(PING, LED_PING);

 		// IF THE MPU6050 ARE ALWAYS CONNECTED, IF NOT, HE RECONNECT AUTOMATICLY
-		if(!accelgyro.testConnection());
+		//if(!accelgyro.testConnection());
+		if(!accelgyroIC1.testConnection());
 		{
 			production = false;
 			emgStop = true;
-			accelgyro.initialize();
-			if(accelgyro.testConnection())
+			//accelgyro.initialize();
+			accelgyroIC1.initialize();
+			//if(accelgyro.testConnection())
+			if(accelgyroIC1.testConnection())
 			{
 				production = true;
 			}


disable watchdog while set()

disable watchdog while set()

--- esp8266_160528_MPL115A2.ino
+++ esp8266_160528_MPL115A2.ino
@@ -3,6 +3,8 @@
 #include "esp8266_160602_udpTxToLogger.h"

 /*
+ * v0.6 2016 Jun. 25
+ *   - disable watchdog while setup()
  * v0.5 2016 Jun. 2
  *   - send to udpLogger
  * v0.4 2016 Jun. 2
@@ -32,6 +34,8 @@
 static int s_count = 0;

 void setup() {
+  wdt_disable();
+
   Serial.begin(115200);
   Serial.println("");

@@ -42,6 +46,8 @@
   // UDP
   WiFi_setup();
   WiFi_printConnectionInfo();
+
+  wdt_enable(WDTO_8S);
 }

 bool ReadCoefficient()


added note structure

added note structure

--- arduino-singing-in-the-rain.ino
+++ arduino-singing-in-the-rain.ino
@@ -6,16 +6,21 @@
  circuit:
  * 8-ohm speaker on digital pin 8

- created 21 Jan 2010
- modified 30 Aug 2011
- by Tom Igoe
-
-This example code is in the public domain.
-
  http://arduino.cc/en/Tutorial/Tone

  */
 #include "pitches.h"
+
+struct note {
+  int pitch;
+  float duration;
+};
+
+struct note melody1[] = {
+  {NOTE_D4, 0.5},
+  {NOTE_D4, 0.25},
+  {NOTE_D4, 0.5}
+};

 // notes in the melody:
 int melody[] = {
@@ -31,14 +36,17 @@
 };

 void setup() {
+  Serial.begin(9600);
   // iterate over the notes of the melody:
-  for (int thisNote = 0; thisNote < sizeof(melody)/sizeof(melody[0]); thisNote++) {
+  for (int thisNote = 0; thisNote < sizeof(melody1)/sizeof(melody1[0]); thisNote++) {

     // to calculate the note duration, take one second
     // divided by the note type.
     //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
-    int noteDuration = 1000 / noteDurations[thisNote];
-    tone(2, melody[thisNote], noteDuration);
+    int noteDuration = 1000 * melody1[thisNote].duration;
+    tone(2, melody1[thisNote].pitch, noteDuration);
+    Serial.println(melody1[thisNote].pitch);
+    Serial.println(melody1[thisNote].duration);

     // to distinguish the notes, set a minimum time between them.
     // the note's duration + 30% seems to work well:


Update arduino

Update arduino

--- arduino/ir_blower/ir_blower.ino
+++ arduino/ir_blower/ir_blower.ino
@@ -1,50 +1,52 @@
+// Author  : Brendan Horan
 // License : BSD 3-Clause
-// Version 0.0.1
-// Author : Brendan Horan
+// Version : 0.0.1
+// NOTES   :
+//  *  Install a 10uf capacitor between RESET and GND.
+//     This prevents the Arduino Nano from restarting
+//     on serial port open.
+//  *  Physical pin 3 -> IR sender
+//  *  Physical pin 4 -> power control
 //
-// NOTES :
-//   Install a 10uf capacitor between RESET and GND.
-//   This prevents the Arduino Nano from restarting
-//   on serial port open.
-
+// Requires the IRremote library :
+// https://github.com/shirriff/Arduino-IRremote
+// NOTE some libraries are licensed under other licenses
+
+
 #include <IRremote.h>
 IRsend irsend;
-
+
 // Variable to hold incoming serial comms
 int ctlmsg = 0;
-
+
+// Define Power controler pin
+int pctl = 4;
+
+
 void setup() {
-        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
-        Serial.print ("Connected:9600");
+        pinMode(pctl,OUTPUT);
+        digitalWrite(pctl,HIGH);
+        Serial.begin(9600);
+        Serial.println ("Connected:9600");
+        Serial.println ("OK");
 }
-
+
+
 void loop() {
-
+
+
         // wait for data
         if (Serial.available() > 0) {
                 // read data
                 ctlmsg = Serial.read();
-
-                // send IR signal based on value from ir-blower server
-               // 49 =1 , 50=2 etc
+                Serial.print (ctlmsg);
+
+
+               // send IR signal based on value from ir-blower server
+               // IR-blower-server will send value (1-6, a-f)
+               // Arduino client reads the ASCII value and acts on it
+
                 switch (ctlmsg) {
                   case 49:
-                    Serial.print("49");
-                  //  irsend.send
-                    break;
-                  case 50:
-                    Serial.print("50");
-                 //   irsend.send
-                    break;
-                  case 51:
-                    Serial.print("51");
-                 //   irsend.send
-                    break;
-                  case 52:
-                    Serial.print("52");
-                 //   irsend.send
-                    break;
-                }
-
-        }
-}
+                    // Value 1
+                    // Master 9 input select +


Complete magsensor code.

Complete magsensor code.

--- arduino/magsensor/magsensor.ino
+++ arduino/magsensor/magsensor.ino
@@ -1,30 +1,46 @@
+#include <EEPROM.h>
 #include <RCSwitch.h>
 #include <LowPower.h>
+#include "protocol.h"

 //RCSwitch rfDevice = RCSwitch();

-int SERIAL_COMMUNICATION_SPEED = 9600;
+int SERIAL_COMMUNICATION_SPEED = 9600;
 // How long do we sleep. The longer, the better for the battery but the
 // resolution of our switch will suffer.
-period_t SLEEP_PERIOD = SLEEP_8S;
+// Usual values: SLEEP_8S or SLEEP_FOREVER
+period_t SLEEP_PERIOD = SLEEP_FOREVER;
 // Pin on which the magnetic swith is plugged.
 int MAGNETIC_SWITCH_PIN = 2;
 // Pin on which the RF device is plugged;
 int RF_DEVICE_PIN = 13;
 // Status of the magnetic switch. We consider the door closed
-boolean contact = true;
-// Did we just booted ?
-boolean justBooted = true;
+boolean g_contact = true;
+// EEPROM address usage
+int EE_DEVICE_NUMBER = 0;
+// device number
+int g_device_number;

-// Function called on interrupt
-void wakeUp() {
-  // It is a critical section so don't do anything
+// Function called on door state change
+void doorStateChange() {
+  // Check contact state. We assume a normally closed switch.
+  boolean newContact = (digitalRead(MAGNETIC_SWITCH_PIN) == HIGH);
+  // Does the contact status changed since we last check
+  if (newContact != g_contact) {
+    // Send the status of the contact on one bit
+    //rfDevice.send(contact, 1);
+    flashLED();
+    // Update the status of the contact
+    g_contact = newContact;
+    //Serial.print("pushing to RF device: ");
+    //Serial.println(contact);
+  }
 }

 void flashLED() {
   digitalWrite(RF_DEVICE_PIN, HIGH);
   delay(50);
-  digitalWrite(RF_DEVICE_PIN, LOW);
+  digitalWrite(RF_DEVICE_PIN, LOW);
 }

 void setup() {
@@ -38,31 +54,21 @@
   // rfDevice.setProtocol(2);
   // Optional set number of transmission repetitions.
   // rfDevice.setRepeatTransmit(15);
-  /********************  Magnetic switch initialisation ***********************/
+  /*****************************  Configuration *******************************/
+  g_device_number = EEPROM.read(EE_DEVICE_NUMBER);
+  if (!g_device_number) { // If not setup already, configure it to default value 1
+    g_device_number = 1;
+    EEPROM.write(EE_DEVICE_NUMBER, g_device_number);
+  }
+  /***************************  Pin initialisation ****************************/
   pinMode(MAGNETIC_SWITCH_PIN, INPUT);
   pinMode(RF_DEVICE_PIN, OUTPUT);
+  /*********************** Interruption initialisation ************************/
+  // Allow wake up pin to trigger interrupt on state change.
+  attachInterrupt(digitalPinToInterrupt(MAGNETIC_SWITCH_PIN), doorStateChange, CHANGE);
 }

 void loop() {
-  // Allow wake up pin to trigger interrupt on state change.
-  //attachInterrupt(digitalPinToInterrupt(MAGNETIC_SWITCH_PIN), wakeUp, CHANGE);
-
   // Go to sleep mode
   LowPower.powerDown(SLEEP_PERIOD, ADC_OFF, BOD_OFF);
-
-  // Disable external pin interrupt on wake up pin.
-  //detachInterrupt(digitalPinToInterrupt(MAGNETIC_SWITCH_PIN));
-
-  // Check contact state. We assume a normally closed switch.
-  boolean newContact = (digitalRead(MAGNETIC_SWITCH_PIN) == HIGH);
-  // Does the contact status changed since we last check
-  if (newContact != contact) {
-    // Send the status of the contact on one bit
-    //rfDevice.send(contact, 1);
-    flashLED();
-    // Update the status of the contact
-    contact = newContact;
-    //Serial.print("pushing to RF device: ");
-    //Serial.println(contact);
-  }
 }


small correction, added the inclusion of magnetometer library, in order to be more consistent

--- examples/basic_bt_movement/basic_bt_movement.ino
+++ examples/basic_bt_movement/basic_bt_movement.ino
@@ -1,5 +1,7 @@
 #include <AFMotor.h>
 #include <Smartcar.h>
+#include <Wire.h>
+#include <HMC5883L.h>
 #include <SoftwareSerial.h>

 SoftwareSerial bluetooth(50,51); // RX, TX


Different on/off temps, fix variable types

--- temperature-relay.ino
+++ temperature-relay.ino
@@ -46,7 +46,8 @@
 float temperature;
 float minuteAverage;
 float outdoorTemp;
-float tempThreshold = 62.0F;
+double tempOnThreshold = 62.0;
+double tempOffThreshold = 68.0;
 bool power = false;
 boolean ledState = LOW;

@@ -91,7 +92,8 @@
   Particle.variable("power", power);
   Particle.variable("temperature", temperature);
   Particle.variable("min_average", minuteAverage);
-  Particle.variable("threshold", tempThreshold);
+  Particle.variable("temp_on", tempOnThreshold);
+  Particle.variable("temp_off", tempOffThreshold);
   Particle.function("power", adjustPower);
   publishPowerStatus();

@@ -246,9 +248,9 @@

     Serial.println("## Evaluating Power");

-    if(minuteAverage > tempThreshold) {
+    if(minuteAverage > tempOffThreshold) {
       turnOffPower();
-    } else {
+    } else if(minuteAverage < tempOnThreshold) {
       turnOnPower();
     }
   }


added linelocation_prev

added linelocation_prev

--- master/master.ino
+++ master/master.ino
@@ -103,7 +103,7 @@
 float bearing;
 float bearing_offset;
 int32_t bearing_int;
-uint8_t linelocation;
+uint8_t linelocation, linelocation_prev;

 /**********************************************************/
 /*                        Orbit                           */