esp32.ino 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 ROT_PIN1 14
  7. #define ROT_PIN2 12
  8. #define ROT_PIN3 26
  9. #define ROT_PIN4 27
  10. #define INOUT_PIN1 16
  11. #define INOUT_PIN2 17
  12. #define INOUT_PIN3 18
  13. #define INOUT_PIN4 19
  14. #define rot_total_steps 12800
  15. #define inOut_total_steps 4642
  16. // #define inOut_total_steps 4660
  17. const float gearRatio = 100.0f / 16.0f;
  18. #define BUFFER_SIZE 10 // Maximum number of theta-rho pairs in a batch
  19. // Create stepper motor objects
  20. AccelStepper rotStepper(AccelStepper::FULL4WIRE, ROT_PIN1, ROT_PIN3, ROT_PIN2, ROT_PIN4); // Rot axis
  21. AccelStepper inOutStepper(AccelStepper::FULL4WIRE, INOUT_PIN1, INOUT_PIN3, INOUT_PIN2, INOUT_PIN4); // In-out axis
  22. // Create a MultiStepper object
  23. MultiStepper multiStepper;
  24. // Buffer for storing theta-rho pairs
  25. float buffer[BUFFER_SIZE][2]; // Store theta, rho pairs
  26. int bufferCount = 0; // Number of pairs in the buffer
  27. bool batchComplete = false;
  28. // Track the current position in polar coordinates
  29. float currentTheta = 0.0; // Current theta in radians
  30. float currentRho = 0.0; // Current rho (0 to 1)
  31. bool isFirstCoordinates = true;
  32. float totalRevolutions = 0.0; // Tracks cumulative revolutions
  33. float maxSpeed = 550;
  34. float maxAcceleration = 5000;
  35. float interpolationResolution = 0.001;
  36. int modulus(int x, int y) {
  37. return x < 0 ? ((x + 1) % y) + y - 1 : x % y;
  38. }
  39. void setup()
  40. {
  41. // Set maximum speed and acceleration
  42. rotStepper.setMaxSpeed(maxSpeed); // Adjust as needed
  43. rotStepper.setAcceleration(maxAcceleration); // Adjust as needed
  44. inOutStepper.setMaxSpeed(maxSpeed); // Adjust as needed
  45. inOutStepper.setAcceleration(maxAcceleration); // Adjust as needed
  46. // Add steppers to MultiStepper
  47. multiStepper.addStepper(rotStepper);
  48. multiStepper.addStepper(inOutStepper);
  49. // Initialize serial communication
  50. Serial.begin(115200);
  51. Serial.println("R");
  52. homing();
  53. }
  54. void resetTheta()
  55. {
  56. // Reset angle and revolutions
  57. currentTheta = 0.0;
  58. totalRevolutions = 0.0;
  59. // Update the stepper positions to match the current coordinates:
  60. // rotStepper at 0 (corresponding to theta = 0)
  61. rotStepper.setCurrentPosition(0);
  62. // inOutStepper at currentRho * inOut_total_steps (no offset since theta=0)
  63. long inOutPos = (long)(currentRho * inOut_total_steps);
  64. inOutStepper.setCurrentPosition(inOutPos);
  65. // Set the flag to handle the next coordinate as the "first" one
  66. isFirstCoordinates = true;
  67. // Notify Python about the reset
  68. Serial.println("THETA_RESET");
  69. }
  70. void loop()
  71. {
  72. // Check for incoming serial commands or theta-rho pairs
  73. if (Serial.available() > 0)
  74. {
  75. String input = Serial.readStringUntil('\n');
  76. // Ignore invalid messages
  77. if (input != "HOME" && input != "RESET_THETA" && !input.startsWith("SET_SPEED") && !input.endsWith(";"))
  78. {
  79. Serial.println("IGNORED");
  80. return;
  81. }
  82. if (input.startsWith("SET_SPEED"))
  83. {
  84. // Parse and set the speed
  85. int spaceIndex = input.indexOf(' ');
  86. if (spaceIndex != -1)
  87. {
  88. String speedStr = input.substring(spaceIndex + 1);
  89. float speed = speedStr.toFloat();
  90. if (speed > 0) // Ensure valid speed
  91. {
  92. rotStepper.setMaxSpeed(speed);
  93. inOutStepper.setMaxSpeed(speed);
  94. Serial.println("SPEED_SET");
  95. Serial.println("R");
  96. }
  97. else
  98. {
  99. Serial.println("INVALID_SPEED");
  100. }
  101. }
  102. else
  103. {
  104. Serial.println("INVALID_COMMAND");
  105. }
  106. return;
  107. }
  108. if (input == "HOME")
  109. {
  110. homing();
  111. return;
  112. }
  113. if (input == "RESET_THETA")
  114. {
  115. resetTheta(); // Reset currentTheta
  116. Serial.println("THETA_RESET"); // Notify Python
  117. Serial.println("R");
  118. return;
  119. }
  120. // If not a command, assume it's a batch of theta-rho pairs
  121. if (!batchComplete)
  122. {
  123. int pairIndex = 0;
  124. int startIdx = 0;
  125. // Split the batch line into individual theta-rho pairs
  126. while (pairIndex < BUFFER_SIZE)
  127. {
  128. int endIdx = input.indexOf(";", startIdx);
  129. if (endIdx == -1)
  130. break; // No more pairs in the line
  131. String pair = input.substring(startIdx, endIdx);
  132. int commaIndex = pair.indexOf(',');
  133. // Parse theta and rho values
  134. float theta = pair.substring(0, commaIndex).toFloat(); // Theta in radians
  135. float rho = pair.substring(commaIndex + 1).toFloat(); // Rho (0 to 1)
  136. buffer[pairIndex][0] = theta;
  137. buffer[pairIndex][1] = rho;
  138. pairIndex++;
  139. startIdx = endIdx + 1; // Move to next pair
  140. }
  141. bufferCount = pairIndex;
  142. batchComplete = true;
  143. }
  144. }
  145. // Process the buffer if a batch is ready
  146. if (batchComplete && bufferCount > 0)
  147. {
  148. rotStepper.enableOutputs();
  149. inOutStepper.enableOutputs();
  150. // Start interpolation from the current position
  151. float startTheta = currentTheta;
  152. float startRho = currentRho;
  153. for (int i = 0; i < bufferCount; i++)
  154. {
  155. if (isFirstCoordinates)
  156. {
  157. movePolar(buffer[0][0], buffer[0][1]);
  158. isFirstCoordinates = false; // Reset the flag after the first movement
  159. }
  160. else
  161. {
  162. // Use interpolation for subsequent movements
  163. // movePolar(buffer[i][0], buffer[i][1]);
  164. interpolatePath(
  165. startTheta, startRho,
  166. buffer[i][0], buffer[i][1],
  167. interpolationResolution
  168. );
  169. }
  170. // Update the starting point for the next segment
  171. startTheta = buffer[i][0];
  172. startRho = buffer[i][1];
  173. }
  174. rotStepper.disableOutputs();
  175. inOutStepper.disableOutputs();
  176. batchComplete = false; // Reset batch flag
  177. bufferCount = 0; // Clear buffer
  178. Serial.println("R");
  179. }
  180. }
  181. void homing()
  182. {
  183. Serial.println("HOMING");
  184. inOutStepper.enableOutputs();
  185. // Move inOutStepper inward for homing
  186. inOutStepper.setSpeed(-maxSpeed); // Adjust speed for homing
  187. while (true)
  188. {
  189. inOutStepper.runSpeed();
  190. if (inOutStepper.currentPosition() <= -inOut_total_steps * 1.1)
  191. { // Adjust distance for homing
  192. break;
  193. }
  194. }
  195. inOutStepper.setCurrentPosition(0); // Set home position
  196. rotStepper.setCurrentPosition(0);
  197. currentTheta = 0.0; // Reset polar coordinates
  198. currentRho = 0.0;
  199. inOutStepper.disableOutputs();
  200. Serial.println("HOMED");
  201. }
  202. void movePolar(float theta, float rho)
  203. {
  204. if (rho < 0.0)
  205. rho = 0.0;
  206. else if (rho > 1.0)
  207. rho = 1.0;
  208. long rotSteps = (long)(theta * (rot_total_steps / (2.0f * M_PI)));
  209. float revolutions = theta / (2.0 * M_PI);
  210. long offsetSteps = (long)(revolutions * (rot_total_steps / gearRatio));
  211. // Now inOutSteps is always derived from the absolute rho, not incrementally
  212. long inOutSteps = (long)(rho * inOut_total_steps);
  213. inOutSteps -= offsetSteps;
  214. long targetPositions[2] = {rotSteps, inOutSteps};
  215. multiStepper.moveTo(targetPositions);
  216. multiStepper.runSpeedToPosition(); // Blocking call
  217. // Update current coordinates
  218. currentTheta = theta;
  219. currentRho = rho;
  220. }
  221. void interpolatePath(float startTheta, float startRho, float endTheta, float endRho, float stepSize)
  222. {
  223. float distance = sqrt(pow(endTheta - startTheta, 2) + pow(endRho - startRho, 2));
  224. int numSteps = max(1, (int)(distance / stepSize));
  225. // Calculate the shortest angle difference
  226. float angleDiff = endTheta - startTheta;
  227. while (angleDiff > M_PI) angleDiff -= 2.0f * M_PI;
  228. while (angleDiff < -M_PI) angleDiff += 2.0f * M_PI;
  229. for (int step = 0; step <= numSteps; step++)
  230. {
  231. float t = (float)step / numSteps;
  232. float interpolatedTheta = startTheta + t * angleDiff;
  233. float interpolatedRho = startRho + t * (endRho - startRho);
  234. movePolar(interpolatedTheta, interpolatedRho);
  235. }
  236. }