New version 2.1

New version 2.1

--- arduino/autofowl/autofowl.ino
+++ arduino/autofowl/autofowl.ino
@@ -5,7 +5,10 @@
 #include <Wire.h>
 #include <RTClib.h>

-#define DEBUG 1
+#define DEBUG 0
+// Set to 1 if you want to force setting of RTC to compilation time.
+// You probably want to set this back to 0 then reflash the device when done.
+#define FORCE_SET_RTC 0

 // --------------------------------------
 // -- Constants
@@ -16,6 +19,7 @@
 const int TICK                              = 150; // microseconds
 const byte EEPROM_UNINIT_VALUE              = -1;

+// Button positions
 const int BUTTON_UP                         = LOW;
 const int BUTTON_DOWN                       = HIGH;

@@ -56,11 +60,12 @@
 const int EEPROM_UNSET                      = 255;

 // Motor constants
-const int MOTOR_MAX_RPMS                    = 60;
+const int MOTOR_MAX_RPMS                    = 150;
 const int STEPS_PER_REVOLUTION              = 200;
 const int MOTOR_SPEED_STEPS_PER_SECOND      = ( MOTOR_MAX_RPMS / 60 ) * STEPS_PER_REVOLUTION;
-const int MOTOR_ACCEL_STEPS_PER_SEC_PER_SEC = 50;
-// Disable motor driver when stopped. Decreases power consumption and heat from motor. 0 = no, 1 = yes.
+const int MOTOR_ACCEL_STEPS_PER_SEC_PER_SEC = 60;
+// Disable motor driver when stopped.
+// Decreases power consumption and heat from motor.
 const bool MOTOR_DISABLE_ON_STOP            = true;

 // Number of ticks beyond threshold to wait before changing door position
@@ -72,8 +77,9 @@
 const int CLOCK_MIN_INCREMENT               = 15;

 // Door-specific constants
-// Number of revolutions to fully change door position
-const int REVOLUTIONS_TO_CHANGE             = 100;
+// Number of revolutions needed to change door position
+// Should be empirically determined since it depends on lenght of thread rod.
+const long REVOLUTIONS_TO_CHANGE             = 170;

 // Pins
 // Arduino Uno / Buttons
@@ -115,15 +121,15 @@
 // Used for light sensor
 int LightCurrent          = 0;             // Current reading
 int LightLast             = LightCurrent;  // Last reading
-int LightThreshUp         = 400;
-int LightThreshDown       = 100;
+int LightThreshUp         = 400;           // Light threshold above which we open door
+int LightThreshDown       = 100;           // Light threshold below which we close door
 int LightThreshTicks      = 0;             // Ticks needed to start door position change
 // Used for clock
 DateTime Now;
-TimeSpan ClockThreshUp;
-TimeSpan ClockThreshDown;
-// Is motor enabled or not
-bool MotorEnabled;
+TimeSpan ClockThreshUp;                    // Time above which we open door
+TimeSpan ClockThreshDown;                  // Time below which we close door
+// Used for motor
+bool MotorEnabled;                         // Is motor enabled or not?

 // Initialize the LCD
 LiquidCrystal Lcd(PIN_LCD_RS, PIN_LCD_ENABLE, PIN_LCD_D4, PIN_LCD_D5, PIN_LCD_D6, PIN_LCD_D7);
@@ -134,6 +140,7 @@
 // Declare the clock
 RTC_DS1307 RTC;

+// Setup function run when device is powered on
 void setup() {

   // initialize serial and wait for port to open:
@@ -160,7 +167,7 @@
   // set up the LCD's number of columns and rows:
   Lcd.begin(16, 2);
   // Print a message to the LCD.
-  Lcd.print("AutoFowl v2.0");
+  Lcd.print("AutoFowl v2.1");

   // Start the Real Time Clock
   Wire.begin();
@@ -168,8 +175,21 @@
   // Check to see if the RTC is keeping time.  If it is, load the time from your computer.
   if (! RTC.isrunning()) {
     // This will reflect the time that your sketch was compiled
-    RTC.adjust(DateTime(__DATE__, __TIME__));
-  }
+    DateTime defaultDatetime = DateTime(__DATE__, __TIME__);
+    RTC.adjust(defaultDatetime);
+    // Print warning
+    Serial.println("RTC is NOT running!");
+  }
+  #if FORCE_SET_RTC
+  RTC.adjust(DateTime(__DATE__, __TIME__));
+  #endif
+  updateTime();
+  Lcd.setCursor(0, 1);
+  Lcd.print(Now.hour());
+  Lcd.print(':');
+  Lcd.print(Now.minute());
+  Lcd.print(':');
+  Lcd.print(Now.second());

   // Read clock settings from EEPROM
   byte clockHourThreshUp = EEPROM.read(CLOCK_HOUR_THRESH_UP_ADDRESS);
@@ -178,19 +198,19 @@
   byte clockMinThreshDown = EEPROM.read(CLOCK_MIN_THRESH_DOWN_ADDRESS);
   ClockThreshUp = TimeSpan(
     0, // days
-    clockHourThreshUp == EEPROM_UNINIT_VALUE ? 0 : clockHourThreshUp,
-    clockMinThreshUp == EEPROM_UNINIT_VALUE ? 0 : clockMinThreshUp ,
+    clockHourThreshUp == EEPROM_UNINIT_VALUE ? 0 : clockHourThreshUp, // hours
+    clockMinThreshUp == EEPROM_UNINIT_VALUE ? 0 : clockMinThreshUp ,  // minutes
     0 // seconds
   );
   ClockThreshDown = TimeSpan(
     0, // days
-    clockHourThreshDown == EEPROM_UNINIT_VALUE ? 0 : clockHourThreshDown,
-    clockMinThreshDown == EEPROM_UNINIT_VALUE ? 0 : clockMinThreshDown,
+    clockHourThreshDown == EEPROM_UNINIT_VALUE ? 0 : clockHourThreshDown, // hours
+    clockMinThreshDown == EEPROM_UNINIT_VALUE ? 0 : clockMinThreshDown,   // minutes
     0 // seconds
   );

   // Set the motors desired constant speed in steps per second
-  Motor.setMaxSpeed( MOTOR_SPEED_STEPS_PER_SECOND );
+  Motor.setMaxSpeed(MOTOR_SPEED_STEPS_PER_SECOND);
   // Set the motors desired acceleration in steps per second per second
   Motor.setAcceleration(MOTOR_ACCEL_STEPS_PER_SEC_PER_SEC);

@@ -213,11 +233,19 @@
     CurrentMode = MODE_AUTO;
   }

+  // Read threshold settings from EEPROM
+  byte lightThreshUp = EEPROM.read(LIGHT_THRESH_UP_ADDRESS);
+  LightThreshUp = lightThreshUp == EEPROM_UNINIT_VALUE ? 400 : lightThreshUp;
+  byte lightThreshDown = EEPROM.read(LIGHT_THRESH_DOWN_ADDRESS);
+  LightThreshDown = lightThreshDown == EEPROM_UNINIT_VALUE ? 100 : lightThreshDown;
+
   // Display greeting on LCD for 1 second
   delay(1000);
   updateLCD();
-}
-
+
+}
+
+// Main program loop
 void loop() {

   // Handle pressed buttons
@@ -234,6 +262,7 @@
   delay(TICK);
 }

+// Main button handling function
 void handleButton() {
   int button = pressedButton();
   if ( button == PIN_MODE_BUTTON ) {
@@ -307,8 +336,10 @@
     }
   } else if ( CurrentMode == MODE_SET_OPEN_THRESH ) {
     LightThreshUp += LIGHT_THRESH_CHANGE_INCREMENT;
+    EEPROM.write(LIGHT_THRESH_UP_ADDRESS, LightThreshUp);
   } else if ( CurrentMode == MODE_SET_CLOSE_THRESH ) {
     LightThreshDown += LIGHT_THRESH_CHANGE_INCREMENT;
+    EEPROM.write(LIGHT_THRESH_DOWN_ADDRESS, LightThreshDown);
   } else if ( CurrentMode == MODE_SET_CLOCK_CLOSE_HOUR_THRESH ) {
     ClockThreshDown = TimeSpan(0, ClockThreshDown.hours() + 1, ClockThreshDown.minutes(), 0);
     EEPROM.write(CLOCK_HOUR_THRESH_DOWN_ADDRESS, ClockThreshDown.hours());
@@ -336,8 +367,10 @@
     }
   } else if ( CurrentMode == MODE_SET_OPEN_THRESH ) {
     LightThreshUp -= LIGHT_THRESH_CHANGE_INCREMENT;
+    EEPROM.write(LIGHT_THRESH_UP_ADDRESS, LightThreshUp);
   } else if ( CurrentMode == MODE_SET_CLOSE_THRESH ) {
     LightThreshDown -= LIGHT_THRESH_CHANGE_INCREMENT;
+    EEPROM.write(LIGHT_THRESH_DOWN_ADDRESS, LightThreshDown);
   } else if ( CurrentMode == MODE_SET_CLOCK_CLOSE_HOUR_THRESH ) {
     ClockThreshDown = TimeSpan(0, ClockThreshDown.hours() - 1, ClockThreshDown.minutes(), 0);
     EEPROM.write(CLOCK_HOUR_THRESH_DOWN_ADDRESS, ClockThreshDown.hours());
@@ -372,21 +405,19 @@
     return;
   }

-  // LightCurrent > LightThreshDown
-  // LightCurrent > LightThreshUp
-  // ClockThreshDown, Now, ClockThreshUp
-  // high.totalseconds() < totalseconds(Now) < high.totalseconds();
-
   // Determine if door should move up or down
   if ( DoorPosition != DOOR_POSITION_UP && (
+       // Open when light says to open but clock says to close
        ( LightCurrent > LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) > ClockThreshDown.totalseconds() ) ||
+       // Open when light says to open but clock says to close
        ( LightCurrent > LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) < ClockThreshUp.totalseconds() && totalseconds(Now) > ClockThreshDown.totalseconds() ) ||
-       // Ambiguous. Open when clock says to open, but there is not enough light to trigger an open
+       // Ambiguous. Open when clock says to open, but there isn't enough light to trigger an open
        ( LightCurrent < LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() ) ||
+       // Open when both light and clock say to open
        ( LightCurrent > LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) > ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() )
      )
-  ) {
-
+  )
+  { // We should open
     LightThreshTicks++;
     updateLCD();
     if ( LightThreshTicks > LIGHT_THRESH_TICKS_TO_CHANGE ) {
@@ -407,8 +438,8 @@
       // Ambiguous. Close when light says to open, but clock says to close. Prevents door staying open if light sensor is faulty.
       ( LightCurrent > LightThreshUp && LightCurrent > LightThreshDown && totalseconds(Now) < ClockThreshUp.totalseconds() && totalseconds(Now) < ClockThreshDown.totalseconds() )
     )
-  ) {
-
+  )
+  { // We should close
     LightThreshTicks++;
     updateLCD();
     if ( LightThreshTicks > LIGHT_THRESH_TICKS_TO_CHANGE ) {
@@ -418,9 +449,14 @@
       LightThreshTicks = 0;
     }
   } else {
+    // We shouldn't move, so reset timer
     LightThreshTicks = 0;
   }
 }
+
+//
+// Sensor input functions
+//

 // Read light sensor and set global var
 void updateLight() {
@@ -428,10 +464,16 @@
   LightCurrent = analogRead(PIN_PHOTOCELL);
 }

+// Read clock time and set global var
 void updateTime() {
   Now = RTC.now();
 }

+//
+// Door moving functions
+//
+
+// Ensures door is open
 void openDoor() {
   // If door is already up, just return
   if ( DoorPosition == DOOR_POSITION_UP ) {
@@ -440,6 +482,7 @@
   moveDoorUp(REVOLUTIONS_TO_CHANGE);
 }

+// Ensures door is closed
 void closeDoor() {
   // If door is already down, just return
   if ( DoorPosition == DOOR_POSITION_DOWN ) {
@@ -448,14 +491,14 @@
   moveDoorDown(REVOLUTIONS_TO_CHANGE);
 }

-void moveDoorUp(int revolutions) {
+void moveDoorUp(long revolutions) {
   updateDoorStatus(DOOR_MOVING_UP, DOOR_POSITION_UNKNOWN);
   moveDoor(revolutions);
   updateDoorStatus(DOOR_STATIONARY, DOOR_POSITION_UP);
 }

 // Start moving door down
-void moveDoorDown(int revolutions) {
+void moveDoorDown(long revolutions) {
   updateDoorStatus(DOOR_MOVING_DOWN, DOOR_POSITION_UNKNOWN);
   moveDoor(-revolutions);
   updateDoorStatus(DOOR_STATIONARY, DOOR_POSITION_DOWN);
@@ -463,9 +506,10 @@

 // Moves door either up or down.
 // If revolutions is positive, door goes up; if negative, door goes down.
-void moveDoor(int revolutions) {
+void moveDoor(long revolutions) {
   // Set the motor target position i.e. number of steps to move
-  Motor.move(revolutions * (long) STEPS_PER_REVOLUTION);
+  long revs = revolutions * STEPS_PER_REVOLUTION;
+  Motor.move(revs);

   enableMotor();

@@ -500,28 +544,40 @@
   EEPROM.write(DOOR_POSITION_ADDRESS, DoorPosition);
 }

-void enableMotor() {
-  MotorEnabled = 1;
-  digitalWrite(PIN_MOTOR_ENABLE, 1);
-}
-
-void disableMotor() {
-  MotorEnabled = 0;
-  if (MOTOR_DISABLE_ON_STOP) {
-    digitalWrite(PIN_MOTOR_ENABLE, 0);
-  }
-}
-
+// Returns true if door is currently moving
 bool doorIsMoving() {
   return ( DoorDirection != DOOR_STATIONARY );
 }

+// Update current door status global vars, EEPROM values, and LCD display
 void updateDoorStatus(int doorMoving, int doorPosition) {
   DoorDirection = doorMoving;
   DoorPosition = doorPosition;
   EEPROM.write(DOOR_POSITION_ADDRESS, doorPosition);
   updateLCD();
 }
+
+//
+// Motor control functions
+//
+
+// Enable door motor
+void enableMotor() {
+  MotorEnabled = 1;
+  digitalWrite(PIN_MOTOR_ENABLE, 1);
+}
+
+// Disable door motor
+void disableMotor() {
+  MotorEnabled = 0;
+  if (MOTOR_DISABLE_ON_STOP) {
+    digitalWrite(PIN_MOTOR_ENABLE, 0);
+  }
+}
+
+//
+// LCD functions
+//

 // Update LCD with current status
 void updateLCD() {
@@ -627,13 +683,19 @@
   return ( LightThreshTicks / (float) LIGHT_THRESH_TICKS_TO_CHANGE ) * 10;
 }

+// Transforms a timestamp into number of seconds
 int32_t totalseconds(DateTime timestamp) {
   return ( (int32_t)timestamp.hour() * 3600 ) + ( (int32_t)timestamp.minute() * 60 ) + timestamp.second();
 }

+// Returns true if time is between two times
 bool between(TimeSpan low, DateTime middle, TimeSpan high) {
   return high.totalseconds() < totalseconds(middle) < high.totalseconds();
 }
+
+//
+// Debugging functions
+//

 /**
  * Writes debug info to serial
@@ -648,46 +710,45 @@
   Serial.print(Now.second(), DEC);
   Serial.print(']');

-  Serial.print(" LightThreshUp=");
-  Serial.print(LightThreshUp);
-  Serial.print(" LightThreshDown=");
-  Serial.print(LightThreshDown);
-  Serial.print(" LightCurrent=");
-  Serial.print(LightCurrent);
+  Serial.print(" LightThreshUp=");        Serial.print(LightThreshUp);
+  Serial.print(" LightThreshDown=");      Serial.print(LightThreshDown);
+  Serial.print(" LightCurrent=");         Serial.print(LightCurrent);

   Serial.print(" ClockThreshUp=");
-  Serial.print(ClockThreshUp.hours(), DEC);
-  Serial.print(':');
-  Serial.print(ClockThreshUp.minutes(), DEC);
-  Serial.print(':');
-  Serial.print(ClockThreshUp.seconds(), DEC);
-  Serial.print(" (");
-  Serial.print(ClockThreshUp.totalseconds(), DEC);
-  Serial.print(")");
+    Serial.print(ClockThreshUp.hours(), DEC);
+    Serial.print(':');
+    Serial.print(ClockThreshUp.minutes(), DEC);
+    Serial.print(':');
+    Serial.print(ClockThreshUp.seconds(), DEC);
+    Serial.print(" (");
+    Serial.print(ClockThreshUp.totalseconds(), DEC);
+    Serial.print(")");
   Serial.print(" ClockThreshDown=");
-  Serial.print(ClockThreshDown.hours(), DEC);
-  Serial.print(':');
-  Serial.print(ClockThreshDown.minutes(), DEC);
-  Serial.print(':');
-  Serial.print(ClockThreshDown.seconds(), DEC);
-  Serial.print(" (");
-  Serial.print(ClockThreshDown.totalseconds(), DEC);
-  Serial.print(")");
-
-  Serial.print(" totalseconds(Now)=");
-  Serial.print(totalseconds(Now), DEC);
-
-  Serial.print(" CurrentMode=");
-  Serial.print(prettyMode());
-
-  Serial.print(" DoorPosition=");
-  Serial.print(prettyDoorPosition());
-  Serial.print(" DoorDirection=");
-  Serial.print(prettyDoorDirection());
-
-  Serial.print(" MotorEnabled=");
-  Serial.print(MotorEnabled);
-
+    Serial.print(ClockThreshDown.hours(), DEC);
+    Serial.print(':');
+    Serial.print(ClockThreshDown.minutes(), DEC);
+    Serial.print(':');
+    Serial.print(ClockThreshDown.seconds(), DEC);
+    Serial.print(" (");
+    Serial.print(ClockThreshDown.totalseconds(), DEC);
+    Serial.print(")");
+
+  Serial.print(" totalseconds(Now)=");    Serial.print(totalseconds(Now), DEC);
+
+  Serial.print(" CurrentMode=");          Serial.print(prettyMode());
+
+  Serial.print(" DoorPosition=");         Serial.print(prettyDoorPosition());
+  Serial.print(" DoorDirection=");        Serial.print(prettyDoorDirection());
+
+  Serial.print(" MotorEnabled=");         Serial.print(MotorEnabled);
+
+  Serial.print(" UpButtonState=");        Serial.print(UpButtonState);
+  Serial.print(" UpButtonLastState=");    Serial.print(UpButtonLastState);
+  Serial.print(" DownButtonState=");      Serial.print(DownButtonState);
+  Serial.print(" DownButtonLastState=");  Serial.print(DownButtonLastState);
+  Serial.print(" ModeButtonState=");      Serial.print(ModeButtonState);
+  Serial.print(" ModeButtonLastState=");  Serial.print(ModeButtonLastState);
+
   Serial.println();
 }
 #endif


Added documentation to carl.ino

Added documentation to carl.ino

--- iso/carl/carl.ino
+++ iso/carl/carl.ino
@@ -19,22 +19,17 @@
 	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 	THE SOFTWARE.
-
-	http://www.esp8266.com/viewtopic.php?f=32&t=3780
-	https://github.com/sandeepmistry/esp8266-Arduino/blob/master/esp8266com/esp8266/libraries/ESP8266WebServer/src/ESP8266WebServer.cpp
 */

+
+
 /*
-187
-296
-345
-
-
-EEPROM
+	NOTES
+	• Tone values above 13900 can cause unexpected behaviour.
+	• The black wire from the battery pack should be closer to the tires than the red one.
+	• Motor methods accept integers between 0-255
 */

-//Tone values above 13900 sometimes generate low tones
-//black closer to tires

 #include <ESP8266WiFi.h>
 #include <ESP8266mDNS.h>
@@ -45,7 +40,6 @@
 #include <sx1509_library.h>
 #include <Adafruit_NeoPixel.h>

-//Not sure if these are needed, but the LED isn't working so might as well
 #ifdef __AVR__
 #include <avr/power.h>
 #endif
@@ -59,61 +53,62 @@
 const int motor_BPinA = 2;
 const int motor_BPinB = 3;
 const int tone_Pin=13;
-// NOTE: Motor max output 255
-
+
+
+/*
+	Robot can use either a pre-existing wifi network by setting the SSID and PASS variables to the corresponding values and setting HOTSPOT to false
+	However, this is not recommended as the personal hotspot for the robot provides a more reliable connection.
+	Using existing networks might provide an easier developing experience as it allows connection via ethernet to the robot given the correct IP address which can be obtained from the arduino serial monitor upon boot
+*/
 const char* esp_SSID = "CarlRobot Gamma";
 const char* esp_PASS = "CarlRobot";
-const bool 	esp_HOTSPOT = true; // Enable to connect to an existing network, see below
-// You can have the ESP connect to your wifi network by replacing the OCSB and wireless4all found in the setup
-
-int robot_Mode=0; //1 = linefollowing, 0 = joystick
-unsigned long int loopIter=0;
-ESP8266WebServer server(80); // Start webserver
+const bool 	esp_HOTSPOT = true;
+
+int robot_Mode=0; 				// 1 = linefollowing, 0 = joystick
+unsigned long int loopIter=0;	// Used for flashing the LED when in linefollowing mode, not very important
+ESP8266WebServer server(80);

 void setup() {
-	Serial.begin(57600); // Begin serial, higher baud rate is less stable but faster
-	digitalWrite(7, HIGH); // Set HIGH output to ESP blue light
-	pixels.begin();
+	Serial.begin(57600); 	// Begin serial, higher baud rate is less stable but faster
+	digitalWrite(7, HIGH); 	// Set HIGH output to ESP blue light
+	pixels.begin();			// Setup the neopixel LEDs
 	setLEDColour(255,0,0);
 	Serial.println();

-	// Legacy code, motor initializer
 	sx1509.init();  // Initialize the SX1509, does Wire.begin()
-    byte clockDivider = 1;
-    sx1509.ledDriverInit(motor_APinA);
-    sx1509.ledDriverInit(motor_APinA, clockDivider, LOGARITHMIC);
-    sx1509.ledDriverInit(motor_APinB);
-    sx1509.ledDriverInit(motor_APinB, clockDivider, LOGARITHMIC);
-    sx1509.ledDriverInit(motor_BPinA);
-    sx1509.ledDriverInit(motor_BPinA, clockDivider, LOGARITHMIC);
-    sx1509.ledDriverInit(motor_BPinB);
-    sx1509.ledDriverInit(motor_BPinB, clockDivider, LOGARITHMIC);
-
-	// setup for QRE113 sensors
-	sx1509.pinDir(7, OUTPUT); //servo
-	sx1509.pinDir(8, OUTPUT); //ultrasonic trigger
-	sx1509.pinDir(9, INPUT); //ultrasonic echo
-	sx1509.pinDir(10, OUTPUT);  // Set SX1509 pin 10 as an output - enables all IR leds
-	sx1509.pinDir(11, INPUT);
+	byte clockDivider = 1;
+	sx1509.ledDriverInit(motor_APinA);
+	sx1509.ledDriverInit(motor_APinA, clockDivider, LOGARITHMIC);
+	sx1509.ledDriverInit(motor_APinB);
+	sx1509.ledDriverInit(motor_APinB, clockDivider, LOGARITHMIC);
+	sx1509.ledDriverInit(motor_BPinA);
+	sx1509.ledDriverInit(motor_BPinA, clockDivider, LOGARITHMIC);
+	sx1509.ledDriverInit(motor_BPinB);
+	sx1509.ledDriverInit(motor_BPinB, clockDivider, LOGARITHMIC);
+
+	// Setup for linefollowing (QRE113) sensors
+	sx1509.pinDir(7, OUTPUT); 	// servo
+	sx1509.pinDir(8, OUTPUT); 	// ultrasonic trigger
+	sx1509.pinDir(9, INPUT); 	// ultrasonic echo
+	sx1509.pinDir(10, OUTPUT);  // set SX1509 pin 10 as an output - enables all IR leds
+	sx1509.pinDir(11, INPUT);	// set the rest of the sensors to input
 	sx1509.pinDir(12, INPUT);
 	sx1509.pinDir(13, INPUT);
 	sx1509.pinDir(14, INPUT);
 	sx1509.pinDir(15, INPUT);

 	if (WiFi.status() == WL_NO_SHIELD)
-		while(true)
+		while(true) // Require the wifishield to boot
 			Serial.println("WiFi shield not present");

-	if (esp_HOTSPOT) {
+	if (esp_HOTSPOT) {	// Setup for personal hotspot
 		Serial.print("Wireless Access Point SSID: ");
 		Serial.println(esp_SSID);
 		WiFi.disconnect();
 		WiFi.mode(WIFI_AP);
 		WiFi.softAP(esp_SSID,esp_PASS);
-	} else {
-		esp_SSID = "OCSB";
-		esp_PASS = "wireless4all";
+	} else {			// Setup for existing network
 		WiFi.mode(WIFI_STA);
 		WiFi.begin(esp_SSID,esp_PASS);
 		while (WiFi.status() != WL_CONNECTED) {
@@ -127,32 +122,28 @@
 			ESP.restart();
 		}
 	}
-	// if (true) { // I don't want these variables floating around .-.
-	// 	IPAddress ip(192,168,0,124);
-	// 	IPAddress gateway(192,168,0,1);
-	// 	IPAddress subnet(255,255,255,0);
-	// 	WiFi.config(ip,gateway,subnet);
-	// }
-
+
+	// Setup the network event handlers
 	server.on("/",server_HandleRoot);
 	server.onNotFound(server_HandleNotFound);
-	server.begin();
-
+	server.begin(); // Start the listeners
+
+	// Print debug info
 	Serial.print("Webserver active");
 	Serial.print(" | ");
 	Serial.println(WiFi.SSID());
-
 	Serial.print("signal strength (RSSI):");
 	Serial.println(WiFi.RSSI());
-
 	Serial.println("IP Addresses: ");
 	Serial.print("\tLOCAL\t");
 	Serial.println(WiFi.localIP());
 	Serial.print("\tSOFTAP\t");
 	Serial.println(WiFi.softAPIP());

+	// OTA update handling
 	ArduinoOTA.begin();

+	// Boot noises and colours
 	tone(13, 500,250);
 	delay(250);
 	noTone(13);
@@ -162,41 +153,51 @@
 	setLEDColour(0,255,0);
 	delay(2000);
 	setLEDColour(0,0,255);
-	// digitalWrite(7, LOW); // Disable the ESP blue light, finished setup
-}
-
-
+}
+
+
+// Variables used in linefollowing logic
 int pleft=0;
 int pright=1;
+
 void loop() {
-	loopIter++;
-	server.handleClient();
-	ArduinoOTA.handle();
-	if (robot_Mode==1) {
-		setLEDColour(loopIter%10==0?255:0,loopIter%10==5?255:0,0);
+	loopIter++;				// Increase logic counter for LED flashing, millis() might be a better method for future use
+	server.handleClient();	// Handle network events
+	ArduinoOTA.handle();	// Handle OTA updates
+	if (robot_Mode==1) { // Linefollowing logic
+		setLEDColour(loopIter%10==0?255:0,loopIter%10==5?255:0,0); // Flash LED
 		sx1509.writePin(10,HIGH);
 		int right = sx1509.readPin(12);  // read line sensor 1 (s4)
-		int left = sx1509.readPin(14);  // read line sensor 3 (s3)
-		// int nleft=0;
-		// int nright=0;
-		// int aleft=pleft*255;
-		// int aright=pright*255;
-		// if (pleft==1 && left==1) {
-		// 	pleft=0;
-		// 	pright=1;
-		// 	aright=255;
-		// } else if (pright==1 && right==1) {
-		// 	pright=0;
-		// 	pleft=1;
-		// 	aleft=255;
-		// }
+		int left = sx1509.readPin(14);   // read line sensor 3 (s3)
+
 		int nleft=0;
 		int nright=0;
 		int aleft=0;
 		int aright=0;
+		/*
+			nleft = left motor reverse
+			aleft = left motor forward
+			nright= right motor reverse
+			aright= right motor forward
+		*/
+		/*
+			Linefollowing logic pseudo-code
+
+			Default action : stop
+			if (both sensors on white)
+				resume previous actions (ex, turn left)
+			elseif (both sensors on black)
+				resume right_previous
+				set right_previous=forward
+			elseif (left sensor on white)
+				set left_motor,left_previous=forward
+				set previous_right=stop
+			elseif (right sensor on white)
+				set right_motor,right_previous=forward
+				set previous_left=stop
+
+		*/
 		if (left==0&&right==0) {
-			// aleft=255;
-			// aright=255;
 			aleft=pleft;
 			aright=pright;
 		} else if (left==1&&right==1) {
@@ -206,14 +207,13 @@
 			aleft=255;
 			pleft=aleft;
 			pright=0;
-			// nleft=180;
 		} else if (right==0) {
 			aright=255;
 			pright=aright;
 			pleft=0;
-			// nright=180;
 		}
-		motor_SetOutputs(nleft,aleft,nright,aright );
+		motor_SetOutputs(nleft,aleft,nright,aright ); //Set motor to determined values
+		//Print debug info on one line, otherwise hard to read on scrolling serial monitor
 		Serial.print(pleft);
 		Serial.print(" ");
 		Serial.print(pright);
@@ -225,61 +225,67 @@
 		Serial.print(aleft);
 		Serial.print(" ");
 		Serial.print(aright);
-
 		Serial.println(" ");
-		motor_SetOutputs(nleft,aleft,nright,aright );
 	}
 }

 void motor_SetOutputs(int apina, int apinb, int bpina, int bpinb) {
- 	sx1509.pwm(motor_APinA, apina);
+	// Each motor has 2 parts, reverse output and forward output
+	// PinA=reverse pin
+	// PinB=forward pin
+	sx1509.pwm(motor_APinA, apina);
 	sx1509.pwm(motor_APinB, apinb);
 	sx1509.pwm(motor_BPinA, bpina);
 	sx1509.pwm(motor_BPinB, bpinb);
 }

 void setLEDColour(int r, int g, int b) {
-	for (int i = 0; i < 1; i++) { // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
-    	pixels.setPixelColor(i, pixels.Color(r, g, b));
-    	pixels.show(); // sends updated pixel to hardware
-  	}
+	for (int i = 0; i < 1; i++) {
+		// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
+		pixels.setPixelColor(i, pixels.Color(r, g, b));
+		pixels.show();  // sends updated color to hardware
+	}
 }

 void server_SendGood() {
-	server.send (200, "text/html", "recieved");
+	server.send (200, "text/html", "recieved"); // Tell the client that their request went through
 }

 int getArg(String arg) {
-	return atoi(server.arg(arg).c_str());
+	return atoi(server.arg(arg).c_str()); // Cast the string arguments to integer and return
 }

 void server_HandleRoot(){
 	Serial.println("Handling Root\n");
+	// Get arguments from request, default=0
 	int apina=getArg("apina");
-  	int apinb=getArg("apinb");
+	int apinb=getArg("apinb");
 	int bpina=getArg("bpina");
-  	int bpinb=getArg("bpinb");
-  	int r=getArg("r");
-  	int g=getArg("g");
-  	int b=getArg("b");
-  	int freq=getArg("freq");
-  	int duration=getArg("dur");
-  	int restart=getArg("restart");
-  	robot_Mode=getArg("mode");
-  	if (freq==0) {
-  		noTone(tone_Pin);
-  	} else if (duration!=0) {
-  		tone(tone_Pin,freq,duration);
-  		delay(duration);
-  		noTone(tone_Pin);
-  	} else {
-	  	tone(tone_Pin,freq,1000000);
-  	}
+	int bpinb=getArg("bpinb");
+	int r=getArg("r");
+	int g=getArg("g");
+	int b=getArg("b");
+	int freq=getArg("freq");
+	int duration=getArg("dur");
+	int restart=getArg("restart");
+
+	robot_Mode=getArg("mode"); // Set robot mode
+	if (freq==0) { // Stop tone generation
+		noTone(tone_Pin);
+	} else if (duration!=0) { // Set tone to play for set time in milliseconds
+		tone(tone_Pin,freq,duration);
+		delay(duration);
+		noTone(tone_Pin);
+	} else { // Play tone 'forever'
+		tone(tone_Pin,freq,1000000);
+	}

-
+	// Set motor outputs to received values
 	motor_SetOutputs(apina,apinb,bpina,bpinb);
+	// Set LED to received values
 	setLEDColour(r,g,b);
-
+
+	// Build response displaying given variables
 	String response = "
Update 9-16

Arguments:

";
 	for (uint8_t i=0; i<server.args(); i++)
 		response+="\t"+server.argName(i)+":\t"+server.arg(i)+"\n";
@@ -291,7 +297,7 @@
 	}
 }

-void server_HandleNotFound() {
+void server_HandleNotFound() { // Build error message when a request 404's
 	String message = "File Not Found\n\n";
 	message += "URI: ";
 	message += server.uri();


L C1 and C2 step rotation functions embedded; UI changed to reflect L C1 and C2 step rotation

--- hal100/hal100.ino
+++ hal100/hal100.ino
@@ -18,6 +18,11 @@
   https://www.jaycar.com.au/128x128-lcd-screen-module-for-arduino/p/XC4629
   http://www.arduino.cc/en/Tutorial/TFTDisplayText

+
+Motor 1 = "L" Motor
+Motor 2 = "C1" Motor "Cold"
+Motor 3 = "C2 Motor "Hot"
+
 */
 #include "proto/device_id.h"
 #include <TFT.h>    // Arduino LCD library
@@ -40,7 +45,8 @@
 char enteredFreq[6];
 char tuningFreq[6];
 char key;
-char DisplayValueC[5];
+char DisplayValueC1[5];
+char DisplayValueC2[5];
 char DisplayValueL[5];
 char DisplayValueSWR[5];
 char input; //buffer for input characters for calculations
@@ -50,10 +56,11 @@
 float KHz;                  // KHz constant
 float PlanckTime;           // Planck constant
 float pi;                   // π constant
-float valueC = 0;           // calculated value C float
+float valueC1 = 0;           // calculated value C float
 float valueCEffective = 0;  // calculated value C float
 float valueL = 0;           // calculated value L float
-float valueCorr = 0;        // calculated value C float
+float valueC1Corr = 0;      // calculated value C1 float
+float valueC2Corr = 0;      // calculated value C1 float
 float valueLcorr = 0;       // calculated value L float
 float Cmult;                // constant multiplier to calculate C value
 float Lmult;                // constant multiplier to calculate L value
@@ -70,18 +77,23 @@
 int i;

-// Keypad code start
+// --- Keypad code start ---
 const byte ROWS = 5; // Five rows
 const byte COLS = 4; // Four columns
 // Define the Keymap
 char keys[ROWS][COLS] = {
-  {'S', '1', '2', '3'}, // ROW0-pin5      Buttons association 1=1 2=2 3=3 4=4 5=5 6=6 7=7 8=8 9=9 0=0 *=Led OFF #=Led ON
+// Buttons association 1=1 2=2 3=3 4=4 5=5 6=6 7=7 8=8 9=9 0=0 *=Led OFF #=Led ON
+// TOP Buttons  C c L l
+//Buttons in middle H U D S
+
+// COL0-pin1, COL1-pin2, COL2-pin3, COL3-pin4
+  {'S', '1', '2', '3'}, // ROW0-pin5
   {'K', '4', '5', '6'}, // ROW1-pin6
-  {'U', '7', '8', '9'}, // ROW2-pin7      TOP Buttons  C c L l
+  {'U', '7', '8', '9'}, // ROW2-pin7
   {'D', '*', '0', '#'}, // ROW3-pin8
-  {'L', 'l', 'C', 'c'}  // ROW4-pin9      Buttons in middle H U D S
+  {'c', 'C', 'h', 'H'}  // ROW4-pin9
+
 };
-// COL0-pin1, COL1-pin2, COL2-pin3, COL3-pin4

 // Connect keypad ROW0 Pad pin ->> 5=30 <<- pin Mega, ROW1 6=32, ROW2 7=23, ROW3 8=25, ROW4 9=27
 byte rowPins[ROWS] = { 30, 32, 23, 25, 27 };
@@ -90,7 +102,7 @@

 // Create the Keypad
 Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
-// end of Keypad code
+// --- end of Keypad code ---

 void busReceiver(const TCommand *payload, const PJON_Packet_Info &packet_info) {
 	switch (payload->id) {
@@ -111,7 +123,7 @@
 		valueSWR = (1 + p) / (1 - p);
 		Serial.print(", Value SWR=");
 		Serial.println(valueSWR);
-   displaySWRvalue();
+        displaySWRvalue();

 		break;
 	}
@@ -164,8 +176,8 @@
 	calculateL();                                     // calculate L value at given frequency and C value
 	calculateStepsL();                                // calculate steps needed to move C to value L
 	LmoveStage1();                                    // send command to nano to move motor "L" to L step value
-	EraseDisplayC(), EraseDisplayL();                 // clear previous values L and C at display
-	displayC(), displayL();                           // display current values L and C at display
+	EraseDisplayC1(), EraseDisplayL();                 // clear previous values L and C at display
+	displayC1(), displayL();                           // display current values L and C at display
 	mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
 	// End STAGE 1 tuning process
 }
@@ -180,13 +192,24 @@

 void incL(float diff) {
-	valueRotateL = valueRotateL + diff;
-	mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
-}
-
-void incC(float diff) {
-	valueRotateC1 = valueRotateC1 + diff;
-	mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
+  EraseDisplayL();
+  valueRotateL = valueRotateL + diff;
+  displayL();
+  mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
+}
+
+void incC1(float diff) {
+  EraseDisplayC1();
+  valueRotateC1 = valueRotateC1 + diff;
+  displayC1();
+  mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
+}
+
+void incC2(float diff) {
+  EraseDisplayC2();
+  valueRotateC2 = valueRotateC2 + diff;
+  displayC2();
+  mechSetPosition(round (valueRotateL), round (valueRotateC1), round (valueRotateC2));
 }

 void incLCorr(float diff) {
@@ -196,13 +219,19 @@
     }
 }

-void incCCorr(float diff) {
+void incC1Corr(float diff) {
     if (tuningFreqCalc != 0.0) {
-      valueCorr = valueCorr + diff;
+      valueC1Corr = valueC1Corr + diff;
       SetFrequencyStage1();
     }
 }

+void incC2Corr(float diff) {
+    if (tuningFreqCalc != 0.0) {
+      valueC2Corr = valueC2Corr + diff;
+      SetFrequencyStage1();
+    }
+}

 void eraseFreqTopScreen() {                      // erases frequency value from top of display
   TFTscreen.stroke(0, 20, 30);
@@ -251,7 +280,7 @@
 }

 void displayL() {                                         // display L values
-  dtostrf(valueRotateL, 5, 2, DisplayValueL);
+  dtostrf(valueRotateL, 5, 0, DisplayValueL);
   TFTscreen.stroke(0, 255, 0);
   TFTscreen.setTextSize(2);
   TFTscreen.text(DisplayValueL, 40, 40);
@@ -263,17 +292,30 @@
   TFTscreen.text(DisplayValueL, 40, 40);
 }

-void displayC() {                                       // display C values
-  dtostrf(valueRotateC1, 5, 0, DisplayValueC);
+void displayC1() {                                       // display C values
+  dtostrf(valueRotateC1, 5, 0, DisplayValueC1);
   TFTscreen.stroke(0, 255, 0);
   TFTscreen.setTextSize(2);
-  TFTscreen.text(DisplayValueC, 40, 60);
-}
-
-void EraseDisplayC() {                                   // erase display C values
+  TFTscreen.text(DisplayValueC1, 40, 60);
+}
+
+void EraseDisplayC1() {                                   // erase display C values
   TFTscreen.stroke(0, 20, 20);
   TFTscreen.setTextSize(2);
-  TFTscreen.text(DisplayValueC, 40, 60);
+  TFTscreen.text(DisplayValueC1, 40, 60);
+}
+
+void displayC2() {                                       // display C values
+  dtostrf(valueRotateC2, 5, 0, DisplayValueC2);
+  TFTscreen.stroke(0, 255, 0);
+  TFTscreen.setTextSize(2);
+  TFTscreen.text(DisplayValueC2, 40, 80);
+}
+
+void EraseDisplayC2() {                                   // erase display C values
+  TFTscreen.stroke(0, 20, 20);
+  TFTscreen.setTextSize(2);
+  TFTscreen.text(DisplayValueC2, 40, 80);
 }

 void eraseFrequency() {                         // when * pressed - erases entered frequency bottom of the screen
@@ -315,9 +357,9 @@
   PlanckTime = 299792458;
   Cmult = 1.5;
   valueCEffective = PlanckTime / ( tuningFreqCalc * KHz ) * Cmult;
-  valueC = valueCEffective + valueCorr;
-  Serial.print("Value C pF=");
-  Serial.println(valueC);
+  valueC1 = valueCEffective + valueC1Corr;
+  Serial.print("Value C1 pF=");
+  Serial.println(valueC1);
 }

 void calculateL () {                            // Calculate "L" value from formula L=((1/(2*π*f*C))/(2*π*f))*1000000000000 (where f in KHz and C in pF)
@@ -337,7 +379,7 @@
   Serial.println(pFtotalValue);
   float pFperStep = pFtotalValue / ( totalStepsC / 2 );
   Serial.println(pFperStep);
-  valueRotateC1 = ( valueC - pFmin ) / pFperStep;
+  valueRotateC1 = ( valueC1 - pFmin ) / pFperStep;
   Serial.print("steps C to rotate=");
   Serial.println(valueRotateC1);
 }
@@ -372,27 +414,33 @@
         case '#':                           // submit frequesncy
           SetFrequency();
           break;
-        case 'C':                           // will be used for "C" motor move 1 step CCW
-          incCCorr(-1);
-          break;
-        case 'c':                           // will be used for "C" motor move 1 step CW
-          incCCorr(1);
-          break;
-        case 'L':                           // used for "L" motor move 1 step CCW
-          incLCorr(-0.001);
-          break;
-        case 'l':                           // used for "L" motor move 1 step CW
-          incLCorr(0.001);
+        case 'c':                           // "C1 Cold" motor move 5 step CCW
+          incC1(-5);
+          break;
+        case 'C':                           // "C1 Cold" motor move 5 step CW
+          incC1(5);
+          break;
+        case 'h':                           // "C2 Hot" motor move 5 step CCW
+          incC2(-5);
+          break;
+        case 'H':                           // "C2 Hot" motor move 5 step CW
+          incC2(5);
+          break;
+        case 'D':                           // "L" motor move 100 step CCW
+          incL(-100.0);
+          break;
+        case 'U':                           // "L" motor move 100 step CW
+          incL(+100.0);
           break;
         case '*':                           // erase entered frequency
           eraseFrequency();
           break;
-        case 'U':                           // calibrate both motors
-          mechCalibrate(channelC1);
-          break;
-        case 'D':                           // calibrate both motors
-          mechCalibrate(channelL);
-          break;
+//        case 'U':                           // calibrate both motors
+//          mechCalibrate(channelC1);
+//          break;
+//        case 'D':                           // calibrate both motors
+//          mechCalibrate(channelL);
+//          break;

       }
   }


start of a capture requires an additional delay

First frame sync problem (in double dongle/no master configurations) is
now resolved.

--- d_BacpacCommands.ino
+++ d_BacpacCommands.ino
@@ -204,14 +204,16 @@
     break;
   case SET_CAMERA_3D_SYNCHRONIZE:
     // Master shutter button depressed
-    if (1) { // send to slaves
+    if (!isMaster) { // send to slaves
       Serial.print("SY");
       printHex(RECV(3), true);
       Serial.println("");
-      Serial.flush();
     }
     buf[0] = 0x83; buf[1] = 'S'; buf[2] = 'R'; buf[3] = RECV(3);
-    delay(200);
+    if (buf[3] == 1) {
+      delay(1000); // start of a capture requres additional delay
+    }
+    delay(140);
     SendBufToBacpac();
     if (buf[3] == 0 && td[TD_MODE] != MODE_TIMELAPSE) {
       queueIn("SR3"); // notify video saved
@@ -221,7 +223,7 @@
       switch (RECV(3)) {
       case 1:
       case 2:
-        timelapse = 1800;
+        timelapse = 1900;
         break;
       default:
         timelapse = 0;


Update bicicletaInteligente.ino

Update bicicletaInteligente.ino

Se ha cambiado el valor de la aceleración media de 55 a 120, para conseguir un mejor funcionamiento.

--- bicicletaInteligente.ino
+++ bicicletaInteligente.ino
@@ -1,111 +1,111 @@
-/* BICICLETA INTELIGENTE. Pablo Sánchez Carmona */
-#include "sensor.h"
-#include "pendiente.h"
-#include "bluetooth.h"
-
-// Definición de pines
-#define PIN_ACELERADOR 4 // Señal PWM
-// Ponderación (para el cálculo de la aceleración)
-#define A1 0.5
-#define A2 0.2
-#define A3 0.1
-#define TASA 0.5
-// Definición de variables para controlar el algoritmo
-static unsigned long velocidad_minima = 5;
-static unsigned long velocidad_paseo = 15;
-static unsigned long velocidad_crucero = 25;
-// Definición de variables para la aceleración
-byte acelerador = 0;
-byte acelerador_deseable = 0;
-byte incremento_acelerador = 0;
-byte acelerador_final = 0;
-
-//----------------------------------------
-
-void setup() {
-  analogWrite(PIN_ACELERADOR, 0);
-  setupSensores();
-  establecerMPU();
-  configurarBT();
-}
-
-void loop() {
-
-  // Funciones de la librería "Sensor" y "Pendiente"
-  lecturaSensores();
-  lecturaDatos();
-  obtenerVelocidad();
-  obtenerAceleracion();
-  // Modo de funcionamiento
-  switch(modo){
-    case 0:
-      analogWrite(PIN_ACELERADOR, 0);
-      break;
-    case 1:
-      // Funciones del algoritmo de funcionamiento
-      decisionAcelerador();
-      obtenerIncremento();
-      acelerador_final = acelerador + TASA*incremento_acelerador;
-      analogWrite(PIN_ACELERADOR, acelerador_final);
-      break;
-    case 2:
-      if(sensor_freno_der || sensor_freno_izq || !sensor_pas || anguloX < 0){
-        acelerador = 0;
-      }
-      else{
-        acelerador = 55;
-      }
-      analogWrite(PIN_ACELERADOR, acelerador);
-      break;
-    default:
-      analogWrite(PIN_ACELERADOR, 0);
-      break;
-  }
-  // Función de la librería "Bluetooth"
-  envioDatos();
-}
-
-//----------------------------------------
-
-void decisionAcelerador(){
-  if(sensor_freno_der || sensor_freno_izq || !sensor_pas || anguloX < 0){
-    acelerador = 0;
-  }
-  else {
-    if(velocidad < velocidad_minima){
-      acelerador = 255;
-    }
-    else {
-      if (velocidad < velocidad_paseo){
-        acelerador_deseable = 75;
-      }
-      else if (velocidad < velocidad_crucero){
-        acelerador_deseable = 75*((velocidad_crucero - velocidad)/(velocidad_crucero - velocidad_paseo));
-      }
-      else {
-        acelerador_deseable = 0;
-      }
-    }
-  }
-}
-
-void obtenerIncremento(){
-
-  if(aceleracion > 0) {
-    incremento_acelerador = incremento_acelerador + A1*(acelerador_deseable - acelerador)*255;
-  }
-  if(anguloX > 0){
-    incremento_acelerador = incremento_acelerador + A2*anguloX*255;
-  }
-  if(velocidad < velocidad_crucero){
-    incremento_acelerador = incremento_acelerador + A3*(velocidad_crucero - velocidad)*255;
-  }
-
-}
-
-
-
-
-
-
+/* BICICLETA INTELIGENTE. Pablo Sánchez Carmona */
+#include "sensor.h"
+#include "pendiente.h"
+#include "bluetooth.h"

+// Definición de pines
+#define PIN_ACELERADOR 4 // Señal PWM
+// Ponderación (para el cálculo de la aceleración)
+#define A1 0.5
+#define A2 0.2
+#define A3 0.1
+#define TASA 0.5
+// Definición de variables para controlar el algoritmo
+static unsigned long velocidad_minima = 5;
+static unsigned long velocidad_paseo = 15;
+static unsigned long velocidad_crucero = 25;
+// Definición de variables para la aceleración
+byte acelerador = 0;
+byte acelerador_deseable = 0;
+byte incremento_acelerador = 0;
+byte acelerador_final = 0;
+
+//----------------------------------------
+
+void setup() {
+  analogWrite(PIN_ACELERADOR, 0);
+  setupSensores();
+  establecerMPU();
+  configurarBT();
+}
+
+void loop() {
+
+  // Funciones de la librería "Sensor" y "Pendiente"
+  lecturaSensores();
+  lecturaDatos();
+  obtenerVelocidad();
+  obtenerAceleracion();
+  // Modo de funcionamiento
+  switch(modo){
+    case 0:
+      analogWrite(PIN_ACELERADOR, 0);
+      break;
+    case 1:
+      // Funciones del algoritmo de funcionamiento
+      decisionAcelerador();
+      obtenerIncremento();
+      acelerador_final = acelerador + TASA*incremento_acelerador;
+      analogWrite(PIN_ACELERADOR, acelerador_final);
+      break;
+    case 2:
+      if(sensor_freno_der || sensor_freno_izq || !sensor_pas || anguloX < 0){
+        acelerador = 0;
+      }
+      else{
+        acelerador = 120;
+      }
+      analogWrite(PIN_ACELERADOR, acelerador);
+      break;
+    default:
+      analogWrite(PIN_ACELERADOR, 0);
+      break;
+  }
+  // Función de la librería "Bluetooth"
+  envioDatos();
+}
+
+//----------------------------------------
+
+void decisionAcelerador(){
+  if(sensor_freno_der || sensor_freno_izq || !sensor_pas || anguloX < 0){
+    acelerador = 0;
+  }
+  else {
+    if(velocidad < velocidad_minima){
+      acelerador = 255;
+    }
+    else {
+      if (velocidad < velocidad_paseo){
+        acelerador_deseable = 120;
+      }
+      else if (velocidad < velocidad_crucero){
+        acelerador_deseable = 120*((velocidad_crucero - velocidad)/(velocidad_crucero - velocidad_paseo));
+      }
+      else {
+        acelerador_deseable = 0;
+      }
+    }
+  }
+}
+
+void obtenerIncremento(){
+
+  if(aceleracion > 0) {
+    incremento_acelerador = incremento_acelerador + A1*(acelerador_deseable - acelerador)*255;
+  }
+  if(anguloX > 0){
+    incremento_acelerador = incremento_acelerador + A2*anguloX*255;
+  }
+  if(velocidad < velocidad_crucero){
+    incremento_acelerador = incremento_acelerador + A3*(velocidad_crucero - velocidad)*255;
+  }
+
+}
+
+
+
+
+
+
+


adicao de mais botoes e correcoes no sendcodenec !

--- codigo.ino
+++ codigo.ino
@@ -191,6 +191,8 @@
     Serial.println("Sent raw");
 }

+
+
 int lastButtonState; //@Lanchinho, seria isto aqui o ultimo estado do btn 1 ?


Refactoring core_app

Refactoring core_app

--- core_app/core_app.ino
+++ core_app/core_app.ino
@@ -33,102 +33,58 @@
 char *psw = "vivo";

 /* Current State */
-int curState = ALARM_ON;
+int curState = ALARM_OFF;

 SIM908Client simClient(0,1,5,4,3);

-PubSubClient mqttClient(server, port, callback, simClient);
-// Callback function
-void callback(char* topic, byte* payload, unsigned int length) {
-  // In order to republish this payload, a copy must be made
-  // as the orignal payload buffer will be overwritten whilst
-  // constructing the PUBLISH packet.
-
-  // Allocate the correct amount of memory for the payload copy
-  //byte* p = (byte*)malloc(length);
-  // Copy the payload to the new buffer
-  //memcpy(p,payload,length);
-  //mqttClient.publish("sisafa/sisafa_test/test", p, length);
-
-  Serial.print("incomming: ");
-  Serial.print(topic);
-  Serial.print(" - ");
-  Serial.print((char *)payload);
-  Serial.println();
-
-  // Free the memory
-  //free(p);
-}
-
-  Timer gpsTimer(gpsLoopTime);
-  Timer alarmTimer(alarmLoopTime);
+PubSubClient mqttClient(server, port, msg_callback, simClient);
+
+Timer gpsTimer(gpsLoopTime);
+Timer alarmTimer(alarmLoopTime);

 void setup()
 {
-  //start serial comunication at baud rate 9600
-  //Serial.begin(9600);
-
-//  Serial.println("Connecting to network...");
-  //start shield in gsm mode
+  //starting client with baud rate 9600
   simClient.begin(9600);
-
+  //starting GPS module
   simClient.startGPS();
-
-  //attaches GPRS network and creates a web connection
-//  Serial.println("Attatching GPRS...");
-//  int res = simClient.attach(apn,usr,psw);
-
-//  Serial.println("Connecting to server...");
+  //attaching GPRS network and creating a web connection
+  int res = simClient.attach(apn,usr,psw);
   //setup used message protocol
-  //TODO: generalize for different types of protocols. ex.:
-  // MQTT, HTTP, SMS
   if (mqttClient.connect("10k2D129", "sisafa_test", "T5KIP1")) {
-    if(!mqttClient.publish("sisafa/sisafa_test/test","ARDUINO ON!")){
-//      Serial.println("message not sent...");
-    }
-    else{
-//      Serial.println("message delivered.");
-    }
+    //when connected, must subscribe topic power_op
   }
   else{
-//    Serial.println("Connection not stabilished...");
+    //restart shield
   }
 }

 void loop()
 {
- // mqttClient.loop();
-
-//  curState = ALARM_OFF;
+  mqttClient.loop();
+
   switch(curState){
-   case ALARM_OFF:{
-     handleAlarmOff();
-     break;
-   }
-   case ALARM_ON:{
-     handleAlarmOn(gpsTimer);
-     break;
-   }
-   case ALARM_BUZZ:{
-     handleAlarmBuzz(alarmTimer);
-     break;
-   }
-   default:{
-     break;
-   }
- }
-
-}
-
-//method for handling messages recieved from the web mosquitto
-void msg(String topic, String payload, char * bytes, unsigned int length)
-{
-  Serial.print("incomming: ");
-  Serial.print(topic);
-  Serial.print(" - ");
-  Serial.print(payload);
-  Serial.println();
-
+    case ALARM_OFF:{
+      handleAlarmOff();
+      break;
+    }
+    case ALARM_ON:{
+      handleAlarmOn(gpsTimer);
+      break;
+    }
+    case ALARM_BUZZ:{
+      handleAlarmBuzz(alarmTimer);
+      break;
+    }
+    default:{
+      break;
+    }
+  }
+}
+
+//function for handling messages recieved from the server
+void msg_callback(char* topic, byte* payload, unsigned int length)
+{
   // first char from payload converted from ASCII to int [0-9]
   int op = payload[0] - 48;


Reduced update interval.

Reduced update interval.

--- mech/mech.ino
+++ mech/mech.ino
@@ -215,7 +215,7 @@
 }

 void sendStatusUpdates() {
-	static const unsigned long REFRESH_INTERVAL = 20; // ms
+	static const unsigned long REFRESH_INTERVAL = 1000; // ms
 		static unsigned long lastRefreshTime = 0;
 		if(millis() - lastRefreshTime >= REFRESH_INTERVAL)
 		{


enum : ok, machine d'etats avec les etats en claire

--- calibrateur.ino
+++ calibrateur.ino
@@ -46,8 +46,26 @@
 int resultatImpulsion[19];
 long resultatTemps[19];

-
-defineTimerRun(rafraichirAffichage,800) //ne pas mettre ce timer a une valeur trop faible pour éviter le rebond lors de l'apuui bouton (ne pas compter des apuis multiple pour un seul appuie voulu)
+enum {
+		POTAR = 3,
+		MILIEU = 4,
+		USB = 1,
+		ETALORSWEEP = 10,
+		REGPOTENCINVIT = 11,
+		REGLPOTENC = 12,
+		MESREFPULSE = 13,
+		FINDMINMAX = 14,
+		WAITCLIC = 15,
+		DISPRESULT = 16,
+		WAITCLIC2 = 17,
+		SWEEPTOMIN = 2,
+		SWEPPTOMAX = 20
+};
+
+
+defineTimerRun(rafraichirAffichage,800)
+ //ne pas mettre ce timer a une valeur trop faible pour éviter le rebond
+ //lors de l'apuui bouton (ne pas compter des apuis multiple pour un seul appuie voulu)
 {
 	 //Serial.println("affichagePP");
 	  affichage.refreshAfficheur();
@@ -56,11 +74,10 @@
 defineTimerRun(surveilleBouton,40)
 //ne pas mettre ce timer a une valeur trop faible pour éviter le rebond lors de
 //l'apuui bouton (ne pas compter des apuis multiple pour un seul appuie voulu)
-        {
-         //Serial.println("bouton");
-          boutonP.refreshBouton();
-
-          }
+{
+	//Serial.println("bouton");
+	boutonP.refreshBouton();
+}

 defineTimerRun(surveilleServo,100) //conserver 100 ou modifier le "*0.1" dans méthode appliqueobjectif du Servo
 {
@@ -78,9 +95,9 @@

 defineTask(reflechi)
     void reflechi::setup()
-       {
-
-        }
+	{
+
+	}

     void reflechi::loop()
     //defineTimerRun(reflechi,40)
@@ -115,12 +132,12 @@
 		int objTest (0);
 		switch (etatCalibrateur)
 			{
-				case 1:
+				case USB :
 					Serial.println(F("Double Clic pour procéder à l'etlonnage"));
 					etatCalibrateur=10;
 					break;

-				case 10:
+				case ETALORSWEEP :
 					if (boutonP.hasBeenClicked())
 						{
 							boutonP.acquit();
@@ -138,7 +155,7 @@
 					}
 					break;

-				case 11:
+				case REGPOTENCINVIT :
 					leServo.setObjectif(leServo.getMilieu());
 					// pour etre certain qu'on aprt du milieu et que le servo
 					//n'est pas n'importe ou suite à des manip de type sweep
@@ -150,7 +167,7 @@
 					}
 					break;

-				case 12 :
+				case REGLPOTENC :
 					// Serial.print("obj potence=");
 					// Serial.print(potence.getObjectif());
 					// Serial.print("   Encours potence=");
@@ -167,7 +184,7 @@
 						}
 					break;

-				case 13: //mesure des impulsion de reference sur une rotation de delta
+				case MESREFPULSE: //mesure des impulsion de reference sur une rotation de delta
 					Serial.println("ICI");
 					compteur=0;
 					compteurRef=0;
@@ -185,7 +202,7 @@
 							etatCalibrateur=1;
 						}
 					break;
-				case 14:
+				case FINDMINMAX:
 					Serial.println("lalalal");
 					//sequence pour aller au max puis au min et de déterminer les pwm Min et Max du servo
 					while (compteur>compteurRef-ERREURCOMPTAGE)
@@ -247,7 +264,7 @@
 					etatCalibrateur=15;

-				case 15:
+				case WAITCLIC:
 					if (boutonP.hasBeenClicked())
 						{
 							boutonP.acquit();
@@ -256,7 +273,7 @@
 						}
 					break;

-				case 16:
+				case DISPRESULT:
 					Serial.println(F("Alors quelle sens de rotation ?") );
 					Serial.print(resultatImpulsion[5]);
 					Serial.print(F(" impulsions en "));
@@ -274,7 +291,7 @@
 					etatCalibrateur=17;
 					break;

-				case 17:
+				case WAITCLIC2:
 					if (boutonP.hasBeenClicked())
 						{
 							boutonP.acquit();
@@ -292,7 +309,7 @@
 						}
 					break ;

-				case 2:
+				case SWEEPTOMIN:
 					if (leServo.isMin())
 						{
 							etatCalibrateur=20;
@@ -307,7 +324,7 @@
 						}
 					break;

-				case 20:
+				case SWEPPTOMAX:
 					if (leServo.isMax())
 						{
 							etatCalibrateur=2;
@@ -322,7 +339,7 @@
 						}
 					break;

-				case 3:
+				case POTAR:
 					int temp;
 					int potarVal;
 					potarVal=lePotar.getValue();
@@ -350,7 +367,7 @@
 						}
 					break;

-				case 4:
+				case MILIEU:
 					leServo.setObjectif(leServo.getMilieu());
 					if (boutonP.hasBeenClicked())
 						{
@@ -372,62 +389,31 @@

 void setup()
-   {
-     Serial.begin(57600);
-     potence.setPotence();
-     leServo.setType(true);
-     Wire.begin();
-
-    Serial.println("hello");
-    mySCoop.start();
-   temp=millis();
-   //etatCalibrateur=3; fait dans l'init de la variable
-   affichage.affiche(3);
-   attachInterrupt(0, updatePulseCompteur, CHANGE ); // Int0= la pin N°2 sur un UNO
-
-
-     }
+{
+	Serial.begin(57600);
+	potence.setPotence();
+	leServo.setType(true);
+	Wire.begin();
+
+	Serial.println("hello");
+	mySCoop.start();
+	temp=millis();
+	//etatCalibrateur=3; fait dans l'init de la variable
+	affichage.affiche(3);
+	attachInterrupt(0, updatePulseCompteur, CHANGE ); // Int0= la pin N°2 sur un UNO
+}
  void updatePulseCompteur()
-    {
-      compteur++;
-    }
+{
+	compteur++;
+}

- void loop ()
-
-   {
-     mySCoop.sleep(1);
-
-//    if (boutonP.hasBeenClicked()==true)
-//      {
-//        Serial.println("clic ");
-//        boutonP.acquit();
-//
-//        }
-//   if (boutonP.hasBeenDoubleClicked()==true)
-//      {
-//        Serial.println("DoubleClic ");
-//        boutonP.acquit();
-//
-//        }
-//
-//    if (boutonP.hasBeenLongClicked()==true)
-//      {
-//        Serial.println("Long Clic ");
-//        boutonP.acquit();
-//
-//        }
-
-
-    if (millis()>2000+temp)
-         {
-
-         //Serial.print("valeur potar : ");
-         //Serial.println(lePotar.getValue());
-         temp=millis();
-
-         //Serial.print("Etat : ");
-    //Serial.println(etatCalibrateur);
-         }
-
-     }
-
+void loop ()
+{
+	mySCoop.sleep(1);
+	if (millis()>2000+temp)
+		{
+			temp=millis();
+		}
+
+}
+


successfully tested

successfully tested

--- module/module.ino
+++ module/module.ino
@@ -30,7 +30,6 @@
 void loop() {
 	bool responseFlag = false;
 	unsigned long elapsedTime = 0;
-	unsigned long readStart, readEnd = 0;
 	digitalWrite(ledPin, LOW);

 	while(responseFlag == false) {
@@ -40,23 +39,22 @@
 	}

 	if(responseFlag == true) {
-		readStart = millis();
+		digitalWrite(ledPin, HIGH);
 		MF_READ(0x01, 0x05);
-		while((readEnd - readStart) < readDelay) {
-			readEnd = millis();
-		}
+		delay(200);
 		responseFlag = getResponse();
 		if(responseFlag == false)
 			Serial.println("Unexpected result");
+		responseFlag = false;
 	}

 	elapsedTime = accumulator(false);

 	MF_WRITE(0x01, 0x05, elapsedTime);
+	delay(200);
 	responseFlag = getResponse();
 	if(responseFlag == false)
 		Serial.println("Unexpected result");
-	delay(100000);
 }

 bool getResponse(void) {


Switching to timed polling instead of delaying

--- module/module.ino
+++ module/module.ino
@@ -146,6 +146,7 @@
 unsigned long accumulator(unsigned char serialNumber[], unsigned long elapsedTime) {
 	// some variables used in this scope
 	unsigned long startTime = 0;
+	unsigned long lastPollTime = 0;
 	unsigned int periodX, periodY;
 	unsigned int pollCounter = 0;
 	int signals[] = { 0, 0, 0, 0, 0 };
@@ -158,127 +159,95 @@
 	}

 	while (1) {
-		// Polling logic (approximately every second)
-		sendCommand(CMD_GET_SNR, blockID, machineID, keyA, NULL);
-		// if card is missing, increment a counter and blink LED?? too slow
-		if (!getResponse(serialNumber)) {
-			digitalWrite(ledPin, (digitalRead(ledPin) == HIGH ? LOW : HIGH));
-			pollCounter += 1;
-			// if the counter reaches a specified timeout, return
-			if (pollCounter == pollTimeout) {
-				//soundFeedback(isReject);
-				getStringFromMem(cancel);
-				elapsedTime = calcTime(startTime);
-
-				// Any valid accumulated time will be returned
-				if ((startTime > 0) && (freeTime < elapsedTime) && (elapsedTime < 5*quota)) {
-          			return elapsedTime;
+		if ( (millis() - lastPollTime) > pollInterval ) {
+			// Polling logic (approximately every second)
+			sendCommand(CMD_GET_SNR, blockID, machineID, keyA, NULL);
+			// if card is missing, increment a counter and blink LED?? too slow
+			if (!getResponse(serialNumber)) {
+				digitalWrite(ledPin, (digitalRead(ledPin) == HIGH ? LOW : HIGH));
+				pollCounter += 1;
+				// if the counter reaches a specified timeout, return
+				if (pollCounter == pollTimeout) {
+					//soundFeedback(isReject);
+					getStringFromMem(cancel);
+					elapsedTime = calcTime(startTime);
+
+					// Any valid accumulated time will be returned
+					if ((startTime > 0) && (freeTime < elapsedTime) && (elapsedTime < 5*quota)) {
+	          			return elapsedTime;
+					}
+					else {
+						return 0;
+					}
+
 				}
-				else {
-					return 0;
+			}
+			else {
+				digitalWrite(ledPin, HIGH);
+				pollCounter = 0;
+			}
+			// End Polling Logic
+
+			// Begin signal monitoring logic
+			periodX = pulseIn(driverX, HIGH);
+			periodY = pulseIn(driverY, HIGH);
+
+	    	signals[i] = isRange(periodX + periodY);
+
+			// Only here temporarily for debugging
+			if (1) {
+				Serial.print("PeriodX: "); Serial.print(periodX);
+				Serial.print(" PeriodY: "); Serial.print(periodY);
+				Serial.print(" "); Serial.print(signals[0]); Serial.print(signals[1]); Serial.print(signals[2]); Serial.print(signals[3]); Serial.print(signals[4]);
+				Serial.print(" "); Serial.print(numValid); Serial.print(" "); Serial.print(numInvalid);
+				Serial.print(" Start Time: "); Serial.println(startTime);
+			}
+
+			// if periodX and periodY IS a valid pair
+			if ( signals[i] == 1 ) {
+				numValid += 1;
+				numInvalid = 0;
+				// a job is detected when we get enough valid signals in a row
+				// begin stopwatch
+				if (numValid == sampleSize) {
+					if (startTime == 0) {
+						startTime = millis();
+					}
 				}
-
-			}
-		}
-		else {
-			digitalWrite(ledPin, HIGH);
-			pollCounter = 0;
-		}
-		// End Polling Logic
-
-		// Begin signal monitoring logic
-		periodX = pulseIn(driverX, HIGH);
-		periodY = pulseIn(driverY, HIGH);
-
-    	signals[i] = isRange(periodX + periodY);
-
-		// Only here temporarily for debugging
-		if (1) {
-			Serial.print("PeriodX: "); Serial.print(periodX);
-			Serial.print(" PeriodY: "); Serial.print(periodY);
-			Serial.print(" "); Serial.print(signals[0]); Serial.print(signals[1]); Serial.print(signals[2]); Serial.print(signals[3]); Serial.print(signals[4]);
-			Serial.print(" "); Serial.print(numValid); Serial.print(" "); Serial.print(numInvalid);
-			Serial.print(" Start Time: "); Serial.println(startTime);
-		}
-
-		// if periodX and periodY IS a valid pair
-		if ( signals[i] == 1 ) {
-			numValid += 1;
-			numInvalid = 0;
-			// a job is detected when we get enough valid signals in a row
-			// begin stopwatch
-			if (numValid == sampleSize) {
-				if (startTime == 0) {
-					startTime = millis();
+			}
+			// if periodX and periodY IS NOT a valid pair
+			if ( signals[i] == 0 ) {
+				numValid = 0;
+				numInvalid += 1;
+				// check if enough negative signals have been detected
+				// calculate elapsed time
+				if (numInvalid == sampleSize) {
+					elapsedTime = calcTime(startTime);
+
+					// if a job was detected, return
+					if ((startTime > 0) && (freeTime < elapsedTime) && (elapsedTime < 5*quota)) {
+						return elapsedTime;
+					}
+					else {
+						startTime = 0;
+						elapsedTime = 0;
+						numValid = 0;
+						numInvalid = 0;
+					}
 				}
 			}
-		}
-		// if periodX and periodY IS NOT a valid pair
-		if ( signals[i] == 0 ) {
-			numValid = 0;
-			numInvalid += 1;
-			// check if enough negative signals have been detected
-			// calculate elapsed time
-			if (numInvalid == sampleSize) {
-				elapsedTime = calcTime(startTime);
-
-				// if a job was detected, return
-				if ((startTime > 0) && (freeTime < elapsedTime) && (elapsedTime < 5*quota)) {
-					return elapsedTime;
-				}
-				else {
-					startTime = 0;
-					elapsedTime = 0;
-					numValid = 0;
-					numInvalid = 0;
-				}
-			}
-		}
-
-		if (i == sampleSize - 1) {
-			i = 0;
-		}
-    	else {
-      		i += 1;
-    	}
-
-    	digitalWrite(interlock, HIGH);
-		delay(pollInterval);
-	}
-}
-/*
-	Checks the previous signals and counts the number of
-	valid and invalid signals recorded.
-
-	Returns 1 if all valid
-			0 if all invalid
-			-1 otherwise
-*/
-int checkHistory(int signals[]) {
-	int i = 0;
-	int numValid, numInvalid = 0;
-	for (i = 0; i < sampleSize; i++) {
-		if (signals[i] == 1) {
-			numValid += 1;
-		}
-		if (signals[i] == 0) {
-			numInvalid += 1;
-		}
-	}
-
-	if (1) {
-		Serial.print(numValid); Serial.print(numInvalid); Serial.print(" ");
-	}
-	//delay(debounce);
-
-	if (numValid == sampleSize) {
-		return flag.detectedJobStart;
-	}
-	else if (numInvalid == sampleSize) {
-		return flag.detectedJobEnd;
-	}
-	else {
-		return flag.idle;
+
+			if (i == sampleSize - 1) {
+				i = 0;
+			}
+	    	else {
+	      		i += 1;
+	    	}
+
+	    	digitalWrite(interlock, HIGH);
+			//delay(pollInterval);
+			lastPollTime = millis();
+		}
 	}
 }
 /*void soundFeedback(bool isReject) {


Refactor bathroom example.

Refactor bathroom example.

--- vor-arduino/examples/bathroom/bathroom.ino
+++ vor-arduino/examples/bathroom/bathroom.ino
@@ -9,7 +9,7 @@

 #define INTERVAL 30000

-#define PAYLOAD_FORMAT "{\"id\":\"toilet8am\",\"type\":\"toilet\",\"reserved\":%s,\"methane\":%d}"
+#define PAYLOAD_FORMAT "{\"id\":\"toilet8am\",\"type\":\"toilet\",\"reserved\":%s,\"methane\":%s}"

 #define MOTION1_PIN 2
 #define MOTION2_PIN 3
@@ -44,18 +44,18 @@

     bool change = (prevMotion1Value != motion1Value || prevMotion2Value != motion2Value) && // some change
         ( (prevMotion1Value == HIGH && prevMotion2Value == HIGH) || // previously no motion
-          (motion1Value == HIGH && motion1Value == HIGH) ); // at the moment no motion
+          (motion1Value == HIGH && motion2Value == HIGH) ); // at the moment no motion

     prevMotion1Value = motion1Value;
     prevMotion2Value = motion2Value;
-    bool reservedValue = motion1Value == LOW && motion2Value == LOW;
+    bool reservedValue = motion1Value == LOW || motion2Value == LOW;

     if (change || now - intervalTime > INTERVAL) {
         intervalTime = now;

         const char* reserved = reservedValue ? "true" : "false";
         char methane[16];
-        dtostrf(methaneValue, 4, 2, methane);
+        dtostrf(methaneValue, 16, 2, methane);
         char message[128];
         sprintf(message, PAYLOAD_FORMAT, reserved, methane);


fix: remove hostname define

fix: remove hostname define

--- ArduinoFirmwareEsp/ArduinoFirmwareEsp.ino
+++ ArduinoFirmwareEsp/ArduinoFirmwareEsp.ino
@@ -1,5 +1,4 @@
 #include "CommLgc.h"
-//#include "utility/wifi_utils.h"

 #include <ESP8266WiFi.h>
 #include <ESP8266mDNS.h>
@@ -11,11 +10,9 @@
 #include <Hash.h>
 #include <ESP8266WebServer.h>

-#define HOSTNAME "Arduino-Primo"
-
 ESP8266WebServer server(80);    //server UI
 bool SERVER_STOP = false;       //check stop server
-// MCU McuType = NRF52;
+
 void setup() {

   ArduinoOTA.begin();
@@ -29,7 +26,7 @@

   ArduinoOTA.handle();
   CommunicationLogic.handle();
-  if(CommunicationLogic.UI_alert){			//stop UI SERVER){}
+  if(CommunicationLogic.UI_alert){			//stop UI SERVER
     if(!SERVER_STOP){
       server.stop();
       SERVER_STOP = true;
@@ -37,16 +34,5 @@
   }
   else
     handleWBServer();
-  // unsigned long currentMillis = millis();
-  // if (currentMillis - previousMillis >= interval) {
-  //   // save the last time you blinked the LED
-  //   previousMillis = currentMillis;
-  //   if (ledState == LOW) {
-  //     ledState = HIGH;
-  //   } else {
-  //     ledState = LOW;
-  //   }
-  //   digitalWrite(WIFI_LED, ledState);
-  // }

 }


Improve source code

Improve source code

--- ArduinoMid.ino
+++ ArduinoMid.ino
@@ -48,6 +48,7 @@
 // Output for Sony Alpine emulation
 const int sonyPin = A0;
 const int sonyShiftPin = A2;
+const int alpinePin = 3;
 //
 // Defines min/max menu amplitude
 const int maxMenuNumber = 2;
@@ -75,60 +76,78 @@
     lcd.begin(16,2);
     //
     // Define Alpine Pin
-    pinMode(alpPin, OUTPUT);
+    pinMode(alpinePin, OUTPUT);
 }

 void loop() {
+    Serial.println("Entering in  loop...");
     //
     // Get navigation states
     buttonStateUp = digitalRead(buttonPinUp);
     buttonStateDw = digitalRead(buttonPinDw);
     //
     // Handle navigation buttons
-    handleButtonNavigation(buttonStateUp,buttonStateDw);
+    int navigation =     handleButtonNavigation(buttonStateUp,buttonStateDw);
     //
     // Switch menu
-    switch ( navigationState ) {
+    switch ( navigation ) {
+        //
+        // First menu
+        case 0:
+            Serial.println("Entering in /0/");
+            handleIndexMenu();
+        break;
+        //
+        // Second menu
         case 1:

           break;
+        //
+        // Third menu
         case 2:

           break;
-
-        case 0:
-            handleDefaultMenu();
-        break;
         //
         // MID Introduction ...
         default:
+            Serial.println("Entering in  /default/ ");
             handleIntroduceMenu();
-            navigationState++;
         break;
       }

-
-
-}
-
-/**
-        Handle MID's steering buttons
+}
+
+/**
+        Handle MID's steering buttons navigation
  */
 int handleButtonNavigation(int stateUp,int stateDw){
     Serial.println(stateUp);
     Serial.println(stateDw);
-
-
+    //
+    // Cursor upper
     if (buttonStateUp == HIGH) {
         navigationState++;
     }
-
+    //
+    // Cursor down
      if (buttonStateDw == HIGH) {
         navigationState--;
+     }
+    //
+    // Move cursor to Height number to loop chain
+    if(navigationState >= maxMenuNumber){
+        navigationState = minMenuNumber;
     }
-
+    //
+    // Move cursor to lower number to loop chain
+    if(navigationState <= minMenuNumber){
+        navigationState = maxMenuNumber;
+    }
     // Debug info ...
     Serial.println(navigationState);
+    //
+    // Return navigation cursor
+    return navigationState;
 }

 /**
@@ -140,32 +159,34 @@
 /**
         Handle Default menu
  */
-void handleDefaultMenu(){
+void handleIndexMenu(){

 }
 /**
         Handle Introduce menu
  */
 void handleIntroduceMenu(){
-     lcd.print("Welcome to "); // Prints "Arduino" on the LCD
-     delay(3000); // 3 seconds delay
-     lcd.setCursor(11,0); // Sets the location at which subsequent text written to the LCD will be displayed
+     lcd.print("Welcome... "); // Prints "Arduino" on the LCD
+     delay(1500);
+     lcd.clear();
      lcd.print("Opel");
+     lcd.setCursor(7,0); // Sets the location at which subsequent text written to the LCD will be displayed
+     lcd.print("Astra");
+     delay(1500);
+     lcd.setCursor(1,2);
+          lcd.blink(); //Displays the blinking LCD cursor
+          lcd.setCursor(2,1);
+          lcd.print("Loading ...");
+
      delay(3000);
-     lcd.setCursor(1,2);
-     lcd.print("Astra");
-     delay(3000);
-     lcd.clear(); // Clears the display
-     lcd.blink(); //Displays the blinking LCD cursor
-     delay(4000);
-     lcd.setCursor(2,1);
-     lcd.print("Loading ...");
-     delay(3000);
-     lcd.noBlink(); // Turns off the blinking LCD cursor
-     lcd.cursor(); // Displays an underscore (line) at the position to which the next character will be written
+     lcd.clear();
+     lcd.noBlink();
      delay(4000);
      lcd.noCursor(); // Hides the LCD cursor
      lcd.clear(); // Clears the LCD screen
+     //
+     //  When done introducing change move to nex menu
+     navigationState++;
 }

 /**


Tweak code after watching stepper motion

--- shipStation/stepper_demo/stepper_demo.ino
+++ shipStation/stepper_demo/stepper_demo.ino
@@ -1,5 +1,5 @@
 #include <AccelStepper.h>
-#include <MultiStepper.h>
+//#include <MultiStepper.h>
 #include <math.h>

 /* Written for ST6600 stepper driver
@@ -15,66 +15,58 @@
 #define STEPANGLE 0.002094395
 #define PI 3.1415926535897932384626433832795

-AccelStepper xAxis(1,8,9);
-AccelStepper yAxis(1,10,11);
-MultiStepper steppers;
+AccelStepper xAxis(1,9,8);
+AccelStepper yAxis(1,11,10);
+//MultiStepper steppers;

-long positions[2];        // x, y
 float angle = 0;          // Radians, used to find x,y on a circle
 long centerX = 0;         // May be useful later
 long centerY = 0;
-long radius = 100;
+long radius = 20000;

 void setup()
 {
-  // Initialize pins
-  pinMode(8, OUTPUT);     // x direction pin
-  pinMode(9, OUTPUT);     // x step pin
-  pinMode(10, OUTPUT);    // y direction pin
-  pinMode(11, OUTPUT);    // y step pin
-
   Serial.begin(115200);

   // Adjust these values after seeing it in action.
-  xAxis.setMaxSpeed(300);
-  xAxis.setAcceleration(100);
-  yAxis.setMaxSpeed(300);
-  yAxis.setAcceleration(100);
-
-  // Add individual steppers to the multistepper object
-  steppers.addStepper(xAxis);
-  steppers.addStepper(yAxis);
+  // 1/4  step: 1600, 800
+  // 1/16 step: 10000, 5000
+  xAxis.setMaxSpeed(10000);
+  xAxis.setAcceleration(5000);
+  yAxis.setMaxSpeed(10000);
+  yAxis.setAcceleration(5000);
 }

-void updatePos(float degs)
-{
-    // Moves to a point on a circle, based on radius and angle
-    // Blocks until finished
-    float rads = degs * PI / 180;
-    positions[0] = radius*cos(rads)+centerX; // x
-    positions[1] = radius*sin(rads)+centerY; // y
-    Serial.print("Deg = ");
-    Serial.print(degs);
+
+void moveRandomly(){
+  long randNum, xPos, yPos, curTime, endTime;
+  while(1){
+    // Random numbers from -25,000 to +25,000
+    xPos = random(30000) - 15000;
+    xAxis.moveTo(xPos);
+
+    yPos = random(30000) - 15000;
+    yAxis.moveTo(yPos);
+
+    curTime = millis();
+    endTime = curTime + random(10000);
+
+    Serial.print("Moving to ");
+    Serial.print(xPos);
     Serial.print(", ");
-    Serial.print(positions[0]);
-    Serial.print(", ");
-    Serial.print(positions[1]);
-    Serial.println(".");
-    steppers.moveTo(positions);
-    steppers.runSpeedToPosition();
+    Serial.print(yPos);
+    Serial.print(", for ");
+    Serial.print(endTime - curTime);
+    Serial.println(" millis.");
+
+    while(millis() < endTime){
+      xAxis.run();
+      yAxis.run();
+    }
+  }
 }

 void loop()
 {
-  // Spiral outwards
-  for(int degs=0; degs<360; degs++){
-    updatePos(degs);
-    radius += 10;
-  }
-
-  // Spiral inwards
-  for(int degs=360; degs>0; degs--){
-    updatePos(degs);
-    radius -= 10;
-  }
+   moveRandomly();
 }


Update 006_Tlačidlo.ino

Update 006_Tlačidlo.ino


Fixup formatting

Fixup formatting

--- SimpleNeopixelDemo/SimpleNeopixelDemo.ino
+++ SimpleNeopixelDemo/SimpleNeopixelDemo.ino
@@ -48,7 +48,7 @@

 void sendBit( bool bitVal ) {

-    if (  bitVal ) {
+    if (  bitVal ) {				// 0 bit

 		asm volatile (
 			"sbi %[port], %[bit] \n\t"				// Set the output bit
@@ -63,11 +63,11 @@
 			[port]		"I" (_SFR_IO_ADDR(PIXEL_PORT)),
 			[bit]		"I" (PIXEL_BIT),
 			[onCycles]	"I" (NS_TO_CYCLES(T1H) - 2),		// 1-bit width less overhead  for the actual bit setting, note that this delay could be longer and everything would still work
-			[offCycles] "I" (NS_TO_CYCLES(T1L) - 2)			// Minimum interbit delay. Note that we probably don't need this at all since the loop overhead will be enough, but here for correctness
-
-			);
+			[offCycles] 	"I" (NS_TO_CYCLES(T1L) - 2)			// Minimum interbit delay. Note that we probably don't need this at all since the loop overhead will be enough, but here for correctness
+
+		);

-    } else {
+    } else {					// 1 bit

 		// **************************************************************************
 		// This line is really the only tight goldilocks timing in the whole program!
@@ -87,9 +87,9 @@
 			[port]		"I" (_SFR_IO_ADDR(PIXEL_PORT)),
 			[bit]		"I" (PIXEL_BIT),
 			[onCycles]	"I" (NS_TO_CYCLES(T0H) - 2),
-			[offCycles] "I" (NS_TO_CYCLES(T0L) - 2)
-
-			);
+			[offCycles]	"I" (NS_TO_CYCLES(T0L) - 2)
+
+		);

     }


minor change 1

minor change 1

--- proj/hypercube/HCS/Animations.ino
+++ proj/hypercube/HCS/Animations.ino
@@ -360,7 +360,7 @@
   static boolean in_fade_rev = false;
   static boolean out_fade_rev = false;
   static const double in_rate_increase = 1.2;
-  static const double out_rate_increase = 1.75;
+  static const double out_rate_increase = 2.5;

   // Update the positions of both the strips and reset the array
   if(shell == INNER) {