Tuan Nguyen 1 anno fa
parent
commit
d2190a5dcc
3 ha cambiato i file con 89 aggiunte e 10 eliminazioni
  1. 27 2
      app.py
  2. 32 8
      arduino_code_TMC2209/arduino_code_TMC2209.ino
  3. 30 0
      templates/index.html

+ 27 - 2
app.py

@@ -129,13 +129,13 @@ def send_command(command):
     ser.write(f"{command}\n".encode())
     print(f"Sent: {command}")
 
-    # Wait for "DONE" acknowledgment from Arduino
+    # Wait for "R" acknowledgment from Arduino
     while True:
         with serial_lock:
             if ser.in_waiting > 0:
                 response = ser.readline().decode().strip()
                 print(f"Arduino response: {response}")
-                if response == "DONE":
+                if response == "R":
                     print("Command execution completed.")
                     break
 
@@ -705,6 +705,31 @@ def run_playlist():
         return jsonify({"success": True, "message": f"Playlist '{playlist_name}' is now running."})
     except Exception as e:
         return jsonify({"success": False, "error": str(e)}), 500
+    
+@app.route('/set_speed', methods=['POST'])
+def set_speed():
+    """Set the speed for the Arduino."""
+    global ser
+    if ser is None or not ser.is_open:
+        return jsonify({"success": False, "error": "Serial connection not established"}), 400
+
+    try:
+        # Parse the speed value from the request
+        data = request.json
+        speed = data.get('speed')
+
+        if speed is None:
+            return jsonify({"success": False, "error": "Speed is required"}), 400
+
+        if not isinstance(speed, (int, float)) or speed <= 0:
+            return jsonify({"success": False, "error": "Invalid speed value"}), 400
+
+        # Send the SET_SPEED command to the Arduino
+        command = f"SET_SPEED {speed}"
+        send_command(command)
+        return jsonify({"success": True, "speed": speed})
+    except Exception as e:
+        return jsonify({"success": False, "error": str(e)}), 500
 
 if __name__ == '__main__':
     app.run(debug=True, host='0.0.0.0', port=8080)

+ 32 - 8
arduino_code_TMC2209/arduino_code_TMC2209.ino

@@ -181,7 +181,7 @@ void appMode()
         String input = Serial.readStringUntil('\n');
 
         // Ignore invalid messages
-        if (input != "HOME" && input != "RESET_THETA" && !input.endsWith(";"))
+        if (input != "HOME" && input != "RESET_THETA" && !input.startsWith("SET_SPEED") && !input.endsWith(";"))
         {
             Serial.println("IGNORED");
             return;
@@ -231,6 +231,35 @@ void appMode()
             return;
         }
 
+        if (input.startsWith("SET_SPEED"))
+        {
+            // Parse and set the speed
+            int spaceIndex = input.indexOf(' ');
+            if (spaceIndex != -1)
+            {
+                String speedStr = input.substring(spaceIndex + 1);
+                double speed = speedStr.toDouble();
+
+                if (speed > 0) // Ensure valid speed
+                {
+                    rotStepper.setMaxSpeed(speed);
+                    inOutStepper.setMaxSpeed(speed);
+                    Serial.print("SPEED_SET ");
+                    Serial.println(speed);
+                    Serial.println("R");
+                }
+                else
+                {
+                    Serial.println("INVALID_SPEED");
+                }
+            }
+            else
+            {
+                Serial.println("INVALID_COMMAND");
+            }
+            return;
+        }
+
 
         // If not a command, assume it's a batch of theta-rho pairs
         if (!batchComplete)
@@ -349,13 +378,8 @@ void movePolar(float theta, float rho)
 
     // Move both motors synchronously
     multiStepper.moveTo(targetPositions);
-    isRunning = true;
-    
-    while (rotStepper.distanceToGo() != 0 || inOutStepper.distanceToGo() != 0)
-    {
-        multiStepper.run(); // Non-Blocking call
-    }
-    isRunning = false;
+    multiStepper.runSpeedToPosition(); // Blocking call
+
     // Update the current coordinates
     currentTheta = theta;
     currentRho = rho;

+ 30 - 0
templates/index.html

@@ -24,6 +24,11 @@
                     <button onclick="disconnectSerial()">Disconnect</button>
                     <button onclick="restartSerial()">Restart</button>
                 </div>
+                <div class="button-group">
+                    <label for="speed_input">Speed:</label>
+                    <input type="number" id="speed_input" placeholder="1-5000" min="1" step="1" max="5000">
+                    <button class="small-button"  onclick="changeSpeed()">Set Speed</button>
+                </div>
             </div>
             <div class="section"> 
                 <h2>Mode</h2>
@@ -626,6 +631,31 @@
                 });
             });
           });
+
+        async function changeSpeed() {
+            const speedInput = document.getElementById('speed_input');
+            const speed = parseFloat(speedInput.value);
+
+            if (isNaN(speed) || speed <= 0) {
+                logMessage('Invalid speed. Please enter a positive number.');
+                return;
+            }
+
+            logMessage(`Setting speed to: ${speed}...`);
+            const response = await fetch('/set_speed', {
+                method: 'POST',
+                headers: { 'Content-Type': 'application/json' },
+                body: JSON.stringify({ speed })
+            });
+
+            const result = await response.json();
+            if (result.success) {
+                document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
+                logMessage(`Speed set to: ${speed}`);
+            } else {
+                logMessage(`Failed to set speed: ${result.error}`);
+            }
+        }
         // Keep track of the files in the new playlist
         let playlist = [];
         // Currently selected item in the playlist