esp32_TMC2209.ino 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #include <AccelStepper.h>
  2. #include <MultiStepper.h>
  3. #include <math.h> // For M_PI and mathematical operations
  4. #define rotInterfaceType AccelStepper::DRIVER
  5. #define inOutInterfaceType AccelStepper::DRIVER
  6. #define stepPin_rot 22
  7. #define dirPin_rot 23
  8. #define stepPin_InOut 18
  9. #define dirPin_InOut 19
  10. #define rot_total_steps 16000.0
  11. #define inOut_total_steps 5760.0
  12. #define gearRatio 10
  13. #define BUFFER_SIZE 10 // Maximum number of theta-rho pairs in a batch
  14. // Create stepper motor objects
  15. AccelStepper rotStepper(rotInterfaceType, stepPin_rot, dirPin_rot);
  16. AccelStepper inOutStepper(inOutInterfaceType, stepPin_InOut, dirPin_InOut);
  17. // Create a MultiStepper object
  18. MultiStepper multiStepper;
  19. // Buffer for storing theta-rho pairs
  20. float buffer[BUFFER_SIZE][2]; // Store theta, rho pairs
  21. int bufferCount = 0; // Number of pairs in the buffer
  22. bool batchComplete = false;
  23. // Track the current position in polar coordinates
  24. float currentTheta = 0.0; // Current theta in radians
  25. float currentRho = 0.0; // Current rho (0 to 1)
  26. bool isFirstCoordinates = true;
  27. float totalRevolutions = 0.0; // Tracks cumulative revolutions
  28. long maxSpeed = 1000;
  29. float maxAcceleration = 1000;
  30. long interpolationResolution = 1;
  31. float userDefinedSpeed = maxSpeed; // Store user-defined speed
  32. void setup()
  33. {
  34. // Set maximum speed and acceleration
  35. rotStepper.setMaxSpeed(maxSpeed); // Adjust as needed
  36. rotStepper.setAcceleration(maxAcceleration); // Adjust as needed
  37. inOutStepper.setMaxSpeed(maxSpeed); // Adjust as needed
  38. inOutStepper.setAcceleration(maxAcceleration); // Adjust as needed
  39. // Add steppers to MultiStepper
  40. multiStepper.addStepper(rotStepper);
  41. multiStepper.addStepper(inOutStepper);
  42. // Initialize serial communication
  43. Serial.begin(115200);
  44. Serial.println("R");
  45. homing();
  46. }
  47. void getVersion() {
  48. Serial.println("Table: Dune Weaver");
  49. Serial.println("Drivers: ESP32-TMC2209");
  50. Serial.println("Version: 1.4.0");
  51. }
  52. void resetTheta()
  53. {
  54. isFirstCoordinates = true; // Set flag to skip interpolation for the next movement
  55. Serial.println("THETA_RESET"); // Notify Python
  56. }
  57. void loop() {
  58. appMode();
  59. }
  60. void appMode()
  61. {
  62. // Check for incoming serial commands or theta-rho pairs
  63. if (Serial.available() > 0)
  64. {
  65. String input = Serial.readStringUntil('\n');
  66. // Ignore invalid messages
  67. if (input != "HOME" && input != "RESET_THETA" && input != "GET_VERSION" && !input.startsWith("SET_SPEED") && !input.endsWith(";"))
  68. {
  69. Serial.print("IGNORED: ");
  70. Serial.println(input);
  71. return;
  72. }
  73. if (input == "GET_VERSION")
  74. {
  75. getVersion();
  76. }
  77. if (input == "RESET_THETA")
  78. {
  79. resetTheta(); // Reset currentTheta
  80. Serial.println("THETA_RESET"); // Notify Python
  81. Serial.println("READY");
  82. return;
  83. }
  84. if (input == "HOME")
  85. {
  86. homing();
  87. return;
  88. }
  89. if (input.startsWith("SET_SPEED"))
  90. {
  91. // Parse out the speed value from the command string
  92. int spaceIndex = input.indexOf(' ');
  93. if (spaceIndex != -1)
  94. {
  95. String speedStr = input.substring(spaceIndex + 1);
  96. float speedPercentage = speedStr.toFloat();
  97. // Make sure the percentage is valid
  98. if (speedPercentage >= 1.0 && speedPercentage <= 100.0)
  99. {
  100. // Convert percentage to actual speed
  101. long newSpeed = (speedPercentage / 100.0) * maxSpeed;
  102. userDefinedSpeed = newSpeed;
  103. // Set the stepper speeds
  104. rotStepper.setMaxSpeed(newSpeed);
  105. inOutStepper.setMaxSpeed(newSpeed);
  106. Serial.println("SPEED_SET");
  107. }
  108. else
  109. {
  110. Serial.println("INVALID_SPEED");
  111. }
  112. }
  113. else
  114. {
  115. Serial.println("INVALID_COMMAND");
  116. }
  117. return;
  118. }
  119. // If not a command, assume it's a batch of theta-rho pairs
  120. if (!batchComplete)
  121. {
  122. int pairIndex = 0;
  123. int startIdx = 0;
  124. // Split the batch line into individual theta-rho pairs
  125. while (pairIndex < BUFFER_SIZE)
  126. {
  127. int endIdx = input.indexOf(";", startIdx);
  128. if (endIdx == -1)
  129. break; // No more pairs in the line
  130. String pair = input.substring(startIdx, endIdx);
  131. int commaIndex = pair.indexOf(',');
  132. // Parse theta and rho values
  133. float theta = pair.substring(0, commaIndex).toFloat(); // Theta in radians
  134. float rho = pair.substring(commaIndex + 1).toFloat(); // Rho (0 to 1)
  135. buffer[pairIndex][0] = theta;
  136. buffer[pairIndex][1] = rho;
  137. pairIndex++;
  138. startIdx = endIdx + 1; // Move to next pair
  139. }
  140. bufferCount = pairIndex;
  141. batchComplete = true;
  142. }
  143. }
  144. // Process the buffer if a batch is ready
  145. if (batchComplete && bufferCount > 0)
  146. {
  147. // Start interpolation from the current position
  148. float startTheta = currentTheta;
  149. float startRho = currentRho;
  150. for (int i = 0; i < bufferCount; i++)
  151. {
  152. if (isFirstCoordinates)
  153. {
  154. // Directly move to the first coordinate of the new pattern
  155. long initialRotSteps = buffer[0][0] * (rot_total_steps / (2.0 * M_PI));
  156. rotStepper.setCurrentPosition(initialRotSteps);
  157. inOutStepper.setCurrentPosition(inOutStepper.currentPosition() + (totalRevolutions * rot_total_steps / gearRatio));
  158. currentTheta = buffer[0][0];
  159. totalRevolutions = 0;
  160. movePolar(buffer[0][0], buffer[0][1]);
  161. isFirstCoordinates = false; // Reset the flag after the first movement
  162. }
  163. else
  164. {
  165. // Use interpolation for subsequent movements
  166. interpolatePath(
  167. startTheta, startRho,
  168. buffer[i][0], buffer[i][1],
  169. interpolationResolution
  170. );
  171. }
  172. // Update the starting point for the next segment
  173. startTheta = buffer[i][0];
  174. startRho = buffer[i][1];
  175. }
  176. batchComplete = false; // Reset batch flag
  177. bufferCount = 0; // Clear buffer
  178. Serial.println("R");
  179. }
  180. }
  181. void homing()
  182. {
  183. Serial.println("HOMING");
  184. // Move inOutStepper inward for homing
  185. inOutStepper.setSpeed(-maxSpeed); // Adjust speed for homing
  186. while (true)
  187. {
  188. inOutStepper.runSpeed();
  189. if (inOutStepper.currentPosition() <= -inOut_total_steps * 1.1)
  190. { // Adjust distance for homing
  191. break;
  192. }
  193. }
  194. inOutStepper.setCurrentPosition(0); // Set home position
  195. currentTheta = 0.0; // Reset polar coordinates
  196. currentRho = 0.0;
  197. Serial.println("HOMED");
  198. }
  199. void movePolar(float theta, float rho)
  200. {
  201. // Convert polar coordinates to motor steps
  202. long rotSteps = theta * (rot_total_steps / (2.0 * M_PI)); // Steps for rot axis
  203. long inOutSteps = rho * inOut_total_steps; // Steps for in-out axis
  204. // Calculate offset for inOut axis
  205. float revolutions = theta / (2.0 * M_PI); // Fractional revolutions (can be positive or negative)
  206. long offsetSteps = revolutions * rot_total_steps / gearRatio; // 1600 steps inward or outward per revolution
  207. // Update the total revolutions to keep track of the offset history
  208. totalRevolutions += (theta - currentTheta) / (2.0 * M_PI);
  209. // Apply the offset to the inout axis
  210. if (!isFirstCoordinates) {
  211. inOutSteps -= offsetSteps;
  212. }
  213. // Define target positions for both motors
  214. long targetPositions[2];
  215. targetPositions[0] = rotSteps;
  216. targetPositions[1] = inOutSteps;
  217. // Move both motors synchronously
  218. multiStepper.moveTo(targetPositions);
  219. multiStepper.runSpeedToPosition(); // Blocking call
  220. // Update the current coordinates
  221. currentTheta = theta;
  222. currentRho = rho;
  223. }
  224. void interpolatePath(float startTheta, float startRho, float endTheta, float endRho, float stepSize)
  225. {
  226. // Calculate the total distance in the polar coordinate system
  227. float distance = sqrt(pow(endTheta - startTheta, 2) + pow(endRho - startRho, 2));
  228. int numSteps = max(1, (int)(distance / stepSize)); // Ensure at least one step
  229. for (int step = 0; step <= numSteps; step++)
  230. {
  231. float t = (float)step / numSteps; // Interpolation factor (0 to 1)
  232. float interpolatedTheta = startTheta + t * (endTheta - startTheta);
  233. float interpolatedRho = startRho + t * (endRho - startRho);
  234. // Move to the interpolated theta-rho
  235. movePolar(interpolatedTheta, interpolatedRho);
  236. }
  237. }