Explorar el Código

handle proper reset between patterns

Tuan Nguyen hace 1 año
padre
commit
10c3559fbd
Se han modificado 2 ficheros con 69 adiciones y 23 borrados
  1. 24 2
      app.py
  2. 45 21
      arduino_code/arduino_code.ino

+ 24 - 2
app.py

@@ -10,16 +10,18 @@ app = Flask(__name__)
 
 # Theta-rho directory
 THETA_RHO_DIR = './patterns'
+IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
 os.makedirs(THETA_RHO_DIR, exist_ok=True)
 
 # Serial connection (default None, will be set by user)
 ser = None
 stop_requested = False
 
+
 def list_serial_ports():
     """Return a list of available serial ports."""
     ports = serial.tools.list_ports.comports()
-    return [port.device for port in ports]
+    return [port.device for port in ports if port.device not in IGNORE_PORTS]
 
 def connect_to_serial(port, baudrate=115200):
     """Connect to the specified serial port."""
@@ -83,7 +85,7 @@ def send_command(command):
         time.sleep(0.5)  # Small delay to avoid busy waiting
 
 def run_theta_rho_file(file_path):
-    """Run a theta-rho file by interpolating straight paths and sending data in optimized batches."""
+    """Run a theta-rho file by sending data in optimized batches."""
     global stop_requested
     stop_requested = False
 
@@ -114,6 +116,7 @@ def run_theta_rho_file(file_path):
 
     # Reset theta after execution or stopping
     reset_theta()
+    ser.write("FINISHED\n".encode())
                 
 def reset_theta():
     ser.write("RESET_THETA\n".encode())
@@ -125,6 +128,22 @@ def reset_theta():
                 print("Theta successfully reset.")
                 break
         time.sleep(0.5)  # Small delay to avoid busy waiting
+        
+def read_serial_responses():
+    """Continuously read and print all responses from the Arduino."""
+    global ser
+    if ser is None or not ser.is_open:
+        print("Serial connection not established.")
+        return
+    
+    while True:
+        try:
+            if ser.in_waiting > 0:
+                response = ser.readline().decode().strip()
+                print(f"Arduino response: {response}")
+        except Exception as e:
+            print(f"Error reading from serial: {e}")
+            break
 
 @app.route('/')
 def index():
@@ -271,4 +290,7 @@ def download_file(filename):
     return send_from_directory(THETA_RHO_DIR, filename)
 
 if __name__ == '__main__':
+    # Start the thread for reading Arduino responses
+    threading.Thread(target=read_serial_responses, daemon=True).start()
+    
     app.run(debug=True, host='0.0.0.0', port=8080)

+ 45 - 21
arduino_code/arduino_code.ino

@@ -12,6 +12,7 @@
 
 #define rot_total_steps 16000.0
 #define inOut_total_steps 5760.0
+#define gearRatio 10
 
 #define BUFFER_SIZE 10 // Maximum number of theta-rho pairs in a batch
 
@@ -30,7 +31,8 @@ bool batchComplete = false;
 // Track the current position in polar coordinates
 float currentTheta = 0.0; // Current theta in radians
 float currentRho = 0.0;   // Current rho (0 to 1)
-bool skipInterpolation = true;
+bool isFirstCoordinates = true;
+float totalRevolutions = 0.0; // Tracks cumulative revolutions
 
 void setup()
 {
@@ -51,10 +53,28 @@ void setup()
     homing();
 }
 
-void resetThetaToNearestMultiple()
+void printCurrentCoordinates(String description)
 {
-    currentTheta = 0;
-    skipInterpolation = true; // Set flag to skip interpolation for the next movement
+    Serial.print(description);
+    Serial.print(" Theta: ");
+    Serial.print(currentTheta);
+    Serial.print(" Rho: ");
+    Serial.println(currentRho);
+}
+
+void printCurrentMotorPositions()
+{
+  Serial.print(" Rot: ");
+  Serial.print(rotStepper.currentPosition());
+  Serial.print(" Inout: ");
+  Serial.println(inOutStepper.currentPosition());
+}
+
+void resetTheta(float targetTheta)
+{
+    // currentTheta = 0;
+    isFirstCoordinates = true; // Set flag to skip interpolation for the next movement
+    Serial.println("THETA_RESET"); // Notify Python
 }
 
 void loop()
@@ -71,20 +91,21 @@ void loop()
             return;
         }
 
-        if (input == "RESET_THETA")
+        if (input == "HOME")
         {
-            resetThetaToNearestMultiple(); // Reset currentTheta
-            Serial.println("THETA_RESET"); // Notify Python
-            Serial.println("READY");
+            homing();
             return;
         }
 
-        if (input == "HOME")
+        if (input == "RESET_THETA")
         {
-            homing();
+            resetTheta(0); // Reset currentTheta
+            Serial.println("THETA_RESET"); // Notify Python
+            Serial.println("READY");
             return;
         }
 
+
         // If not a command, assume it's a batch of theta-rho pairs
         if (!batchComplete)
         {
@@ -125,26 +146,26 @@ void loop()
 
         for (int i = 0; i < bufferCount; i++)
         {
-            if (skipInterpolation)
+            if (isFirstCoordinates)
             {
-                // float targetRotSteps = buffer[0][0] * (rot_total_steps / (2.0 * M_PI));
-                // rotStepper.setCurrentPosition(targetRotSteps);
+                // Directly move to the first coordinate of the new pattern
+                long initialRotSteps = buffer[0][0] * (rot_total_steps / (2.0 * M_PI));
+                rotStepper.setCurrentPosition(initialRotSteps);
+                inOutStepper.setCurrentPosition(inOutStepper.currentPosition() - totalRevolutions * rot_total_steps / gearRatio);
                 currentTheta = buffer[0][0];
-                // Move only the in-out axis to the first coordinate's rho
+                totalRevolutions = 0;
+                isFirstCoordinates = false; // Reset the flag after the first movement
                 movePolar(buffer[0][0], buffer[0][1]);
-                // Reset the flag after the first movement
-                skipInterpolation = false;
             }
-            else
-            {
+              else
+              {
                 // Use interpolation for subsequent movements
                 interpolatePath(
                     startTheta, startRho,
                     buffer[i][0], buffer[i][1],
                     0.001 // Step size
                 );
-            }
-
+              }
             // Update the starting point for the next segment
             startTheta = buffer[i][0];
             startRho = buffer[i][1];
@@ -184,7 +205,10 @@ void movePolar(float theta, float rho)
 
     // Calculate offset for inOut axis
     float revolutions = theta / (2.0 * M_PI); // Fractional revolutions (can be positive or negative)
-    long offsetSteps = revolutions * 1600;    // 1600 steps inward or outward per revolution
+    long offsetSteps = revolutions * rot_total_steps / gearRatio;    // 1600 steps inward or outward per revolution
+
+    // Update the total revolutions to keep track of the offset history
+    totalRevolutions += (theta - currentTheta) / (2.0 * M_PI);
 
     // Apply the offset to the inout axis
     inOutSteps += offsetSteps;