1
0

arduino_code.ino 8.6 KB

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