merging

merging

--- deploy-dist/rootfolder/sketches/ArdulinkProtocol/ArdulinkProtocol.ino
+++ deploy-dist/rootfolder/sketches/ArdulinkProtocol/ArdulinkProtocol.ino
@@ -229,3 +229,234 @@
 }

+/*
+Copyright 2013 Luciano Zu project Ardulink http://www.ardulink.org/
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+This sketch is an example to understand how Arduino can recognize ALProtocol.
+However, it can easily be reused for their own purposes or as a base for a library.
+Read carefully the comments. When you find "this is general code you can reuse"
+then it means that it is generic code that you can use to manage the ALProtocol.
+When you find "this is needed just as example for this sketch" then it means that
+you code useful for a specific purpose. In this case you have to modify it to suit
+your needs.
+*/
+
+// int intensity = 0;               // led intensity this is needed just as example for this sketch
+String inputString = "";         // a string to hold incoming data (this is general code you can reuse)
+boolean stringComplete = false;  // whether the string is complete (this is general code you can reuse)
+
+#define digitalPinListeningNum 14 // Change 14 if you have a different number of pins.
+#define analogPinListeningNum 6 // Change 6 if you have a different number of pins.
+boolean digitalPinListening[digitalPinListeningNum]; // Array used to know which pins on the Arduino must be listening.
+boolean analogPinListening[analogPinListeningNum]; // Array used to know which pins on the Arduino must be listening.
+int digitalPinListenedValue[digitalPinListeningNum]; // Array used to know which value is read last time.
+int analogPinListenedValue[analogPinListeningNum]; // Array used to know which value is read last time.
+
+void setup() {
+  // initialize serial: (this is general code you can reuse)
+  Serial.begin(115200);
+
+  Serial.print("alp://rply/");
+  Serial.print("ok?id=0");
+  Serial.print('\n'); // End of Message
+  Serial.flush();
+
+  //set to false all listen variable
+  int index = 0;
+  for (index = 0; index < digitalPinListeningNum; index++) {
+    digitalPinListening[index] = false;
+    digitalPinListenedValue[index] = -1;
+  }
+  for (index = 0; index < analogPinListeningNum; index++) {
+    analogPinListening[index] = false;
+    analogPinListenedValue[index] = -1;
+  }
+
+  // Turn off everything (not on RXTX)
+  for (index = 2; index < digitalPinListeningNum; index++) {
+    pinMode(index, OUTPUT);
+    digitalWrite(index, LOW);
+  }
+
+  // Turn off LED this is needed just as example for this sketch
+//  analogWrite(11, intensity);
+
+  // Read from 4 this is needed just as example for this sketch
+//  pinMode(4, INPUT);
+
+  // In order to work with analog input signal you have to set pinMode to INPUT please add Ax pinMode statement if you need for it
+  //pinMode(A0, INPUT);
+
+}
+
+void loop() {
+  // when a newline arrives:
+  if (stringComplete) {
+
+    if(inputString.startsWith("alp://")) { // OK is a message I know (this is general code you can reuse)
+
+      boolean msgRecognized = true;
+
+      if(inputString.substring(6,10) == "kprs") { // KeyPressed
+        // here you can write your own code. For instance the commented code change pin intensity if you press 'a' or 's'
+        // take the command and change intensity on pin 11 this is needed just as example for this sketch
+        //char commandChar = inputString.charAt(14);
+        //if(commandChar == 'a' and intensity > 0) { // If press 'a' less intensity
+        //  intensity--;
+        //  analogWrite(11,intensity);
+        //} else if(commandChar == 's' and intensity < 125) { // If press 's' more intensity
+        //  intensity++;
+        //  analogWrite(11,intensity);
+        //}
+      } else if(inputString.substring(6,10) == "ppin") { // Power Pin Intensity (this is general code you can reuse)
+          int separatorPosition = inputString.indexOf('/', 11 );
+          String pin = inputString.substring(11,separatorPosition);
+          String intens = inputString.substring(separatorPosition + 1);
+          pinMode(pin.toInt(), OUTPUT);
+          analogWrite(pin.toInt(),intens.toInt());
+      } else if(inputString.substring(6,10) == "ppsw") { // Power Pin Switch (this is general code you can reuse)
+          int separatorPosition = inputString.indexOf('/', 11 );
+          String pin = inputString.substring(11,separatorPosition);
+          String power = inputString.substring(separatorPosition + 1);
+          pinMode(pin.toInt(), OUTPUT);
+          if(power.toInt() == 1) {
+            digitalWrite(pin.toInt(), HIGH);
+          } else if(power.toInt() == 0) {
+            digitalWrite(pin.toInt(), LOW);
+          }
+      } else if(inputString.substring(6,10) == "tone") { // tone request (this is general code you can reuse)
+          int firstSlashPosition = inputString.indexOf('/', 11 );
+          int secondSlashPosition = inputString.indexOf('/', firstSlashPosition + 1 );
+          int pin = inputString.substring(11,firstSlashPosition).toInt();
+          int frequency = inputString.substring(firstSlashPosition + 1, secondSlashPosition).toInt();
+          int duration = inputString.substring(secondSlashPosition + 1).toInt();
+          if(duration == -1) {
+          	tone(pin, frequency);
+          } else {
+          	tone(pin, frequency, duration);
+          }
+      } else if(inputString.substring(6,10) == "notn") { // no tone request (this is general code you can reuse)
+          int firstSlashPosition = inputString.indexOf('/', 11 );
+          int pin = inputString.substring(11,firstSlashPosition).toInt();
+          noTone(pin);
+      } else if(inputString.substring(6,10) == "srld") { // Start Listen Digital Pin (this is general code you can reuse)
+          String pin = inputString.substring(11);
+          digitalPinListening[pin.toInt()] = true;
+          digitalPinListenedValue[pin.toInt()] = -1; // Ensure a message back when start listen happens.
+          pinMode(pin.toInt(), INPUT);
+      } else if(inputString.substring(6,10) == "spld") { // Stop Listen Digital Pin (this is general code you can reuse)
+          String pin = inputString.substring(11);
+          digitalPinListening[pin.toInt()] = false;
+          digitalPinListenedValue[pin.toInt()] = -1; // Ensure a message back when start listen happens.
+      } else if(inputString.substring(6,10) == "srla") { // Start Listen Analog Pin (this is general code you can reuse)
+          String pin = inputString.substring(11);
+          analogPinListening[pin.toInt()] = true;
+          analogPinListenedValue[pin.toInt()] = -1; // Ensure a message back when start listen happens.
+      } else if(inputString.substring(6,10) == "spla") { // Stop Listen Analog Pin (this is general code you can reuse)
+          String pin = inputString.substring(11);
+          analogPinListening[pin.toInt()] = false;
+          analogPinListenedValue[pin.toInt()] = -1; // Ensure a message back when start listen happens.
+      } else {
+        msgRecognized = false; // this sketch doesn't know other messages in this case command is ko (not ok)
+      }
+
+      // Prepare reply message if caller supply a message id (this is general code you can reuse)
+      int idPosition = inputString.indexOf("?id=");
+      if(idPosition != -1) {
+        String id = inputString.substring(idPosition + 4);
+        // print the reply
+        Serial.print("alp://rply/");
+        if(msgRecognized) { // this sketch doesn't know other messages in this case command is ko (not ok)
+          Serial.print("ok?id=");
+        } else {
+          Serial.print("ko?id=");
+        }
+        Serial.print(id);
+        Serial.print('\n'); // End of Message
+        Serial.flush();
+      }
+    }
+
+    // clear the string:
+    inputString = "";
+    stringComplete = false;
+  }
+
+  // Send listen messages
+  int index = 0;
+  for (index = 0; index < digitalPinListeningNum; index++) {
+    if(digitalPinListening[index] == true) {
+      int value = digitalRead(index);
+      if(value != digitalPinListenedValue[index]) {
+        digitalPinListenedValue[index] = value;
+        Serial.print("alp://dred/");
+        Serial.print(index);
+        Serial.print("/");
+        Serial.print(value);
+        Serial.print('\n'); // End of Message
+        Serial.flush();
+      }
+    }
+  }
+  for (index = 0; index < analogPinListeningNum; index++) {
+    if(analogPinListening[index] == true) {
+      int value = highPrecisionAnalogRead(index);
+      if(value != analogPinListenedValue[index]) {
+        analogPinListenedValue[index] = value;
+        Serial.print("alp://ared/");
+        Serial.print(index);
+        Serial.print("/");
+        Serial.print(value);
+        Serial.print('\n'); // End of Message
+        Serial.flush();
+      }
+    }
+  }
+}
+
+// Reads 4 times and computes the average value
+int highPrecisionAnalogRead(int pin) {
+  int value1 = analogRead(pin);
+  int value2 = analogRead(pin);
+  int value3 = analogRead(pin);
+  int value4 = analogRead(pin);
+
+  int retvalue = (value1 + value2 + value3 + value4) / 4;
+  return retvalue;
+}
+
+/*
+  SerialEvent occurs whenever a new data comes in the
+ hardware serial RX.  This routine is run between each
+ time loop() runs, so using delay inside loop can delay
+ response.  Multiple bytes of data may be available.
+ This is general code you can reuse.
+ */
+void serialEvent() {
+
+  while (Serial.available() && !stringComplete) {
+    // get the new byte:
+    char inChar = (char)Serial.read();
+    // add it to the inputString:
+    inputString += inChar;
+    // if the incoming character is a newline, set a flag
+    // so the main loop can do something about it:
+    if (inChar == '\n') {
+      stringComplete = true;
+    }
+  }
+}
+
+


Tune motor speed.

Tune motor speed.

--- mech/mech.ino
+++ mech/mech.ino
@@ -76,13 +76,13 @@
   stepper3.setCurrentPosition(0);       // Set "Zero" position "C" Motor 3
   calibrate1(false);                    // Calibration function "L" Motor 1
   calibrate2(false);                    // Calibration function "C" Motor 2
-  //calibrate3(false);                  // Calibration function "C" Motor 3
+  calibrate3(false);                  // Calibration function "C" Motor 3
 }

 // Calibration process for "L" Motor 1
 void calibrate1(boolean run) {
   long oldPosition = stepper1.currentPosition();
-  stepper1.setSpeed(-1500);
+  stepper1.setSpeed(-2000);
   while (digitalRead(optInpin1) == LOW) {
     stepper1.runSpeed();
     busLoop();
@@ -97,7 +97,7 @@
 // Calibration process for "C" Motor 2
 void calibrate2(boolean run) {
   long oldPosition = stepper2.currentPosition();
-  stepper2.setSpeed(-600);
+  stepper2.setSpeed(-2000);
   while (digitalRead(optInpin2) == LOW) {
     stepper2.runSpeed();
     busLoop();
@@ -112,7 +112,7 @@
 // Calibration process for "C" Motor 3
 void calibrate3(boolean run) {
   long oldPosition = stepper3.currentPosition();
-  stepper3.setSpeed(-600);
+  stepper3.setSpeed(-2000);
   while (digitalRead(optInpin3) == LOW) {
     stepper3.runSpeed();
     busLoop();


Add comments to improve readability

Add comments to improve readability

--- examples/arduino_can/arduino_can.ino
+++ examples/arduino_can/arduino_can.ino
@@ -4,7 +4,9 @@
 static can_message_t can_message;

 void spi_transfer_mcp2515(uint8_t *buf, uint8_t len) {
+  // TODO: Select the MCP2515 if SPI.transfer(buf,len) doesn't
   SPI.transfer(buf, len);
+  // TODO: Deselect the MCP2515 if SPI.transfer(buf,len) doesn't
 }

 void print_can_message(can_message_t message) {
@@ -12,24 +14,26 @@
   Serial.println(message.std_id, DEC);
   Serial.println(message.ext_id, DEC);
   Serial.println(message.length, DEC);
+  // TODO: Print data
 }

 void setup() {
   can_message = {MTYPE_EXTENDED_DATA, 5, 6, 2, {1,2}};
-  pinMode(9, INPUT);
+  pinMode(9, INPUT); // Used as the interrupt (INT) pin

   Serial.begin(115200);
   Serial.println("Start Serial");

-  delay(50);
+  delay(50); // Allow the MCP2515 time to start. May not be necessary.

-  config_interrupts(0x03);
+  config_interrupts(0x03); // Inturrupt when a message is received
   config_timing(CNF1_10MHZ_125KBIT, CNF2_10MHZ_125KBIT, CNF3_10MHZ_125KBIT);
-  config_receive_ctrl(0x60, 0x60);
-  set_mode(MODE_LOOPBACK);
+  config_receive_ctrl(0x60, 0x60); // Ignore filters, receive all messages
+  set_mode(MODE_LOOPBACK); // Loopback sends messages to itself for testing
 }

 void loop() {
+  // The INT pin will go low when there is an interrupt
   if (!digitalRead(9)) {
     Serial.println("Interrupt");
   }


added command for attaching infrared sensor to motors

--- jenny5-firmware/jenny5-firmware.ino
+++ jenny5-firmware/jenny5-firmware.ino
@@ -30,83 +30,82 @@
 bool first_start;

 //--------------------------------------------------------------------------------------------
-void setup()
+void setup()
 {
   first_start = 0;
-  strcpy(firmware_version, "2016.05.09.0");
-
+  strcpy(firmware_version, "2016.05.10.0");
+
   current_buffer[0] = 0;

   Serial.begin(115200); //Open Serial connection

-  #ifdef DEBUG
+#ifdef DEBUG
   Serial.write("Commands are:");
   Serial.println(F("T# // test connection. Returns T#."));
   Serial.println(F("MSx y# // Moves stepper 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 MSx d# when motor rotation is over. If movement was complete, then d is 0, otherwise is the distance to go."));
   Serial.println(F("MDx y# // Moves dc motor x for y miliseconds. Outputs MDx d# when motor rotation is over. If movement was complete, then d is 0, otherwise is the time to go."));
   Serial.println(F("MVx y# // Moves servo motor x for y steps.");
-
-  Serial.println(F("HSx# // Moves stepper motor x to home position. The first sensor in the list of sensors must be the potentiometer which establish the home position. The motor does nothing if no potentiometer is attached. Returns HSx#."));
-  Serial.println(F("HDx# // Moves DC motor x to home position. The first sensor in the list of sensors must be the button which establish the home position. The motor does nothing if no potentiometer is attached. Returns HDx#."));
-  Serial.println(F("HVx# // Moves servo motor x to home position.  Returns HVx#.");
-
-  Serial.println(F("DSx#  // Disables stepper motor x. Outputs DSx# when done."));
-  Serial.println(F("DDx#  // Disables dc motor x. Outputs DDx# when done."));
-
-  Serial.println(F("Lx#  // Locks stepper motor x. Outputs Lx# when done."));
-
-  Serial.println(F("SSx s a# // Sets speed of stepper motor x to s and the acceleration to a."));
-  Serial.println(F("SDx s# // Sets speed of motor x to s."));
-  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 bring the robot when we start."));
-
-  Serial.println(F("ASx n Py Bz ... # // Attach to stepper motor x a list of n sensors (like Potentiometer y, Button z etc)."));
-  Serial.println(F("ADx n Py Bz ... # // Attach to dc motor x a list of n sensors (like Potentiometer y, Button z etc)."));
-  Serial.println(F("AVx n Py Bz ... # // Attach to servo 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. Outputs Ux d# when the reading has been completed. Note that this works in \"background\" and can output after some time (and in the meantime the program can do something else."));
-  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("GSx# // Gets the parameters for stepper motor x: speed acceleration num_sensors sensor_index1, sensor_type1 sensor_index1, sensor_type1. Outputs GSx s a 1 0 0#"));
-  Serial.println(F("GDx# // Gets the parameters for dc motor x: speed num_sensors sensor_index1, sensor_type1 sensor_index1, sensor_type1. Outputs GDx s a 1 0 0#"));
-  Serial.println(F("GVx# // Gets the parameters for dc motor x: speed num_sensors sensor_index1, sensor_type1 sensor_index1, sensor_type1. Outputs GVx s a 1 0 0#"));
-  Serial.println(F("GPx# // Gets the parameters for potentiometer x: min max home. Outputs PPx l u h#"));
-  Serial.println(F("GUx# // Gets the parameters for ultrasound x: trig_pin echo_pin. Outputs UPx t e#"));
-
-  Serial.println(F("CS n d1 s1 e1 d2 s2 e2# // Creates the stepper motors controller and set some of its parameters. n is the number of motors, d, s, e are dir, step and enable pins. Outputs CS# when done."));
-  Serial.println(F("CD n p1 d11 d12 e1 p2 d21 d22 e2# // Creates the dc motors controller and set some of its parameters. n is the number of motors, p is the pwm_pin, d1 and d2 are the direction pins and e is the enable pins. Outputs CD# when done."));
-  Serial.println(F("CV n# // Creates the servo motors controller and set some of its parameters. n is the number of motors, Outputs CV# when done."));
-
-  Serial.println(F("CP n p1 l1 h1 _h1 _d1 p2 l2 h2 _h2 _d2# // Creates the potentiometers controller and set some of its parameters. n is the number of potentiometers, p is the output pin, l, h and _h are bottom, upper and home position, _d is the directon of the sensor relative to the direction in which the motor is moving. Outputs CP# when done."));
-  Serial.println(F("CU n t1 e1 t2 e2# // Creates the ultrasonic controller and set some of its parameters. n is the number of sonars, t and e are trigger and echo pins. Outputs CU# when done."));
-  Serial.println(F("CI n p1 min1 max1 home1 p2 min2 max2 home2# // Creates the infrared controller and set some of its parameters. n is the number of infrared sensors, p is the analog pin and min, max and home are the lower, upper bounds and home position of this sensor. Outputs CI# when done."));
-  Serial.println(F("CB n p1 p2# // Creates the buttons controller and set some of its parameters. n is the number of button sensors, p is the digital pin. Outputs CB# when done."));
-
-
-  Serial.println(F("V# // Outputs version string. eg: 2016.01.17.0#"));
-
-
-  Serial.println(F("Motor index is between 0 and num_motors - 1"));
-
-  Serial.println();
+                 Serial.println(F("HSx# // Moves stepper motor x to home position. The first sensor in the list of sensors will establish the home position. The motor does nothing if no sensor is attached. Returns HSx#."));
+                 Serial.println(F("HDx# // Moves DC motor x to home position. The first sensor in the list of sensors must be the button which establish the home position. The motor does nothing if no sensor is attached. Returns HDx#."));
+                 Serial.println(F("HVx# // Moves servo motor x to home position.  Returns HVx#.");
+
+                                Serial.println(F("DSx#  // Disables stepper motor x. Outputs DSx# when done."));
+                                Serial.println(F("DDx#  // Disables dc motor x. Outputs DDx# when done."));
+
+                                Serial.println(F("Lx#  // Locks stepper motor x. Outputs Lx# when done."));
+
+                                Serial.println(F("SSx s a# // Sets speed of stepper motor x to s and the acceleration to a."));
+                                Serial.println(F("SDx s# // Sets speed of motor x to s."));
+                                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 bring the robot when we start."));
+
+                                Serial.println(F("ASx n Py Bz ... # // Attach to stepper motor x a list of n sensors (like Potentiometer y, Button z etc)."));
+                                Serial.println(F("ADx n Py Bz ... # // Attach to dc motor x a list of n sensors (like Potentiometer y, Button z etc)."));
+                                Serial.println(F("AVx n Py Bz ... # // Attach to servo 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. Outputs Ux d# when the reading has been completed. Note that this works in \"background\" and can output after some time (and in the meantime the program can do something else."));
+                                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("GSx# // Gets the parameters for stepper motor x: speed acceleration num_sensors sensor_index1, sensor_type1 sensor_index1, sensor_type1. Outputs GSx s a 1 0 0#"));
+                                Serial.println(F("GDx# // Gets the parameters for dc motor x: speed num_sensors sensor_index1, sensor_type1 sensor_index1, sensor_type1. Outputs GDx s a 1 0 0#"));
+                                Serial.println(F("GVx# // Gets the parameters for dc motor x: speed num_sensors sensor_index1, sensor_type1 sensor_index1, sensor_type1. Outputs GVx s a 1 0 0#"));
+                                Serial.println(F("GPx# // Gets the parameters for potentiometer x: min max home. Outputs PPx l u h#"));
+                                Serial.println(F("GUx# // Gets the parameters for ultrasound x: trig_pin echo_pin. Outputs UPx t e#"));
+
+                                Serial.println(F("CS n d1 s1 e1 d2 s2 e2# // Creates the stepper motors controller and set some of its parameters. n is the number of motors, d, s, e are dir, step and enable pins. Outputs CS# when done."));
+                                Serial.println(F("CD n p1 d11 d12 e1 p2 d21 d22 e2# // Creates the dc motors controller and set some of its parameters. n is the number of motors, p is the pwm_pin, d1 and d2 are the direction pins and e is the enable pins. Outputs CD# when done."));
+                                Serial.println(F("CV n# // Creates the servo motors controller and set some of its parameters. n is the number of motors, Outputs CV# when done."));
+
+                                Serial.println(F("CP n p1 l1 h1 _h1 _d1 p2 l2 h2 _h2 _d2# // Creates the potentiometers controller and set some of its parameters. n is the number of potentiometers, p is the output pin, l, h and _h are bottom, upper and home position, _d is the directon of the sensor relative to the direction in which the motor is moving. Outputs CP# when done."));
+                                Serial.println(F("CU n t1 e1 t2 e2# // Creates the ultrasonic controller and set some of its parameters. n is the number of sonars, t and e are trigger and echo pins. Outputs CU# when done."));
+                                Serial.println(F("CI n pin1 min1 max1 home1 dir1 pin2 min2 max2 home2 dir2# // Creates the infrared controller and set some of its parameters. n is the number of infrared sensors, p is the analog pin and min, max and home are the lower, upper bounds and home position of this sensor. Outputs CI# when done."));
+                                Serial.println(F("CB n p1 p2# // Creates the buttons controller and set some of its parameters. n is the number of button sensors, p is the digital pin. Outputs CB# when done."));
+
+
+                                Serial.println(F("V# // Outputs version string. eg: 2016.01.17.0#"));
+
+
+                                Serial.println(F("Motor index is between 0 and num_motors - 1"));
+
+                                Serial.println();
 #endif
-  Serial.write("T#");// initialization is over; must check for T# string (which is the alive test)
+                                Serial.write("T#");// initialization is over; must check for T# string (which is the alive test)
 }
-//--------------------------------------------------------------------------------------------
-void parse_and_execute_commands(char* tmp_str, byte str_length, char *serial_out)
+               //--------------------------------------------------------------------------------------------
+               void parse_and_execute_commands(char* tmp_str, byte str_length, char *serial_out)
 {
   byte i = 0;
   serial_out[0] = 0;
-  while (i < str_length){
+  while (i < str_length) {
     // can be more than 1 command in a string, so I have to check again for a letter
-    if ((tmp_str[i] >= 'A' && tmp_str[i] <= 'Z') || (tmp_str[i] >= 'a' && tmp_str[i] <= 'z')){
-
-      if (tmp_str[i] == 'M' || tmp_str[i] == 'm'){// moves motor
-        if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's'){// stepper motor
+    if ((tmp_str[i] >= 'A' && tmp_str[i] <= 'Z') || (tmp_str[i] >= 'a' && tmp_str[i] <= 'z')) {
+
+      if (tmp_str[i] == 'M' || tmp_str[i] == 'm') { // moves motor
+        if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's') { // stepper motor
           int motor_index, num_steps;
           int num_read = sscanf(tmp_str + i + 2, "%d%d", &motor_index, &num_steps);
-          if (num_read == 2){
+          if (num_read == 2) {
             stepper_motors_controller.move_motor(motor_index, num_steps);
             is_command_running = 1;
             i += 5;
@@ -114,333 +113,348 @@
           else
             i++;// error on incomplete string (does nothing)
         }
+        else if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd') { // DC motor
+          int motor_index, num_miliseconds;
+          int num_read = sscanf(tmp_str + i + 2, "%d%d", &motor_index, &num_miliseconds);
+          if (num_read == 2) {
+            dc_motors_controller_TB6612FNG.move_motor(motor_index, num_miliseconds);
+            is_command_running = 1;
+            i += 5;
+          }
+          else
+            i++;// error on incomplete string (does nothing)
+        }
         else
-          if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd'){// DC motor
-            int motor_index, num_miliseconds;
-            int num_read = sscanf(tmp_str + i + 2, "%d%d", &motor_index, &num_miliseconds);
-            if (num_read == 2){
-              dc_motors_controller_TB6612FNG.move_motor(motor_index, num_miliseconds);
-              is_command_running = 1;
-              i += 5;
+          i++; // incomplete string
+        continue;
+      }
+
+      // potentiometer
+      if (tmp_str[i] == 'P' || tmp_str[i] == 'p') {
+        int sensor_index;
+        sscanf(tmp_str + i + 1, "%d", &sensor_index);
+        int sensor_value = potentiometers_controller.get_position(sensor_index);
+        sprintf(serial_out, "P%d %d#", sensor_index, sensor_value);
+        i += 2;
+        continue;
+      }
+
+      // ultrasonic
+      if (tmp_str[i] == 'U' || tmp_str[i] == 'u') {
+        int sensor_index;
+        sscanf(tmp_str + i + 1, "%d", &sensor_index);
+        ultrasonic_sensors_controller.trigger(sensor_index);
+        //sprintf(serial_out, "U%d %d#", sensor_index, sensor_value);
+
+        i += 2;
+        continue;
+      }
+
+      // infrared
+      if (tmp_str[i] == 'I' || tmp_str[i] == 'i') {
+        int sensor_index;
+        sscanf(tmp_str + i + 1, "%d", &sensor_index);
+        int sensor_value = infrared_sensors_controller.get_signal_strength(sensor_index);
+        sprintf(serial_out, "I%d %d#", sensor_index, sensor_value);
+        i += 2;
+        continue;
+      }
+
+      // disables motor
+      if (tmp_str[i] == 'D' || tmp_str[i] == 'd') {
+        int motor_index;
+        if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's') { // disables stepper motor
+          sscanf(tmp_str + i + 2, "%d", &motor_index);
+          stepper_motors_controller.disable(motor_index);
+          sprintf(serial_out, "DS%d#", motor_index);
+        }
+        else if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd') { // disables DC motor
+          sscanf(tmp_str + i + 2, "%d", &motor_index);
+          dc_motors_controller_TB6612FNG.disable(motor_index);
+          sprintf(serial_out, "DD%d#", motor_index);
+        }
+        i += 4;
+        continue;
+      }
+
+      // locks motor
+      if (tmp_str[i] == 'L' || tmp_str[i] == 'l') {
+        int motor_index;
+        sscanf(tmp_str + i + 1, "%d", &motor_index);
+        stepper_motors_controller.lock(motor_index);
+        sprintf(serial_out, "L%d#", motor_index);
+        i += 2;
+        continue;
+      }
+
+      // go home
+      if (tmp_str[i] == 'H' || tmp_str[i] == 'h') {
+        int motor_index;
+        if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's') { // go stepper home
+          sscanf(tmp_str + i + 2, "%d", &motor_index);
+          stepper_motors_controller.go_home(motor_index, &potentiometers_controller);
+          sprintf(serial_out, "HS%d#", motor_index);
+        }
+        else if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd') { // go stepper home
+          sscanf(tmp_str + i + 2, "%d", &motor_index);
+          dc_motors_controller_TB6612FNG.go_home(motor_index, &buttons_controller);
+          sprintf(serial_out, "HD%d#", motor_index);
+        }
+        is_command_running = 1;
+        i += 4;
+        continue;
+      }
+
+      // sets something
+      if (tmp_str[i] == 'S' || tmp_str[i] == 's') {
+        if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's') { // stepper motor speed and acceleration
+          int motor_index;
+          int motor_speed, motor_acceleration;
+          sscanf(tmp_str + i + 2, "%d%d%d", &motor_index, &motor_speed, &motor_acceleration);
+          stepper_motors_controller.set_speed_and_acceleration(motor_index, motor_speed, motor_acceleration);
+          i += 5;
+        }
+        else if (tmp_str[i + 1] == 'P' || tmp_str[i + 1] == 'p') { // potentiometer min max home
+          int pot_index, pot_min, pot_max, pot_home, pot_pin, pot_dir;
+          sscanf(tmp_str + i + 2, "%d%d%d%d%d%d", &pot_index, &pot_pin, &pot_min, &pot_max, &pot_home, &pot_dir);
+          potentiometers_controller.set_params(pot_index, pot_pin, pot_min, pot_max, pot_home, pot_dir);
+          i += 7;
+        }
+        else if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd') { // dc motor speed
+          int motor_index;
+          int motor_speed;
+          sscanf(tmp_str + i + 2, "%d%d", &motor_index, &motor_speed);
+          dc_motors_controller_TB6612FNG.set_speed(motor_index, motor_speed);
+          i += 5;
+        }
+        continue;
+      }
+
+      if (tmp_str[i] == 'A' || tmp_str[i] == 'a') { // attach sensors to motors
+        int motor_index, num_sensors;
+        char motor_type = tmp_str[i];
+        sscanf(tmp_str + i + 2, "%d%d", &motor_index, &num_sensors);
+        if (motor_type == 'S' || motor_type == 's') // attach to stepper motors controller
+          stepper_motors_controller.set_num_attached_sensors(motor_index, num_sensors);
+        else if (motor_type == 'D' || motor_type == 'd') // attach to DC motors controller
+          dc_motors_controller_TB6612FNG.set_num_attached_sensors(motor_index, num_sensors);
+
+        // now I have to add sensors one by one
+        int j = i + 4;
+        i += 5;
+        while (j < str_length) {
+          if (tmp_str[j] == 'P' || tmp_str[j] == 'p') {
+            int sensor_index;
+            sscanf(tmp_str + j + 1, "%d", &sensor_index);
+            if (motor_type == 'S' || motor_type == 's') // attach to stepper motors controller
+              stepper_motors_controller.add_sensor(motor_index, POTENTIOMETER, sensor_index);
+            else if (motor_type == 'D' || motor_type == 'd') // attach to DC motors controller
+              dc_motors_controller_TB6612FNG.add_sensor(motor_index, POTENTIOMETER, sensor_index);
+            i += 2;
+          }
+          else if (tmp_str[j] == 'B' || tmp_str[j] == 'b') {
+            int sensor_index;
+            sscanf(tmp_str + j + 1, "%d", &sensor_index);
+            if (motor_type == 'S' || motor_type == 's') // attach to stepper motors controller
+              stepper_motors_controller.add_sensor(motor_index, BUTTON, sensor_index);
+            else if (motor_type == 'D' || motor_type == 'd') // attach to DC motors controller
+              dc_motors_controller_TB6612FNG.add_sensor(motor_index, BUTTON, sensor_index);
+            i += 2;
+          }
+          else if (tmp_str[j] == 'I' || tmp_str[j] == 'i') {
+            int sensor_index;
+            sscanf(tmp_str + j + 1, "%d", &sensor_index);
+            if (motor_type == 'S' || motor_type == 's') // attach to stepper motors controller
+              stepper_motors_controller.add_sensor(motor_index, INFRARED, sensor_index);
+            else if (motor_type == 'D' || motor_type == 'd') // attach to DC motors controller
+              dc_motors_controller_TB6612FNG.add_sensor(motor_index, INFRARED, sensor_index);
+            i += 2;
+          }
+          else
+            i++;
+          j++;
+        }
+        i++;
+        continue;
+      }
+
+      if (tmp_str[i] == 'G' || tmp_str[i] == 'g') { // for debugging purpose
+        if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's') { // gets stepper motor speed and acceleration
+          int motor_index;
+          float motor_speed, motor_acceleration;
+          sscanf(tmp_str + i + 2, "%d", &motor_index);
+          stepper_motors_controller.get_speed_and_acceleration(motor_index, &motor_speed, &motor_acceleration);
+          sprintf(serial_out, "GS%d %d %d#", motor_index, (int)motor_speed, (int)motor_acceleration);
+          i += 4;
+        }
+        else if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd') { // gets stepper motor speed and acceleration
+          int motor_index;
+          byte motor_speed;
+          sscanf(tmp_str + i + 2, "%d", &motor_index);
+          dc_motors_controller_TB6612FNG.get_speed(motor_index, &motor_speed);
+          sprintf(serial_out, "GD%d %d#", motor_index, motor_speed);
+          i += 4;
+        }
+        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, pot_dir;
+          byte pot_pin;
+          sscanf(tmp_str + i + 2, "%d", &pot_index);
+          potentiometers_controller.get_params(pot_index, &pot_pin, &pot_min, &pot_max, &pot_home, &pot_dir);
+          sprintf(serial_out, "GP%d %d %d %d %d %d#", pot_index, (int)pot_pin, pot_min, pot_max, pot_home, pot_dir);
+          i += 5;
+        }
+        else if (tmp_str[i + 1] == 'U' || tmp_str[i + 1] == 'u') { // get potentiometer min max home
+          int ultrasound_index;
+          byte trig_pin, echo_pin;
+          sscanf(tmp_str + i + 2, "%d", &ultrasound_index);
+          ultrasonic_sensors_controller.get_sensor_pins(ultrasound_index, &trig_pin, &echo_pin);
+          sprintf(serial_out, "GU%d %d %d#", ultrasound_index, trig_pin, echo_pin);
+          i += 4;
+        }
+        else
+          i++;// incomplete string
+        continue;
+      }
+      // test connection
+      if (tmp_str[i] == 'T' || tmp_str[i] == 't') {
+        sprintf(serial_out, "T#");
+        i += 2;
+        continue;
+      }
+      // version number
+      if (tmp_str[i] == 'V' || tmp_str[i] == 'v') {
+        sprintf(serial_out, "%s#", firmware_version);
+        i += 2;
+        continue;
+      }
+
+      // create something
+      if (tmp_str[i] == 'C' || tmp_str[i] == 'c') {
+        if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's') { // create a list of stepper motors
+          if (!stepper_motors_controller.is_running()) {
+            int num_motors = 0;
+
+            int num_consumed = 0;
+            sscanf(tmp_str + i + 3, "%d%n", &num_motors, &num_consumed);
+
+            int num_consumed_total = 3 + num_consumed;
+            stepper_motors_controller.set_num_motors(num_motors);
+            for (int k = 0; k < num_motors; k++) {
+              int _step_pin, _dir_pin, _enable_pin;
+              sscanf(tmp_str + i + num_consumed_total, "%d%d%d%n", &_dir_pin, &_step_pin, &_enable_pin, &num_consumed);
+              stepper_motors_controller.set_pins(k, _dir_pin, _step_pin, _enable_pin);
+              num_consumed_total += num_consumed + 1;
             }
+            stepper_motors_controller.disable_all();
+            sprintf(serial_out, "CS#");
+            i += num_consumed_total;
+          }
+        }
+        else if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd') { // create a list of DC motors
+          if (!dc_motors_controller_TB6612FNG.is_running()) {
+            int num_motors = 0;
+
+            int num_consumed = 0;
+            sscanf(tmp_str + i + 3, "%d%n", &num_motors, &num_consumed);
+
+            int num_consumed_total = 3 + num_consumed;
+            dc_motors_controller_TB6612FNG.set_num_motors(num_motors);
+            for (int k = 0; k < num_motors; k++) {
+              int pwm_pin, dir_pin1, dir_pin2, enable_pin;
+              sscanf(tmp_str + i + num_consumed_total, "%d%d%d%d%n", &pwm_pin, &dir_pin1, &dir_pin2, &enable_pin, &num_consumed);
+              dc_motors_controller_TB6612FNG.set_motor_pins(k, pwm_pin, dir_pin1, dir_pin2, enable_pin);
+              num_consumed_total += num_consumed + 1;
+            }
+
+            sprintf(serial_out, "CD#");
+            i += num_consumed_total;
+          }
+        }
+        else if (tmp_str[i + 1] == 'U' || tmp_str[i + 1] == 'u') { // create a list of ultrasonic sensors
+
+          int num_sonars = 0;
+
+          int num_consumed = 0;
+          sscanf(tmp_str + i + 3, "%d%n", &num_sonars, &num_consumed);
+
+          int num_consumed_total = 3 + num_consumed;
+          ultrasonic_sensors_controller.set_num_sensors(num_sonars);
+          for (int k = 0; k < num_sonars; k++) {
+            int _trig_pin, _echo_pin;
+            sscanf(tmp_str + i + num_consumed_total, "%d%d%n", &_trig_pin, &_echo_pin, &num_consumed);
+            ultrasonic_sensors_controller.set_sensor_pins(k, _trig_pin, _echo_pin);
+            num_consumed_total += num_consumed + 1;
+          }
+
+          sprintf(serial_out, "CU#");
+          i += num_consumed_total;
+        }
+        else if (tmp_str[i + 1] == 'P' || tmp_str[i + 1] == 'p') { // create a list of potentiometers
+
+          int num_potentiometers = 0;
+
+          int num_consumed = 0;
+          sscanf(tmp_str + i + 3, "%d%n", &num_potentiometers, &num_consumed);
+
+          int num_consumed_total = 3 + num_consumed;
+          potentiometers_controller.set_num_sensors(num_potentiometers);
+          for (int k = 0; k < num_potentiometers; k++) {
+            int _out_pin;
+            int _low, _high, _home, _direction;
+            sscanf(tmp_str + i + num_consumed_total, "%d%d%d%d%d%n", &_out_pin, &_low, &_high, &_home, &_direction, &num_consumed);
+            potentiometers_controller.set_params(k, _out_pin, _low, _high, _home, _direction);
+            num_consumed_total += num_consumed + 1;
+          }
+
+          sprintf(serial_out, "CP#");
+          i += num_consumed_total;
+        }
+        else if (tmp_str[i + 1] == 'I' || tmp_str[i + 1] == 'i') { // create a list of infrared sensors
+
+          int num_infrareds = 0;
+
+          int num_consumed = 0;
+          sscanf(tmp_str + i + 3, "%d%n", &num_infrareds, &num_consumed);
+
+          int num_consumed_total = 3 + num_consumed;
+          infrared_sensors_controller.set_num_sensors(num_infrareds);
+          for (int k = 0; k < num_infrareds; k++) {
+            int out_pin;
+            int min_pos, max_pos, home_pos, _direction;
+            int num_read = sscanf(tmp_str + i + num_consumed_total, "%d%d%d%d%d%n", &out_pin, &min_pos, &max_pos, &home_pos, &_direction, &num_consumed);
+            if (num_read == 5)
+              infrared_sensors_controller.set_params(k, out_pin, min_pos, max_pos, home_pos, _direction);
             else
-              i++;// error on incomplete string (does nothing)
+              sprintf(serial_out, "E#");
+            num_consumed_total += num_consumed + 1;
+          }
+          sprintf(serial_out, "CI#");
+          i += num_consumed_total;
+        }
+        else if (tmp_str[i + 1] == 'B' || tmp_str[i + 1] == 'b') { // create a list of button sensors
+
+          int num_buttons = 0;
+
+          int num_consumed = 0;
+          sscanf(tmp_str + i + 3, "%d%n", &num_buttons, &num_consumed);
+
+          int num_consumed_total = 3 + num_consumed;
+          buttons_controller.set_num_sensors(num_buttons);
+          for (int k = 0; k < num_buttons; k++) {
+            int _pin;
+            sscanf(tmp_str + i + num_consumed_total, "%d%n", &_pin, &num_consumed);
+            buttons_controller.set_params(k, _pin);
+            num_consumed_total += num_consumed + 1;
+          }
+          sprintf(serial_out, "CB#");
+          i += num_consumed_total;
         }
         else
-          i++; // incomplete string
+          i++; // incomplete string
+        continue;
       }
       else
-          if (tmp_str[i] == 'P' || tmp_str[i] == 'p'){// potentiometer
-            int sensor_index;
-            sscanf(tmp_str + i + 1, "%d", &sensor_index);
-            int sensor_value = potentiometers_controller.get_position(sensor_index);
-            sprintf(serial_out, "P%d %d#", sensor_index, sensor_value);
-            i += 2;
-          }
-        else
-          if (tmp_str[i] == 'U' || tmp_str[i] == 'u'){// ultrasonic
-            int sensor_index;
-            sscanf(tmp_str + i + 1, "%d", &sensor_index);
-            ultrasonic_sensors_controller.trigger(sensor_index);
-            //sprintf(serial_out, "U%d %d#", sensor_index, sensor_value);
-
-            i += 2;
-          }
-        else
-          if (tmp_str[i] == 'I' || tmp_str[i] == 'i'){// infrared
-            int sensor_index;
-            sscanf(tmp_str + i + 1, "%d", &sensor_index);
-            int sensor_value = infrared_sensors_controller.get_signal_strength(sensor_index);
-            sprintf(serial_out, "I%d %d#", sensor_index, sensor_value);
-            i += 2;
-          }
-        else
-        if (tmp_str[i] == 'D' || tmp_str[i] == 'd'){// disables motor
-          int motor_index;
-          if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's'){// disables stepper motor
-            sscanf(tmp_str + i + 2, "%d", &motor_index);
-            stepper_motors_controller.disable(motor_index);
-            sprintf(serial_out, "DS%d#", motor_index);
-          }
-          else
-            if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd'){// disables DC motor
-              sscanf(tmp_str + i + 2, "%d", &motor_index);
-              dc_motors_controller_TB6612FNG.disable(motor_index);
-              sprintf(serial_out, "DD%d#", motor_index);
-            }
-          i += 4;
-        }
-        else
-          if (tmp_str[i] == 'L' || tmp_str[i] == 'l'){// locks motor
-            int motor_index;
-            sscanf(tmp_str + i + 1, "%d", &motor_index);
-            stepper_motors_controller.lock(motor_index);
-            sprintf(serial_out, "L%d#", motor_index);
-            i += 2;
-          }
-        else
-          if (tmp_str[i] == 'H' || tmp_str[i] == 'h'){// go home
-            int motor_index;
-            if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's'){// go stepper home
-              sscanf(tmp_str + i + 2, "%d", &motor_index);
-              stepper_motors_controller.go_home(motor_index, &potentiometers_controller);
-              sprintf(serial_out, "HS%d#", motor_index);
-            }
-            else
-              if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd'){// go stepper home
-                sscanf(tmp_str + i + 2, "%d", &motor_index);
-                dc_motors_controller_TB6612FNG.go_home(motor_index, &buttons_controller);
-                sprintf(serial_out, "HD%d#", motor_index);
-              }
-            is_command_running = 1;
-            i += 4;
-          }
-          else
-          if (tmp_str[i] == 'S' || tmp_str[i] == 's'){ // sets something
-            if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's'){ // stepper motor speed and acceleration
-              int motor_index;
-              int motor_speed, motor_acceleration;
-              sscanf(tmp_str + i + 2, "%d%d%d", &motor_index, &motor_speed, &motor_acceleration);
-              stepper_motors_controller.set_speed_and_acceleration(motor_index, motor_speed, motor_acceleration);
-              i += 5;
-            }
-            else
-              if (tmp_str[i + 1] == 'P' || tmp_str[i + 1] == 'p'){ // potentiometer min max home
-                int pot_index, pot_min, pot_max, pot_home, pot_pin, pot_dir;
-                sscanf(tmp_str + i + 2, "%d%d%d%d%d%d", &pot_index, &pot_pin, &pot_min, &pot_max, &pot_home, &pot_dir);
-                potentiometers_controller.set_params(pot_index, pot_pin, pot_min, pot_max, pot_home, pot_dir);
-                i += 7;
-            }
-            else
-              if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd'){ // dc motor speed
-                int motor_index;
-                int motor_speed;
-                sscanf(tmp_str + i + 2, "%d%d", &motor_index, &motor_speed);
-                dc_motors_controller_TB6612FNG.set_speed(motor_index, motor_speed);
-                i += 5;
-              }
-
-          }
-        else
-          if (tmp_str[i] == 'A' || tmp_str[i] == 'a'){// attach sensors to motors
-            int motor_index, num_sensors;
-            char motor_type = tmp_str[i];
-            sscanf(tmp_str + i + 2, "%d%d", &motor_index, &num_sensors);
-            if (motor_type == 'S' || motor_type == 's') // attach to stepper motors controller
-              stepper_motors_controller.set_num_attached_sensors(motor_index, num_sensors);
-            else
-              if (motor_type == 'D' || motor_type == 'd') // attach to DC motors controller
-                dc_motors_controller_TB6612FNG.set_num_attached_sensors(motor_index, num_sensors);
-
-            // now I have to add sensors one by one
-            int j = i + 4;
-            i += 5;
-            while (j < str_length){
-              if (tmp_str[j] == 'P' || tmp_str[j] == 'p'){
-                int sensor_index;
-                sscanf(tmp_str + j + 1, "%d", &sensor_index);
-                if (motor_type == 'S' || motor_type == 's') // attach to stepper motors controller
-                  stepper_motors_controller.add_sensor(motor_index, POTENTIOMETER, sensor_index);
-                else
-                  if (motor_type == 'D' || motor_type == 'd') // attach to DC motors controller
-                    dc_motors_controller_TB6612FNG.add_sensor(motor_index, POTENTIOMETER, sensor_index);
-                i += 2;
-              }
-              else
-                if (tmp_str[j] == 'B' || tmp_str[j] == 'b'){
-                  int sensor_index;
-                  sscanf(tmp_str + j + 1, "%d", &sensor_index);
-                  if (motor_type == 'S' || motor_type == 's') // attach to stepper motors controller
-                    stepper_motors_controller.add_sensor(motor_index, BUTTON, sensor_index);
-                  else
-                    if (motor_type == 'D' || motor_type == 'd') // attach to DC motors controller
-                      dc_motors_controller_TB6612FNG.add_sensor(motor_index, BUTTON, sensor_index);
-                  i += 2;
-                }
-                else
-                  i++;
-              j++;
-            }
-            i++;
-          }
-          else
-          if (tmp_str[i] == 'G' || tmp_str[i] == 'g'){// for debugging purpose
-            if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's'){ // gets stepper motor speed and acceleration
-              int motor_index;
-              float motor_speed, motor_acceleration;
-              sscanf(tmp_str + i + 2, "%d", &motor_index);
-              stepper_motors_controller.get_speed_and_acceleration(motor_index, &motor_speed, &motor_acceleration);
-              sprintf(serial_out, "GS%d %d %d#", motor_index, (int)motor_speed, (int)motor_acceleration);
-              i += 4;
-            }
-            else
-              if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd'){ // gets stepper motor speed and acceleration
-                int motor_index;
-                byte motor_speed;
-                sscanf(tmp_str + i + 2, "%d", &motor_index);
-                dc_motors_controller_TB6612FNG.get_speed(motor_index, &motor_speed);
-                sprintf(serial_out, "GD%d %d#", motor_index, motor_speed);
-                i += 4;
-              }
-              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, pot_dir;
-                  byte pot_pin;
-                  sscanf(tmp_str + i + 2, "%d", &pot_index);
-                  potentiometers_controller.get_params(pot_index, &pot_pin, &pot_min, &pot_max, &pot_home, &pot_dir);
-                  sprintf(serial_out, "GP%d %d %d %d %d %d#", pot_index, (int)pot_pin, pot_min, pot_max, pot_home, pot_dir);
-                  i += 5;
-                }
-                else
-                  if (tmp_str[i + 1] == 'U' || tmp_str[i + 1] == 'u'){ // get potentiometer min max home
-                    int ultrasound_index;
-                    byte trig_pin, echo_pin;
-                    sscanf(tmp_str + i + 2, "%d", &ultrasound_index);
-                    ultrasonic_sensors_controller.get_sensor_pins(ultrasound_index, &trig_pin, &echo_pin);
-                    sprintf(serial_out, "GU%d %d %d#", ultrasound_index, trig_pin, echo_pin);
-                    i += 4;
-                  }
-                  else
-                    i++;// incomplete string
-        }
-        else
-         if (tmp_str[i] == 'T' || tmp_str[i] == 't'){// test connection
-           sprintf(serial_out, "T#");
-           i += 2;
-         }
-         else
-         if (tmp_str[i] == 'V' || tmp_str[i] == 'v'){// version number
-           sprintf(serial_out, "%s#", firmware_version);
-           i += 2;
-         }
-         else
-           if (tmp_str[i] == 'C' || tmp_str[i] == 'c'){// create something
-             if (tmp_str[i + 1] == 'S' || tmp_str[i + 1] == 's'){// create a list of stepper motors
-               if (!stepper_motors_controller.is_running()){
-                 int num_motors = 0;
-
-                 int num_consumed = 0;
-                 sscanf(tmp_str + i + 3, "%d%n", &num_motors, &num_consumed);
-
-                 int num_consumed_total = 3 + num_consumed;
-                 stepper_motors_controller.set_num_motors(num_motors);
-                 for (int k = 0; k < num_motors; k++){
-                   int _step_pin, _dir_pin, _enable_pin;
-                   sscanf(tmp_str + i + num_consumed_total, "%d%d%d%n", &_dir_pin, &_step_pin, &_enable_pin, &num_consumed);
-                   stepper_motors_controller.set_pins(k, _dir_pin, _step_pin, _enable_pin);
-                   num_consumed_total += num_consumed + 1;
-                 }
-                 stepper_motors_controller.disable_all();
-                 sprintf(serial_out, "CS#");
-                 i += num_consumed_total;
-               }
-             }
-             else
-             if (tmp_str[i + 1] == 'D' || tmp_str[i + 1] == 'd'){// create a list of DC motors
-               if (!dc_motors_controller_TB6612FNG.is_running()){
-                 int num_motors = 0;
-
-                 int num_consumed = 0;
-                 sscanf(tmp_str + i + 3, "%d%n", &num_motors, &num_consumed);
-
-                 int num_consumed_total = 3 + num_consumed;
-                 dc_motors_controller_TB6612FNG.set_num_motors(num_motors);
-                 for (int k = 0; k < num_motors; k++){
-                   int pwm_pin, dir_pin1, dir_pin2, enable_pin;
-                   sscanf(tmp_str + i + num_consumed_total, "%d%d%d%d%n", &pwm_pin, &dir_pin1, &dir_pin2, &enable_pin, &num_consumed);
-                   dc_motors_controller_TB6612FNG.set_motor_pins(k, pwm_pin, dir_pin1, dir_pin2, enable_pin);
-                   num_consumed_total += num_consumed + 1;
-                 }
-
-                 sprintf(serial_out, "CD#");
-                 i += num_consumed_total;
-               }
-             }
-             else
-               if (tmp_str[i + 1] == 'U' || tmp_str[i + 1] == 'u'){// create a list of ultrasonic sensors
-
-                 int num_sonars = 0;
-
-                 int num_consumed = 0;
-                 sscanf(tmp_str + i + 3, "%d%n", &num_sonars, &num_consumed);
-
-                 int num_consumed_total = 3 + num_consumed;
-                 ultrasonic_sensors_controller.set_num_sensors(num_sonars);
-                 for (int k = 0; k < num_sonars; k++){
-                   int _trig_pin, _echo_pin;
-                   sscanf(tmp_str + i + num_consumed_total, "%d%d%n", &_trig_pin, &_echo_pin, &num_consumed);
-                   ultrasonic_sensors_controller.set_sensor_pins(k, _trig_pin, _echo_pin);
-                   num_consumed_total += num_consumed + 1;
-                 }
-
-                 sprintf(serial_out, "CU#");
-                 i += num_consumed_total;
-             }
-             else
-               if (tmp_str[i + 1] == 'P' || tmp_str[i + 1] == 'p'){// create a list of potentiometers
-
-                 int num_potentiometers = 0;
-
-                 int num_consumed = 0;
-                 sscanf(tmp_str + i + 3, "%d%n", &num_potentiometers, &num_consumed);
-
-                 int num_consumed_total = 3 + num_consumed;
-                 potentiometers_controller.set_num_sensors(num_potentiometers);
-                 for (int k = 0; k < num_potentiometers; k++){
-                   int _out_pin;
-                   int _low, _high, _home, _direction;
-                   sscanf(tmp_str + i + num_consumed_total, "%d%d%d%d%d%n", &_out_pin, &_low, &_high, &_home, &_direction, &num_consumed);
-                   potentiometers_controller.set_params(k, _out_pin, _low, _high, _home, _direction);
-                   num_consumed_total += num_consumed + 1;
-                 }
-
-                 sprintf(serial_out, "CP#");
-                 i += num_consumed_total;
-               }
-             else
-               if (tmp_str[i + 1] == 'I' || tmp_str[i + 1] == 'i'){// create a list of infrared sensors
-
-                 int num_infrareds = 0;
-
-                 int num_consumed = 0;
-                 sscanf(tmp_str + i + 3, "%d%n", &num_infrareds, &num_consumed);
-
-                 int num_consumed_total = 3 + num_consumed;
-                 infrared_sensors_controller.set_num_sensors(num_infrareds);
-                 for (int k = 0; k < num_infrareds; k++){
-                   int out_pin;
-                   int min_pos, max_pos, home_pos, _direction;
-                   sscanf(tmp_str + i + num_consumed_total, "%d%d%d%d%d%n", &out_pin, &min_pos, &max_pos, &home_pos, &_direction, &num_consumed);
-                   infrared_sensors_controller.set_params(k, out_pin, min_pos, max_pos, home_pos, _direction);
-                   num_consumed_total += num_consumed + 1;
-                 }
-                 sprintf(serial_out, "CI#");
-                 i += num_consumed_total;
-               }
-             else
-               if (tmp_str[i + 1] == 'B' || tmp_str[i + 1] == 'b'){// create a list of button sensors
-
-                 int num_buttons = 0;
-
-                 int num_consumed = 0;
-                 sscanf(tmp_str + i + 3, "%d%n", &num_buttons, &num_consumed);
-
-                 int num_consumed_total = 3 + num_consumed;
-                 buttons_controller.set_num_sensors(num_buttons);
-                 for (int k = 0; k < num_buttons; k++){
-                   int _pin;
-                   sscanf(tmp_str + i + num_consumed_total, "%d%n", &_pin, &num_consumed);
-                   buttons_controller.set_params(k, _pin);
-                   num_consumed_total += num_consumed + 1;
-                 }
-                 sprintf(serial_out, "CB#");
-                 i += num_consumed_total;
-               }
-               else
-                 i++; // incomplete string
-         }
-         else
-           i++;// incomplete string
+        i++;// incomplete string
     }
     else
       i++;
@@ -448,73 +462,73 @@
 }
 //--------------------------------------------------------------------------------------------
 //Main loop
-void loop()
+void loop()
 {
   char serial_out[100];

-// check to see if there are new results from ultrasonic sensor
+  // check to see if there are new results from ultrasonic sensor
   ultrasonic_sensors_controller.update_results(serial_out);
   if (serial_out[0])
     Serial.write(serial_out);
-
+
   if (Serial.available() || current_buffer[0]) {
     int num_read = 0;
     char serial_buffer[65];
-
+
     //num_read = Serial.readBytes(serial_buffer, 64); //Read up to 64 bytes
-
+
     int incomingByte = Serial.read();
-      if (incomingByte != -1){
+    if (incomingByte != -1) {
       serial_buffer[0] = incomingByte;
       num_read = 1;
     }
     serial_buffer[num_read] = 0;// terminate the string
-    if (serial_buffer[0] || current_buffer[0]){
+    if (serial_buffer[0] || current_buffer[0]) {
       if (serial_buffer[0])
         strcat(current_buffer, serial_buffer);
-
-      #ifdef DEBUG
-        Serial.write("initial buffer is=");
-        Serial.write(current_buffer);
-        Serial.println();
-      #endif
-
+
+#ifdef DEBUG
+      Serial.write("initial buffer is=");
+      Serial.write(current_buffer);
+      Serial.println();
+#endif
+
       // parse from the beginning until I find a M, D, L, S, A, P, B, U, G, T
       int current_buffer_length = strlen(current_buffer);
       for (int i = 0; i < current_buffer_length; i++)
-        if ((current_buffer[i] >= 'A' && current_buffer[i] <= 'Z') || (current_buffer[i] >= 'a' && current_buffer[i] <= 'z')){// a command
+        if ((current_buffer[i] >= 'A' && current_buffer[i] <= 'Z') || (current_buffer[i] >= 'a' && current_buffer[i] <= 'z')) { // a command
           // find the terminal character #
           int j = current_buffer_length - 1;
           for (; j > i && current_buffer[j] != '#'; j--);// parse (from the end) until I find the termination char
-          if (j > i){
-
-              #ifdef DEBUG
-                char tmp_str[64];
-                strncpy(tmp_str, current_buffer + i, j - i);
-                tmp_str[j - i] = 0;
-                Serial.write("current command is=");
-                Serial.write(tmp_str);
-                Serial.println();
-              #endif
-
-             parse_and_execute_commands(current_buffer + i, j - i, serial_out);
-             if (serial_out[0])
-               Serial.write(serial_out);
-
-
-              // remove the current executed command
-              strcpy(current_buffer, current_buffer + j + 1);// not sure if this is good due to overlaps
-
-              #ifdef DEBUG
-                Serial.write("buffer left=");
-                Serial.write(current_buffer);
-                Serial.write("\n----------------\n");
-                //Serial.println(strlen(current_buffer)); // buffer length
-              #endif
+          if (j > i) {
+
+#ifdef DEBUG
+            char tmp_str[64];
+            strncpy(tmp_str, current_buffer + i, j - i);
+            tmp_str[j - i] = 0;
+            Serial.write("current command is=");
+            Serial.write(tmp_str);
+            Serial.println();
+#endif
+
+            parse_and_execute_commands(current_buffer + i, j - i, serial_out);
+            if (serial_out[0])
+              Serial.write(serial_out);
+
+
+            // remove the current executed command
+            strcpy(current_buffer, current_buffer + j + 1);// not sure if this is good due to overlaps
+
+#ifdef DEBUG
+            Serial.write("buffer left=");
+            Serial.write(current_buffer);
+            Serial.write("\n----------------\n");
+            //Serial.println(strlen(current_buffer)); // buffer length
+#endif

             break; //for i
           }
-          else{// the string is not completed ... so I must wait for more...
+          else { // the string is not completed ... so I must wait for more...
             break; // for i
           }
         }
@@ -528,8 +542,8 @@
   if (serial_out[0])
     Serial.write(serial_out);

- //   Serial.print("freeMemory()=");
- // Serial.println(freeMemory());
+  //   Serial.print("freeMemory()=");
+  // Serial.println(freeMemory());

   //delay(1000);
 }


Double segment for value greater than nine

--- camera-slider.ino
+++ camera-slider.ino
@@ -1,10 +1,9 @@
-#define MAX_SPEED 120
 #define WHEEL_RADIUS 10
-#define RAIL_LENGTH 100 // cm
+#define TRANSLATE_TIME 2 // second
+#define COUNTDOWN_TIME 35 // second

 // set items
 int buttonPin = 2;
-int ledPin = 3;
 int motorPin = 9;

 // set shift register
@@ -12,104 +11,150 @@
 int clock = 6;
 int latch = 7;

-double currentPosition; // position of camera on rails
+// set segment
+int alim_unite = 11;
+int alim_dizaine = 12;
+
+float currentPosition; // position of camera on rails
+boolean state;
 long time;

+void displayNumber(char nb);
+void countdown(int from);
+void startTraveling();
+void stopTraveling();
+void shiftNumber(short nb);

 void setup()
 {
-  pinMode(ledPin, OUTPUT);
   pinMode(buttonPin, INPUT);
   pinMode(motorPin, OUTPUT);
+
+  pinMode(alim_unite, OUTPUT);
+  pinMode(alim_dizaine, OUTPUT);

   pinMode(data, OUTPUT);
   pinMode(clock, OUTPUT);
   pinMode(latch, OUTPUT);

+  state = LOW; // Allow timelapse start - at first, stop
   currentPosition = 0;
-  digitalWrite(ledPin, HIGH);
-
 }

 void loop()
 {
-  countdown();
+  if(state) {
+    countdown(COUNTDOWN_TIME);
+    startTraveling();
+    delay(TRANSLATE_TIME * 1000);
+    stopTraveling();
+  } else {
+    displayNumber(-2); // TODO: must display letter C instead of T
+  }

   if(digitalRead(buttonPin) == HIGH) {
-    startTraveling();
-  } else {
-    if((millis() - time) > 100) {
-      stopTraveling();
-      time = millis();
+    state = HIGH;
+    } else {
+      if((millis() - time) > 100) {
+        time = millis();
+      }
     }
-  }
 }

 void displayNumber(char nb)
 {
-  digitalWrite(latch, LOW);
-  short val;
-  // TODO : Maybe could do better... It's late, my brain doesn't work well
-  switch (nb) {
-      case 0:
-        val = 191;
-        break;
-      case 1:
-        val = 249;
-        break;
-      case 2:
-        val = 164;
-        break;
-      case 3:
-        val = 48;
-        break;
-      case 4:
-        val = 25;
-        break;
-      case 5:
-        val = 18;
-        break;
-      case 6:
-        val = 2;
-        break;
-      case 7:
-        val = 248;
-        break;
-      case 8:
-        val = 0;
-        break;
-      case 9:
-        val = 16;
-        break;
-
-      default:
-        val = 64;
+  long currentTime;
+  char unite = 0, dizaine = 0;
+
+  if(nb > 9) {
+    dizaine = nb / 10;
   }
-  shiftOut(data, clock, MSBFIRST, val);
-  digitalWrite(latch, HIGH);
+
+  unite = nb - (dizaine * 10);
+
+  currentTime = millis();
+  // set display to be able to see number
+  while((millis() - currentTime) < 1000) {
+    digitalWrite(alim_dizaine, HIGH);
+    shiftNumber(dizaine);
+    digitalWrite(alim_unite, LOW);
+    delay(10);
+
+    digitalWrite(alim_dizaine, LOW);
+    shiftNumber(unite);
+    digitalWrite(alim_unite, HIGH);
+    delay(10);
+  }
 }

-void countdown()
+void countdown(int from)
 {
-  for( short i = 10; i > 0; i-- ) {
+  for( short i = from; i > 0; i-- ) {
     displayNumber(i);
-    delay(1000);
   }
+  displayNumber(-1); // T letter for 'translation'
 }

 void startTraveling()
 {
-  if(currentPosition < RAIL_LENGTH)
-  {
-    currentPosition += 0.001; // TODO ajouter valeur perimetre roue
-    analogWrite(motorPin, MAX_SPEED);
-  } else {
-    digitalWrite(ledPin, LOW);
-  }
+    currentPosition += 0.001; // TODO define radius of wheel
+    digitalWrite(motorPin, HIGH);
+
+    //TODO: add detector of collision to stop train
 }

 void stopTraveling()
 {
-  analogWrite(motorPin, LOW);
+  digitalWrite(motorPin, LOW);
 }

+void shiftNumber(short nb)
+{
+  digitalWrite(latch, LOW);
+  short val;
+
+  // TODO : Maybe could do better... It's late, my brain doesn't work well
+  switch (nb) {
+    case 0:
+      val = 192;
+      break;
+    case 1:
+      val = 249;
+      break;
+    case 2:
+      val = 164;
+      break;
+    case 3:
+      val = 48;
+      break;
+    case 4:
+      val = 25;
+      break;
+    case 5:
+      val = 18;
+      break;
+    case 6:
+      val = 2;
+      break;
+    case 7:
+      val = 248;
+      break;
+    case 8:
+      val = 0;
+      break;
+    case 9:
+      val = 16;
+      break;
+    case -1: // t letter
+      val = 135;
+      break;
+    case -2: // c letter
+      val = 198;
+      break;
+    default:
+      val = 192;
+  }
+
+  shiftOut(data, clock, MSBFIRST, val);
+  digitalWrite(latch, HIGH);
+}


fix pull down for 1284 interrupt pins, and make serial printing faster

--- super_freq/super_freq.ino
+++ super_freq/super_freq.ino
@@ -20,14 +20,16 @@

 void setup() {
     if (DEBUG) {
-        Serial.begin(9600);
+        Serial.begin(115200);
     }

     // pull down for palette change interrupt pin
-    digitalWrite(2, LOW);
+    pinMode(10, INPUT);
+    digitalWrite(10, LOW);

     // pull down for pattern change interrupt pin
-    digitalWrite(2, LOW);
+    pinMode(11, INPUT);
+    digitalWrite(11, LOW);

     // setup interrupt 0 (digital pin 2) to detect changed palette
     // rotary switch position


added non-blocking handshake to esp8266

added non-blocking handshake to esp8266

--- embedded/esp8266/esp8266/esp8266.ino
+++ embedded/esp8266/esp8266/esp8266.ino
@@ -19,7 +19,6 @@

 #define HUB_SIZE 4
 #include <IoTaDeviceHub.h>
-
 #include "iota_defines.h"
 #include "heartbeat.h"
 #include "LedSerialMaster.h"
@@ -34,8 +33,31 @@
 Heartbeat hb;
 LedSerialMaster led(&Serial, MAX_CLIENTS);

-
-std::pair<int, WiFiClient> *unAuthClients;
+long uuid;
+
+
+
+//enum for what an authednticated client is waiting to recieve next
+enum connStatusEnum
+{
+	NOT_CONNECTED,
+	FIRST_CONNECT,
+	MAGIC_BYTE_RX,
+	CLIENT_ID_RX,
+	CONNECTED
+};
+
+enum unAuthEnum
+{
+	timeIn,
+	authProg,
+	unAuthClient
+};
+//Tracking unauthenticated connections,
+//@1st, int = time connected in micros
+//@2nd, connStatusEnum = what stage in connection the unAuthClient is in
+//@3rd, WiFIClient = unAuthClient in question
+std::tuple<uint, connStatusEnum, WiFiClient> *unAuthClients;

 int nextFreeSpot = 0;

@@ -43,9 +65,12 @@
 iota::Map<long, WiFiClient*> *clientMap;

 static const size_t bufferSize = 1024;
-static uint8_t sbuf[bufferSize];
+static uint8_t rxBuf[bufferSize];
+static uint8_t txBuf[bufferSize];

 std::pair<int, int> tMarkers;
+
+

 void setup() {
@@ -61,17 +86,17 @@
 	byte mac[6];
 	WiFi.macAddress(mac);
 	Serial.printf("Mac address: %h %h %h %h %h %h \n", mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]);
-	Serial.printf("Chip id: %d", ESP.getChipId());
-	long uuid = (ESP.getChipId() << 32 | mac[0] << 24 | mac[1] << 16 | mac[2] << 9 | mac[3]);
+	Serial.printf("Chip id: %d\n", ESP.getChipId());
+	uuid = (ESP.getChipId() << 32 | mac[0] << 24 | mac[1] << 16 | mac[2] << 9 | mac[3]);
 	Serial.printf("UUID : %l", uuid);

 	hub = new IoTaDeviceHub(uuid);
 	hub->addFunc(&hb);
 	hub->addFunc(&led);

-	unAuthClients = new std::pair<int, WiFiClient>[MAX_UNAUTH_CLIENTS];
+	unAuthClients = new std::tuple<uint, connStatusEnum, WiFiClient>[MAX_UNAUTH_CLIENTS];
 	for (int i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
-		unAuthClients[i].first = -1;
+		std::get<authProg>(unAuthClients[i]) = NOT_CONNECTED;
 	}

 	clientMap = new iota::Map<long, WiFiClient*>(10);
@@ -92,22 +117,22 @@

 		//uint8_t msgBuffer[256];
-		sbuf[0] = c->read();
-		sbuf[1] = c->read();
-		short msgLen = (sbuf[0] << 8 |sbuf[1]);
+		rxBuf[0] = c->read();
+		rxBuf[1] = c->read();
+		short msgLen = (rxBuf[0] << 8 |rxBuf[1]);
 		//Fixed read in length here, huge speed increase due to fixing timeout!
-		c->readBytes(&sbuf[2], msgLen);
-
-		long source = (sbuf[2] << 56 | sbuf[3] << 48 | sbuf[4] << 40 | sbuf[5] << 32 | sbuf[6] << 24 | sbuf[7] << 16 | sbuf[8] << 8 | sbuf[9]);
-		long dest = (sbuf[10] << 56 | sbuf[11] << 48 | sbuf[12] << 40 | sbuf[13] << 32 | sbuf[14] << 24 | sbuf[15] << 16 | sbuf[16] << 8 | sbuf[17]);
-		short func = (sbuf[18] << 8 | sbuf[19]);
-		short size = (sbuf[20] << 8 | sbuf[21]);
+		c->readBytes(&rxBuf[2], msgLen);
+
+		long source = (rxBuf[2] << 56 | rxBuf[3] << 48 | rxBuf[4] << 40 | rxBuf[5] << 32 | rxBuf[6] << 24 | rxBuf[7] << 16 | rxBuf[8] << 8 | rxBuf[9]);
+		long dest = (rxBuf[10] << 56 | rxBuf[11] << 48 | rxBuf[12] << 40 | rxBuf[13] << 32 | rxBuf[14] << 24 | rxBuf[15] << 16 | rxBuf[16] << 8 | rxBuf[17]);
+		short func = (rxBuf[18] << 8 | rxBuf[19]);
+		short size = (rxBuf[20] << 8 | rxBuf[21]);
 		uint8_t * data = new uint8_t[size];
-		memcpy(data, &sbuf[22], size);
+		memcpy(data, &rxBuf[22], size);

 		//data is now stored inside DataCapsule, data can be freed
 		DataCapsule capsule(source, dest, func, size, data);
-		Serial.print("MEssage recieved from ");
+		Serial.print("Message recieved from ");
 		Serial.println(capsule.getSource());

 		delete data;
@@ -126,63 +151,117 @@

 void loop() {

-	// Check if a new client has connected
+	// Check if a new unAuthClient has connected
 	WiFiClient newClient = server.available();

 	/*
 	Connection process:
-		1. client appears at wifi server
-		2. read first byte transmitted by client connecting
-		3. if client sent MAGIC_BYTE (65) continue
+		1. unAuthClient appears at wifi server
+		2. read first byte transmitted by unAuthClient connecting
+		3. if unAuthClient sent MAGIC_BYTE (65) continue
 		4. send back magic byte+1
-		5. wait for client to send an empty data packet addressed for FID
+		5. wait for unAuthClient to send an empty data packet addressed for FID
 		6. add clientId to clientMap
-		7. enjoy your fancy new connected client!
+		7. enjoy your fancy new connected unAuthClient!
 	*/

+
+
+	//New unAuthClient, looop through unath waiting zone to find first empty
+	//spot and begin auth protocol
 	if (newClient) {
 		for (int i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
-			if (unAuthClients[i].first < 0)
+			if (std::get<authProg>(unAuthClients[i]) == NOT_CONNECTED)
 			{
 				Serial.print("New unauth client at ");
 				Serial.print(i);
 				int now = micros();
 				Serial.print(" t = ");
 				Serial.println(now);
-				unAuthClients[i].first = now;
-				unAuthClients[i].second = newClient;
+				std::get<timeIn>(unAuthClients[i]) = now;
+				std::get<authProg>(unAuthClients[i]) = FIRST_CONNECT;
+				std::get<unAuthClient>(unAuthClients[i]) = newClient;
 				i = MAX_UNAUTH_CLIENTS;
 			}
 		}
 	}

-	int tnow = micros();
-	int timeout_us = 4000000;
+	uint tnow = micros();
+	uint timeout_us = 2000000;
 	for (int i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
 		yield();
-		if (tnow - unAuthClients[i].first > timeout_us && unAuthClients[i].first > 0) {
+		if (tnow - std::get<timeIn>(unAuthClients[i]) > timeout_us && std::get<authProg>(unAuthClients[i]) != NOT_CONNECTED) {
+
+
 			//remove due to lack of connections
-			Serial.print("Removing client timeout ");
+			Serial.print("timeout ");
 			Serial.println(i);
-			unAuthClients[i].first = -1;
+			std::get<timeIn>(unAuthClients[i]) = 0;
+			std::get<authProg>(unAuthClients[i]) = NOT_CONNECTED;
+			std::get<unAuthClient>(unAuthClients[i]).stop();
 		}
-		else if(unAuthClients[i].first > 0)
+		else if(std::get<authProg>(unAuthClients[i]) != NOT_CONNECTED)
 		{
-			//Serial.print("Checking ");
-			//Serial.println(i);
-			//try to handshake
-			if (unAuthClients[i].second.available() > 0) {
-				uint8_t firstContact = unAuthClients[i].second.read();
-				Serial.print("Unauth sent: ");
-				Serial.println(firstContact);
-
-				if (firstContact == MAGIC_BYTE) {
-					Serial.println("Got first part of handshake, responding");
-					unAuthClients[i].second.write(MAGIC_BYTE + 1);
+			switch (std::get<authProg>(unAuthClients[i]))
+			{
+			case(FIRST_CONNECT):
+
+				if (std::get<unAuthClient>(unAuthClients[i]).available() > 0) {
+					Serial.print(i);
+					Serial.println(" sent something");
+					uint8_t firstContact = std::get<unAuthClient>(unAuthClients[i]).read();
+					Serial.print("Unauth sent: ");
+					Serial.println(firstContact);
+
+					if (firstContact == MAGIC_BYTE) {
+						std::get<authProg>(unAuthClients[i]) = MAGIC_BYTE_RX;
+					}
 				}
+				break;
+
+			case(MAGIC_BYTE_RX):
+				Serial.println("sending back magic byte + 1");
+				std::get<unAuthClient>(unAuthClients[i]).write(MAGIC_BYTE + 1);
+				std::get<authProg>(unAuthClients[i]) = CLIENT_ID_RX;
+
+				break;
+
+			case(CLIENT_ID_RX):
+				if (std::get<unAuthClient>(unAuthClients[i]).available() > 0) {
+					DataCapsule cap = createDataPacket(&std::get<unAuthClient>(unAuthClients[i]));
+					Serial.print("Connected to id ");
+					Serial.println(cap.getSource());
+
+					clientMap->put(cap.getSource(), &std::get<unAuthClient>(unAuthClients[i]));
+					std::get<authProg>(unAuthClients[i]) = CONNECTED;
+
+					DataCapsule outCap(uuid,cap.getSource(),FID_HUB,0,NULL);
+					size_t pLen = cap.getTcpPacketLength();
+					uint8_t bytes[pLen];
+
+					cap.createTcpPacket(bytes);
+					for (int i = 0; i < pLen; i++) {
+						Serial.print(" ");
+						Serial.print(bytes[i]);
+					}
+					Serial.println("<- empty capsule");
+					std::get<unAuthClient>(unAuthClients[i]).write(&bytes[0],pLen);
+
+				}
+
+				break;
+
+			case(CONNECTED): //client has been authenticated and moved to clientMap, time to clean up its spot
+				std::get<timeIn>(unAuthClients[i]) = 0;
+				std::get<authProg>(unAuthClients[i]) = NOT_CONNECTED;
+				Serial.print(i);
+				Serial.println(" has been cleaned");
+				break;
+			default:
+				break;
 			}
-
+
 		}
 	}

@@ -193,7 +272,7 @@

 	//get and broadcast state updates
 	//while broadcasts waiting
-	//tx to each attached client
+	//tx to each attached unAuthClient

 	while (hub->numCapsulesRemaining() > 0)
 	{


Revert "Convert serial communications port to a pointer so we can easily switch between ports."

This reverts commit 8afe9f7d0b82be5b729a1b7592cc51929de9a036.

--- OpenStage/OpenStage.ino
+++ OpenStage/OpenStage.ino
@@ -152,8 +152,7 @@
 //------------------------------------------------------------------------------------------------
 // * Enable/disable major OpenStage functions
 //
-bool doSerialInterface=1; //Set to 1 to communicate with the stage via a PC serial port.
-bool controlViaUSB=0; //Control stage via USB serial (disables verbose messages via this port)
+bool doSerialInterface=1; //Set to 1 to communicate with the stage via a PC serial port. See setup() for serial port IDs.
 bool doGamePad=1; //Set to 1 to enable PS3 DualShock as an input device
 bool doLCD=1; //Set to 1 to enable LCD character display

@@ -414,6 +413,7 @@

+
 //------------------------------------------------------------------------------------------------
 // * setup function
 // The setup function is run once when the microcontroller is powered on, reset, or programmed.
@@ -423,7 +423,6 @@
 // The setup function performs basic operations such as defining the DIO direction of each pin,
 // connecting to a serial device, etc.

-HardwareSerial *SerialComms;
 void setup() {

   //Initialise loop counters
@@ -436,18 +435,6 @@
   // during testing. [In future we will add the option for controlling the stage through
   // the USB port]
   Serial.begin(115200);
-  if (doSerialInterface){
-    if (!controlViaUSB){
-       Serial1.begin(115200);
-        SerialComms = &Serial1;
-         SerialComms->println("test");
-
-     } else {
-         SerialComms = &Serial;
-         SerialComms->println("test");
-
-     }
-  } //if doSerialInterface

@@ -581,7 +568,9 @@
     setupLCD();//Print axis names to LCD
   } //if doLCD

-
+  if (doSerialInterface){
+     Serial1.begin(115200);
+  } //if doSerialInterface
 }//End of setup function

@@ -657,7 +646,7 @@

   //Move based on serial commands
   if (doSerialInterface){
-    if (SerialComms->available()){
+    if (Serial1.available()){
         char ch=Serial1.read(); //read first character
         if (ch=='g') //Absolute and relative motion
           serialMove();


new LPG test

new LPG test

--- tests/LpgSerial/LpgSerial.ino
+++ tests/LpgSerial/LpgSerial.ino
@@ -1,58 +1,92 @@

 #include <Arduino.h>

-#define BitVal(data, y) ( (data>>y) & 1)
+#define LPG_INPUT 19
+#define LPG_TIMEOUT  8
+#define LPG_BITS 14
+#define LPG_BYTE_HIGH 6 // time for HIGH 1 byte
+#define LPG_TOLERANCE 1 // tolerance time

-const uint8_t pinInput = 17;
-
-boolean serial2Change = false;
-uint8_t serial2Length;
-boolean serial2Readed = false;
-uint8_t serial2Offset;
-unsigned long serial2LastTime;
-
-uint32_t dataBuff;
-
-void serialListener() {
-
-    int pinState = digitalRead(pinInput);
+class LpgSerial {

-    if (pinState == HIGH) {
-        serial2Change = true;
-        serial2Length = 0;
+    boolean lowEnds = true, receive = false;
+    uint8_t sync = 0, offset = 0;
+    int lastState = LOW;
+    unsigned long lowBegin = 0;
+    uint32_t buffer, transmission;
+
+
+private:
+    boolean isStart() {
+        return lastState == HIGH;
     }

-    if (pinState == LOW && serial2Change) {
-        serial2Length = (uint8_t)(millis() - serial2LastTime); //if it is low, end the time
-        serial2LastTime = millis();
-        serial2Change = false;

-        if (serial2Length >= 1 && serial2Length <= 6) { // 5ms read
-            dataBuff += 0 << serial2Offset;
-            serial2Offset++;
+    uint8_t getInputLen() {
+        unsigned long highLen = 0;
+        int in = digitalRead(LPG_INPUT);

+        if (lowBegin == 0 && in == LOW && isStart()) {
+            lowBegin = millis();
+            lowEnds = false;
+        }
+
+        if (!lowEnds && in == LOW && isStart()) {
+            highLen = millis() - lowBegin;
+        }
+
+        if (highLen > LPG_TIMEOUT) {
+            return 0;
+        }
+
+        lastState = in;
+        return (uint8_t) highLen;
+    }
+
+public:
+
+    void begin() {
+//        if (sync == 0) {
+//            sync = uint8_t(pulseIn(LPG_INPUT, HIGH, LPG_TIMEOUT) / 1000);
+//        }
+    }
+
+    void listener() {
+        uint8_t len = getInputLen();
+
+        if (offset == 0 && receive != 0) {
+            buffer = '\0';
+            receive = false;
+        }
+
+        if (len > LPG_BYTE_HIGH && len < (LPG_BYTE_HIGH + LPG_TOLERANCE)) {
+            buffer += B1;
+            offset++;
+        } else {
+            buffer += B0;
+            offset++;
+        }
+
+        if (offset >= LPG_BITS) {
+            offset = 0;
+            receive = true;
+            transmission = buffer;
         }

-        if (serial2Length > 6 && serial2Length <= 8) { // 7ms read
-            dataBuff += 1 << serial2Offset;
-            serial2Offset++;
-        }
+    }

-        //
-        // 110100000001 // act LPG full
+    boolean isReceive() {
+        return receive;
+    }

-        if (serial2Length > 8 || serial2Offset > 11) { // 15 downs
-            serial2Readed = true;
-            serial2Length = 0;
-            serial2Offset = 0;
-        }
-
+    uint32_t getData() {
+        return transmission;
     }

-}
+};

 // LPG
 // 2221 2201
@@ -62,27 +96,16 @@
 // 1501 1521 C01 1C00 201
 // 110000000001

+LpgSerial lpg;

 void setup() {
-    pinMode(pinInput, INPUT);
-    digitalWrite(pinInput, LOW);
-
-//    attachInterrupt(digitalPinToInterrupt(pinInput), serialEvent2, FALLING );
-    Serial.begin(115200);
-    Serial.println("Beginning ... ");
+    lpg.begin();
 }

 void loop() {
-
-    serialListener();
-
-    if (serial2Readed) {
-        Serial.println(BitVal(dataBuff, 0));
-        Serial.print(F("BIN "));
-        Serial.print(dataBuff, BIN);
-        dataBuff = 0;
-        Serial.println();
-        serial2Readed = false;
+    lpg.listener();
+    if (lpg.isReceive()) {
+        Serial.println(lpg.getData(), BIN);
     }
 }


Testing ifdef

Testing ifdef

--- module/module.ino
+++ module/module.ino
@@ -1,6 +1,7 @@
 #include <SoftwareSerial.h>
 #include "RFID.h"

+// For Arduino with integrated WiFi
 #ifdef UnoWiFi
 	#include <Ciao.h>
 #else


raised governer

raised governer

--- arduino/car_control/src/main_control_nano/main_control_nano.ino
+++ arduino/car_control/src/main_control_nano/main_control_nano.ino
@@ -21,7 +21,7 @@
 #define THROTTLE_SENSITIVITY 3.0

 #define LED_GREEN 4
-#define LED_RED 3
+#define LED_RED 13

 #define RPM_PIN 2
 #define RPM_INTERRUPT 0
@@ -55,7 +55,7 @@
 CmdMessenger commander = CmdMessenger(Serial,',',';','/');

 float _STEER_BIAS = 0.0; //set this to adjust steering
-int _GOVERNER_F = 20; //cap the forward speed
+int _GOVERNER_F = 40; //cap the forward speed
 int _GOVERNER_R = -12;

@@ -280,9 +280,13 @@

   //decay rpms incase vehicle has stopped
   rpm_decay++;
-  if (rpm_decay >10){
+  if(rpm_decay == 30){
+    toggle_LED(LED_RED,false);
+  }
+  if (rpm_decay >60){
     rpm = 0;
     rpm_decay = 0;
+    toggle_LED(LED_RED,true);
     commander.sendBinCmd(cmd_rpm, rpm);
    }


another possible connection

another possible connection

--- keypad/keypad.ino
+++ keypad/keypad.ino
@@ -28,6 +28,11 @@
 byte rowPins[ROWS] = { 9, 8, 7, 6 };
 // Connect keypad COL0, COL1 and COL2 to these Arduino pins.
 byte colPins[COLS] = { 12, 11, 10 };
+
+// REMAPPED CONNECTION
+//byte rowPins[ROWS] = { 12, 7, 9, 10 };
+//byte colPins[COLS] = { 11, 8, 6 };
+

 // Create the Keypad
 Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );


fix:	Fixing baud rate Fixing baud rate to 9600 to improve communication with phone

--- src/main/main.ino
+++ src/main/main.ino
@@ -44,7 +44,7 @@
     ; // wait for serial port to connect. Needed for native USB port only
   }
   // set the data rate for the SoftwareSerial port
-  mySerial.begin(115200);
+  mySerial.begin(9600);


FIX: Use call-by-reference for state change in subfunction

--- sketches/test_key/test_key.ino
+++ sketches/test_key/test_key.ino
@@ -31,7 +31,8 @@
 // simple function to compare current state with new read
 // if different, state and LED are updated
 // We're using input_pullup so the switch is active when LOW!
-void pinchange(bool value, bool state, int pin) {
+// Note: Internally changing `state` requires call-by-reference
+void pinchange(bool value, bool &state, int pin) {
   // Compare them - state records inverse of switch read
   if (value == state) { // Equal means a change
     // Update values as needed, if needed


Temperature text builder is ready

Temperature text builder is ready

--- digit4/digit4.ino
+++ digit4/digit4.ino
@@ -1,5 +1,5 @@
 const int DIGIT_DELAY_IN_MICROSECONDS = 500;
-const int MODE_DURATION_IN_MILLIS = 5000; // temperature / humidity modes
+const int MODE_DURATION_IN_MILLIS = 2000; // temperature / humidity modes

 const int DIGIT_1_PIN = 3;
 const int DIGIT_2_PIN = 5;
@@ -30,8 +30,8 @@
 short digits[4];
 boolean decimalPoints[4];

-int temperature = -23; // real temperature * 10
-int humidity = 463;    // real humidity * 10
+int temperature; // real temperature * 10
+int humidity;    // real humidity * 10
 long startModeMillis;

 enum Mode {
@@ -232,7 +232,7 @@
 }

 int readData() {
-  temperature = -23;
+  temperature = 234; // 1=0.1, -1=-0.1, 12=1.2, -12=-1.2, 123=12.3, -123=-12, 1234=123, -1234=err, 12345=err, -12345=err
   humidity = 463;

   return 0;
@@ -246,13 +246,58 @@
 }

 void setTemperature() {
-  digits[0] = MINUS_SYMBOL;
-  digits[1] = 2;
-  digits[2] = 3;
-  digits[3] = DEGREE_SYMBOL;
+  const boolean isNegative = temperature < 0 ? true : false;
+  const int absTemperature = isNegative ? -temperature : temperature;
+
+  String textTemperature = String(absTemperature);
+  int textLength = textTemperature.length();
+  if (textLength == 0) {
+    textTemperature = "00";
+    textLength = 2;
+  }
+  else if (textLength == 1) {
+    textTemperature = "0" + textTemperature;
+    textLength = 2;
+  }
+
+Serial.println(textTemperature);
+
+  boolean hasDecimalPoint = true;
+  if ((isNegative && (textLength > 2)) || (!isNegative && (textLength > 3))) {
+    textTemperature.remove(textLength);
+    hasDecimalPoint = false;
+    textLength--;
+  }
+
+  if (isNegative) {
+    if (textLength == 2) {
+      digits[0] = MINUS_SYMBOL;
+      digits[1] = String(textTemperature.charAt(textLength - 2)).toInt();
+      digits[2] = String(textTemperature.charAt(textLength - 1)).toInt();
+      digits[3] = DEGREE_SYMBOL;
+    } else {
+      digits[0] = E_SYMBOL;
+      digits[1] = R_SYMBOL;
+      digits[2] = R_SYMBOL;
+      digits[3] = DEGREE_SYMBOL; //todo add code for temperature overflow error
+    }
+  } else { // positive
+    if (textLength > 3) {
+      digits[0] = E_SYMBOL;
+      digits[1] = R_SYMBOL;
+      digits[2] = R_SYMBOL;
+      digits[3] = DEGREE_SYMBOL; //todo add code for temperature overflow error
+    } else {
+      if (textLength == 2) digits[0] = NOTHING_SYMBOL;
+      else digits[0] = String(textTemperature.charAt(textLength - 3)).toInt();
+      digits[1] = String(textTemperature.charAt(textLength - 2)).toInt();
+      digits[2] = String(textTemperature.charAt(textLength - 1)).toInt();
+      digits[3] = DEGREE_SYMBOL;
+    }
+  }

   decimalPoints[0] = false;
-  decimalPoints[1] = true;
+  decimalPoints[1] = hasDecimalPoint;
   decimalPoints[2] = false;
   decimalPoints[3] = false;
 }
@@ -299,6 +344,8 @@

   startModeMillis = millis();
   mode = TEMPERATURE;
+
+  Serial.begin(9600);
 }

 void loop() {
@@ -321,6 +368,8 @@
     else setHumidity();
   }

+//  delay(1000);
+
   // Draw one current digit on display
   activateDigit(INACTIVE);
   drawDigit(digits[currentDigitIndex], decimalPoints[currentDigitIndex]);


Make played flag volatile

Make played flag volatile

--- Pingduino/Pingduino.ino
+++ Pingduino/Pingduino.ino
@@ -27,7 +27,7 @@
     void stop();

   protected:
-    bool _played;
+    volatile bool _played;
     bool _stop;
     bool _initialized;


Update ArduCAM_Shield_V2_Touch.ino

Update ArduCAM_Shield_V2_Touch.ino

--- ArduCAM/examples/Shield_V2/ArduCAM_Shield_V2_Touch/ArduCAM_Shield_V2_Touch.ino
+++ ArduCAM/examples/Shield_V2/ArduCAM_Shield_V2_Touch/ArduCAM_Shield_V2_Touch.ino
@@ -46,8 +46,14 @@
 Serial.println(F("ACK CMD ArduCAM Start!"));
 // set the CS as an output:
 pinMode(SPI_CS, OUTPUT);
+digitalWrite(SPI_CS, HIGH);
 // initialize SPI:
 SPI.begin();
+//Reset the CPLD
+myCAM.write_reg(0x07, 0x80);
+delay(100);
+myCAM.write_reg(0x07, 0x00);
+delay(100);
 while(1){
   //Check if the ArduCAM SPI bus is OK
   myCAM.write_reg(ARDUCHIP_TEST1, 0x55);


Changed communication to use readBytes() instead of parseInt()

--- VendingMachineRFID.ino
+++ VendingMachineRFID.ino
@@ -12,11 +12,15 @@
 #include "VendingMachineRFID.h"

 /* Hack to fix sizeof(card_uid_t) sometimes becoming 5 (?) */
-#define CARD_UID_SIZE 4
+// #define CARD_UID_SIZE 4
+// Caused by Stream.parseInt();

 MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
 uint32_t lastCardScan; // Debounce RFID reads
 uint32_t timeBetweenScans;
+
+uint16_t credits_in_machine;//Serial.parseInt();
+char parseBuffer[2];

 void setup() {
   uint32_t lastCardScan = 0;
@@ -28,7 +32,7 @@
   Serial.print("Sizeof(card): ");
   Serial.println(sizeof(card_t));
   Serial.print("Sizeof(card_uid_t):: ");
-  Serial.println(CARD_UID_SIZE);
+  Serial.println(sizeof(card_uid_t));
   Serial.print("Sizeof(card_credits_t): ");
   Serial.println(sizeof(card_credits_t));
 }
@@ -44,18 +48,24 @@
     if(millis()-lastCardScan > timeBetweenScans){
       lastCardScan = millis();
       cardSwiped();
-
       // Init card
       card_t card;
       // Copy card uid
-      memcpy(&card.uid, &mfrc522.uid.uidByte, CARD_UID_SIZE);
+      memcpy(&card.uid, &mfrc522.uid.uidByte, sizeof(card_uid_t));
       uint16_t addr = findCardOffset(card);
-
+      uint16_t credit_addr = addr+4;
+
+      // Flush incoming buffer
+      while(Serial.available()){Serial.read();}
       // Fetch current credit count for the vending machine, in order to know whether to withdraw or deposit
       Serial.print("C");
       Serial.println(addr);
-      // Recieve response
-      uint16_t credits_in_machine = Serial.parseInt();
+      // Attempt to recieve response from vending machine
+      // If no response from has been recieved within a second, assume it is not powered/booted yet, stop processing
+      if(Serial.readBytes(parseBuffer, sizeof(parseBuffer)) != 2){Serial.print("No response - aborting.");return;}
+      Serial.println(parseBuffer[0],DEC);
+      Serial.println(parseBuffer[1],DEC);
+      memcpy(&credits_in_machine,parseBuffer,sizeof(parseBuffer));
       // Zero credits in machine - done now to avoid race-conditions of people buying when saving credits
       Serial.print("Z");
       Serial.println(credits_in_machine);
@@ -72,8 +82,7 @@
         } else { // Known card!
           // Card found!
           // Withdraw from card
-          uint16_t credit_addr = addr+CARD_UID_SIZE;
-          EEPROM_readAnything(credit_addr,card.credits);
+          EEPROM_readAnything(addr+sizeof(card_uid_t),card.credits);
           if(card.credits == 0){
             // ERR Beep + display "NO CREDITS"?
             Serial.println("NO CREDITS - KNOWN CARD");
@@ -127,19 +136,7 @@
           card.credits = 0;
         } else { // Known card
           // Fetch current credits
-          uint16_t four = 4;
-          uint16_t credit_addr = addr+4;
-          //Serial.print("Z ");
-          Serial.println(addr,DEC);
-          Serial.println(addr+4,DEC);
-          Serial.println(addr+four,DEC);
-          //Serial.print(" + ");
-          //Serial.print(CARD_UID_SIZE);
-          //Serial.print(" = ");
-          Serial.println(credit_addr);
-          credit_addr = addr+four;
-          Serial.println(credit_addr);
-          EEPROM_readAnything(credit_addr,card.credits);
+          EEPROM_readAnything(addr+sizeof(card_uid_t),card.credits);
         }
         card.credits += credits_in_machine;
         // Card found! (Known card OR found free spot for new card)
@@ -207,12 +204,12 @@

 int16_t findFreeCardSpot(){
   uint16_t credits = 0;
-  uint16_t addr = CARD_UID_SIZE; // Offset pointer, so we are looking at the card.credits
+  uint16_t addr = sizeof(card_uid_t); // Offset pointer, so we are looking at the card.credits
   uint16_t last_addr = 1024-sizeof(card_t); // EEPROM size minus size of one element
   for(addr; addr <= last_addr; addr = addr + sizeof(card_t)){
     if(EEPROM_compareAnything(addr,credits)){ // If bytes at address match, ok!
-      Serial.println(addr-CARD_UID_SIZE);
-      return addr-CARD_UID_SIZE; // Offset pointer again, so it points to beginning of card_t
+      Serial.println(addr-sizeof(card_uid_t));
+      return addr-sizeof(card_uid_t); // Offset pointer again, so it points to beginning of card_t
     }
   }
   return 65535; // Error value


Refactoring

Refactoring

--- module/module.ino
+++ module/module.ino
@@ -1,6 +1,5 @@
 #include <SoftwareSerial.h>
 #include "RFID.h"
-

 SoftwareSerial RFID(RFID_RX, RFID_TX);
 SoftwareSerial WIFI(WIFI_RX, WIFI_TX);
@@ -29,7 +28,7 @@
 	const int quota = 3600;
 	const int sendInterval = 15000;
 	// some variables
-	bool responseFlag = false;
+	bool isValidResponse = false;
 	unsigned int userID = 0;
 	unsigned long existingTime, elapsedTime = 0;
 	unsigned char readData[bufferSize];
@@ -38,23 +37,23 @@
 	// ----------------------------------------------------------------------
 	// Scan for RFID tags
 	Serial.print(messages.scan);
-	while (!responseFlag) {
+	while (!isValidResponse) {
 		// no payload, so pass NULL
 		sendCommand(CMD_GET_SNR, blockID, machineID, keyA, NULL);
 		delay(waitforSerialResponse);
-		responseFlag = getResponse(readData);
-	}
-	// -----------------------------------------------------------------------
+		isValidResponse = getResponse(readData);
+	}
+	// ----------------------------------------------------------------------
 	// RFID tag detected, read block that contains time data (for this machine)
 	// LED will turn on
 	Serial.print(messages.detected);
 	digitalWrite(ledPin, HIGH);
 	sendCommand(CMD_READ, blockID, machineID, keyA, NULL);
 	delay(waitforReadResponse);
-	responseFlag = getResponse(readData);
-	// ------------------------------------------------------------------------
+	isValidResponse = getResponse(readData);
+	// -----------------------------------------------------------------------
 	// Analyze response packet and data
-	if (!responseFlag) {
+	if (!isValidResponse) {
 		soundFeedback(isReject);
 		Serial.print(messages.readUnsuccessful);
 	}
@@ -78,7 +77,7 @@
 			// Get user ID
 			sendCommand(CMD_READ, blockID, userData, keyA, NULL);
 			delay(waitforReadResponse);
-			responseFlag = getResponse(readData);
+			isValidResponse = getResponse(readData);
 			userID = getUser(readData);

 			// Sound and text feedback
@@ -100,8 +99,8 @@
 	if (elapsedTime > 0) {
 		sendCommand(CMD_WRITE, blockID, machineID, keyA, elapsedTime + existingTime);
 		delay(waitforWriteResponse);
-		responseFlag = getResponse(readData);
-		if (!responseFlag) {
+		isValidResponse = getResponse(readData);
+		if (!isValidResponse) {
 			Serial.print(messages.errorRead);
 		}
 		else {
@@ -175,7 +174,7 @@
 			if (pollCounter == pollTimeout) {
 				soundFeedback(isReject);
 				Serial.print(messages.cancel);
-				sendCount = (millis() - startTime)/1000;
+				sendCount = calculateTime(startTime);

 				// Any valid accumulated time will be returned
 				if (pulseCount > minCount) {
@@ -228,7 +227,7 @@
 				// check if the job was more than 5 seconds
 				if (pulseCount > minCount) {
 					// calculate elapsed time in seconds
-					return (millis() - startTime)/1000;
+					return calculateTime(startTime);
 				}
 				pulseCount = 0;
 			}
@@ -274,3 +273,7 @@
 		tone(speakerPin, acceptNote, acceptDuration);
 	}
 }
+
+unsigned int calculateTime(unsigned int startTime) {
+	return (millis() - startTime)/1000;
+}


did some stuff

did some stuff

--- TPSscaler/TPSscaler.ino
+++ TPSscaler/TPSscaler.ino
@@ -27,15 +27,23 @@

 #define MAX_TPS_IN 800
 #define MIN_TPS_IN 100
-#define POWER 0.333
+#define POWERUP 0.333
+#define POWERDOWN 3
+#define EXTRA 100

 //0.52-4.7 -> 3-235
 //0.55-3.9 -> 3-195

 Adafruit_MCP4725 dac;
-static unsigned short table[MAX_TPS_IN-MIN_TPS_IN+1];
+static unsigned short table_up[(MAX_TPS_IN - MIN_TPS_IN+1)/2];
+static unsigned short table_down[(MAX_TPS_IN - MIN_TPS_IN + 1)/2];
+
+int accumulated[20];
+int TPS_DIFF =MAX_TPS_IN - MIN_TPS_IN + 1;

 #define PRINT 0
+
+int pTPS;  //previous TPS

 void setup() {
 #if PRINT
@@ -44,14 +52,24 @@
   pinMode(INPUT_PIN, INPUT);
   dac.begin(0x62);
   //pinMode(OUTPUT_PIN, OUTPUT);
-  for (int i = 0; i < MAX_TPS_IN-MIN_TPS_IN+1; i++) {
-    float x = (((float)i)/(MAX_TPS_IN-MIN_TPS_IN+1));
-    x = pow(x,POWER);
+  int v_in = analogRead(INPUT_PIN);
+  pTPS = v_in-MIN_TPS_IN;
+  for (int i = 0; i < ( TPS_DIFF)/2; i++) {
+    float x = (((float)i)/( TPS_DIFF)/2);
+      float y = (((float)i)/( TPS_DIFF)/2);
+    x = pow(x,POWERUP);
     x = x * (UPPER-LOWER);
-    unsigned short res = ((unsigned short)x) + LOWER;
-    if (res > UPPER) res = UPPER;
-    if (res < LOWER) res = LOWER;
-    table[i] = res;
+    y = pow(y,POWERDOWN);
+    y = y * (UPPER-LOWER);
+    unsigned short res1 = ((unsigned short)x) + LOWER;
+    unsigned short res2 = ((unsigned short)y) + LOWER;
+    if (res1 > UPPER) res1 = UPPER;
+    if (res1 < LOWER) res1 = LOWER;
+     if (res2 > UPPER) res2 = UPPER;
+    if (res2 < LOWER) res2 = LOWER;
+
+    table_up[i] = res1;
+    table_down[i] = res2;
 #if PRINT
     Serial.print(i+MIN_TPS_IN);
     Serial.print(" ");
@@ -61,14 +79,25 @@
 }

 void loop() {
-  int v_in = analogRead(INPUT_PIN);
-  int idx = v_in-MIN_TPS_IN;
-  //idx = idx + (random(10)-5);
-  if (idx < 0) idx = 0;
-  if (idx > MAX_TPS_IN-MIN_TPS_IN) idx = MAX_TPS_IN-MIN_TPS_IN;
-  int v_out = table[idx];
+  int v_in = analogRead(INPUT_PIN);
+  int i_in = v_in - MIN_TPS_IN;
+  int idx;
+  if (pTPS - i_in > EXTRA) i_in = i_in + 150;
+  else if (i_in - pTPS > EXTRA) i_in = i_in - 150;
+
+  if (i_in < 0) idx = 0;
+  else if (i_in > MAX_TPS_IN - MIN_TPS_IN) idx = MAX_TPS_IN-MIN_TPS_IN;
+  else idx = i_in;
+
+  int v_out;
+  int movingAv = 0; // CHANGE THIS
+  if (movingAv > 0)
+  v_out = table_up[idx];
+  else
+  v_out = table_down[idx];
   //analogWrite(OUTPUT_PIN, v_out);
   dac.setVoltage(v_out, false);
+  pTPS = i_in;
 #if PRINT
   Serial.print(v_in);
   Serial.print(" ");


Engine room disable LCD

Engine room disable LCD

--- engine-room/engine_arduino/engine_arduino.ino
+++ engine-room/engine_arduino/engine_arduino.ino
@@ -14,6 +14,9 @@
 #define YELLOW rgb_color(255, 255, 0)
 #define OFF rgb_color(0, 0, 0)

+// TODO(bhomberg): update pin numbers
+// LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
+
 PololuLedStrip<2> leds;
 rgb_color colors[STRIP_LENGTH];

@@ -22,6 +25,7 @@
 #define SWITCH_WALL 3  // That's a wall, not a switch.

 #define NO 98  // Represents no pin
+const int SWITCH_PINS[] = {
    8,  7,  6,  5,  4, NO,  3,
   NO, 13, 12, NO, 11, 10,  9,
   20, 19, 18, 17, 16, 15, 14,
@@ -196,9 +200,6 @@
   return rgb_color(0, 0, 0);
 }

-// TODO(bhomberg): update pin numbers
-LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
-
 // Arduino setup() and loop()
 void setup() {
   if (USE_SERIAL) {
@@ -216,12 +217,8 @@

   // PololuLedStripBase::interruptFriendly = true;

-  for (uint16_t i = 0; i < STRIP_LENGTH; i++) {
-    colors[i] = GREEN;
-  }
-
-  lcd.begin(20, 4);
-  lcd.print("turn the lights on!  but do it right!");
+  // lcd.begin(20, 4);
+  // lcd.print("turn the lights on!  but do it right!");
 }

 //void loop() {


remove need to use pull up resistor for interrupt

--- vibrate_alarm_clock_2.ino
+++ vibrate_alarm_clock_2.ino
@@ -16,7 +16,9 @@
 #define MOTOR_PIN2 3
 #define MOTOR_SLEEP_PIN 6

-#define ALARM_PIN INT0 //Driven LOW by Chronodot on alarm triggered
+//These two rofero to the same pin
+#define ALARM_INT_PIN INT0//Driven LOW by Chronodot on alarm triggered
+#define ALARM_NORM_PIN 2//Driven LOW by Chronodot on alarm triggered

 #define ADC_PRECISION 1024

@@ -108,6 +110,8 @@
   pinMode(RIGHT_BUTTON_PIN, INPUT_PULLUP);

   pinMode(VOLTAGE_MEASURE_PIN, INPUT);
+
+  pinMode(ALARM_NORM_PIN, INPUT_PULLUP);

   pinMode(MOTOR_PIN1, OUTPUT);
@@ -128,7 +132,7 @@

   delay(INITIAL_TEXT_DELAY);

-  attachInterrupt(ALARM_PIN, alarmTriggered, FALLING);
+  attachInterrupt(ALARM_INT_PIN, alarmTriggered, FALLING);

@@ -211,7 +215,7 @@

 void processLeftButtonPressed(){
   unsigned long currentMillis = millis();
-
+
   if((currentMillis - timeLastPressedLeftButton) < MIN_TIME_BETWEEN_BUTTON_PRESSES){
     return;
   }
@@ -273,7 +277,6 @@

 void processMiddleButtonPressed(){
   unsigned long currentMillis = millis();
-

   if((currentMillis - timeLastPressedMiddleButton) < MIN_TIME_BETWEEN_BUTTON_PRESSES){
     return;