file.ino 8.8 KB

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