arduino_code.ino 8.6 KB

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