arduino_code.ino 7.7 KB

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