arduino_code_TMC2209.ino 8.3 KB

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