 
 void loop()
 {
+  double alpha = 0;
   digitalWrite(HbridgeEnablePin, HIGH);
-  // Read the analog in value
-  // The range was reduced 
-  double sensorValueMin = 255;//0
-  double sensorValueMax = 767;//1023
-  double deadBand = 0.05; // Use to ensure zero speed. Should not be zero
+  
+  alpha = computeLogicState();
+  delay(minTime_ms);
+
+  alpha = computeLogicState();
+  double initialTime = millis();
+  double elapsedTime_ms = millis() - initialTime;
+  while (elapsedTime_ms < minTime_ms/alpha*(1-alpha)-minTime_ms)
+  {
+    digitalWrite(HbridgeEnablePin, LOW);
+    delay(minTime_ms);
+
+    alpha = computeLogicState();
+    elapsedTime_ms = millis() - initialTime;
+   
+  }
+  digitalWrite(HbridgeEnablePin, LOW);
+  delay(fabs(minTime_ms/alpha*(1-alpha)- elapsedTime_ms));
+
+//  // print the results to the serial monitor:
+//  Serial.print("alphaManual = " );                       
+//  Serial.print(alphaSigned);      
+//  Serial.print("\t alphaUsed = ");      
+//  Serial.println(alphaSigned);   
+}
+
+double computeLogicState()
+{
   sensorValue = analogRead(analogInPin);
-  
-  // If the analog value is changed, it means that the user wants to take control manually
-  // so fallback to manual control
-  if (fabs(initialSensorValue-sensorValue)>10)
+  // If the analog value is changed, it means that the user wants to take control with the joystick
+  // so fallback to joystick control
+  if (fabs(initialSensorValue-sensorValue) > 10)
   {
     isSerialControl = false;
   }
-  if (sensorValue < 10)
-  { 
+	
+  // Fallback to manual control if the analog voltage is close to zero (probably unplugged)
+  isManualControl = (sensorValue < 10);
+
+  if (isManualControl)  
+  {
     // Motor is free to move to enable manual control
     digitalWrite(HbridgeEnablePin, LOW);
   }
-  if (false==isSerialControl)
+  
+  // If not in Serial control overwrite the value 
+  if (false == isSerialControl)
   {
     alphaSigned = 2*((sensorValue-sensorValueMin)/(sensorValueMax - sensorValueMin)-0.5);  
   }
+  // The saturation ensures the motor can be stopped and avoids division by zero
   double alpha = max(fabs(alphaSigned), deadBand);
   alpha = min(alpha, 1);
 
-  if (alphaSigned>fabs(deadBand))
+  if (alphaSigned > fabs(deadBand))
   {
     // Forward rotation
     digitalWrite(HbridgeLogicPin1, HIGH);

To stop the serial control send "o".
There is not guarantee that there is a linear relationship between alpha and the rotation speed
*/
// \todo this code needs refactorization

// Minimal time to have motor starting at maximum voltage. This will depend on the motor used
// Try to reduce to get a smooth motion

    }
    else
    {
      // Brake ?
      digitalWrite(HbridgeLogicPin1, LOW);
      digitalWrite(HbridgeLogicPin2, LOW);
    }
	// \todo: add an input to enable manual rotation of the motor
  }
  return alpha;
}


