esp32.ino 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #include <AccelStepper.h>
  2. #include <MultiStepper.h>
  3. #include <math.h> // For M_PI and mathematical operations
  4. #include <RingBufCPP.h>
  5. #define rotInterfaceType AccelStepper::DRIVER
  6. #define inOutInterfaceType AccelStepper::DRIVER
  7. #define stepPin_rot 22
  8. #define dirPin_rot 23
  9. #define stepPin_InOut 18
  10. #define dirPin_InOut 19
  11. #define rot_total_steps 16000.0
  12. #define inOut_total_steps 5760.0
  13. #define gearRatio 10
  14. #define BUFFER_SIZE 10 // Maximum number of theta-rho pairs in a batch
  15. // struct to hold a batch of coordinates
  16. struct Batch {
  17. float coords[BUFFER_SIZE][2];
  18. int batchCount;
  19. };
  20. //ring buffer to hold batches
  21. RingBufCPP<struct Batch, 1> buf;
  22. // Create stepper motor objects
  23. AccelStepper rotStepper(rotInterfaceType, stepPin_rot, dirPin_rot);
  24. AccelStepper inOutStepper(inOutInterfaceType, stepPin_InOut, dirPin_InOut);
  25. // Create a MultiStepper object
  26. MultiStepper multiStepper;
  27. // Buffer for storing theta-rho pairs
  28. float buffer[BUFFER_SIZE][2]; // Store theta, rho pairs
  29. bool batchComplete = false;
  30. // Track the current position in polar coordinates
  31. float currentTheta = 0.0; // Current theta in radians
  32. float currentRho = 0.0; // Current rho (0 to 1)
  33. bool isFirstCoordinates = true;
  34. float totalRevolutions = 0.0; // Tracks cumulative revolutions
  35. long maxSpeed = 1000;
  36. float maxAcceleration = 1000;
  37. long interpolationResolution = 1;
  38. float userDefinedSpeed = maxSpeed; // Store user-defined speed
  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 getVersion() {
  55. Serial.println("Table: Dune Weaver");
  56. Serial.println("Drivers: ESP32-TMC2209");
  57. Serial.println("Version: 1.4.0");
  58. }
  59. void resetTheta()
  60. {
  61. isFirstCoordinates = true; // Set flag to skip interpolation for the next movement
  62. Serial.println("THETA_RESET"); // Notify Python
  63. }
  64. void loop() {
  65. appMode();
  66. }
  67. void appMode()
  68. {
  69. // Check for incoming serial commands or theta-rho pairs
  70. if (Serial.available() > 0)
  71. {
  72. String input = Serial.readStringUntil('\n');
  73. // Ignore invalid messages
  74. if (input != "HOME" && input != "RESET_THETA" && input != "GET_VERSION" && !input.startsWith("SET_SPEED") && !input.endsWith(";"))
  75. {
  76. Serial.print("IGNORED: ");
  77. Serial.println(input);
  78. return;
  79. }
  80. if (input == "GET_VERSION")
  81. {
  82. getVersion();
  83. }
  84. if (input == "RESET_THETA")
  85. {
  86. resetTheta(); // Reset currentTheta
  87. Serial.println("THETA_RESET"); // Notify Python
  88. Serial.println("READY");
  89. return;
  90. }
  91. if (input == "HOME")
  92. {
  93. homing();
  94. return;
  95. }
  96. if (input.startsWith("SET_SPEED"))
  97. {
  98. // Parse out the speed value from the command string
  99. int spaceIndex = input.indexOf(' ');
  100. if (spaceIndex != -1)
  101. {
  102. String speedStr = input.substring(spaceIndex + 1);
  103. float speedPercentage = speedStr.toFloat();
  104. // Make sure the percentage is valid
  105. if (speedPercentage >= 1.0 && speedPercentage <= 100.0)
  106. {
  107. // Convert percentage to actual speed
  108. long newSpeed = (speedPercentage / 100.0) * maxSpeed;
  109. userDefinedSpeed = newSpeed;
  110. // Set the stepper speeds
  111. rotStepper.setMaxSpeed(newSpeed);
  112. inOutStepper.setMaxSpeed(newSpeed);
  113. Serial.println("SPEED_SET");
  114. }
  115. else
  116. {
  117. Serial.println("INVALID_SPEED");
  118. }
  119. }
  120. else
  121. {
  122. Serial.println("INVALID_COMMAND");
  123. }
  124. return;
  125. }
  126. // If not a command, assume it's a batch of theta-rho pairs
  127. if (!buf.isFull())
  128. {
  129. int pairIndex = 0;
  130. int startIdx = 0;
  131. // declare the batch struct to be filled
  132. struct Batch bat;
  133. // Split the batch line into individual theta-rho pairs
  134. while (pairIndex < BUFFER_SIZE)
  135. {
  136. int endIdx = input.indexOf(";", startIdx);
  137. if (endIdx == -1)
  138. break; // No more pairs in the line
  139. String pair = input.substring(startIdx, endIdx);
  140. int commaIndex = pair.indexOf(',');
  141. // Parse theta and rho values
  142. float theta = pair.substring(0, commaIndex).toFloat(); // Theta in radians
  143. float rho = pair.substring(commaIndex + 1).toFloat(); // Rho (0 to 1)
  144. bat.coords[pairIndex][0] = theta;
  145. bat.coords[pairIndex][1] = rho;
  146. pairIndex++;
  147. startIdx = endIdx + 1; // Move to next pair
  148. }
  149. //add the batch to
  150. bat.batchCount = pairIndex;
  151. buf.add(bat);
  152. }
  153. }
  154. // Process the buffer if a batch is ready
  155. if (!buf.isEmpty())
  156. {
  157. // Start interpolation from the current position
  158. float startTheta = currentTheta;
  159. float startRho = currentRho;
  160. struct Batch bat;
  161. buf.pull(&bat);
  162. for (int i = 0; i < bat.batchCount; i++)
  163. {
  164. if (isFirstCoordinates)
  165. {
  166. // Directly move to the first coordinate of the new pattern
  167. long initialRotSteps = bat.coords[0][0] * (rot_total_steps / (2.0 * M_PI));
  168. rotStepper.setCurrentPosition(initialRotSteps);
  169. inOutStepper.setCurrentPosition(inOutStepper.currentPosition() + (totalRevolutions * rot_total_steps / gearRatio));
  170. currentTheta = bat.coords[0][0];
  171. totalRevolutions = 0;
  172. movePolar(bat.coords[0][0], bat.coords[0][1]);
  173. isFirstCoordinates = false; // Reset the flag after the first movement
  174. }
  175. else
  176. {
  177. // Use interpolation for subsequent movements
  178. interpolatePath(
  179. startTheta, startRho,
  180. bat.coords[i][0], bat.coords[i][1],
  181. interpolationResolution
  182. );
  183. }
  184. // Update the starting point for the next segment
  185. startTheta = bat.coords[i][0];
  186. startRho = bat.coords[i][1];
  187. }
  188. Serial.println("R");
  189. }
  190. }
  191. void homing()
  192. {
  193. Serial.println("HOMING");
  194. // Move inOutStepper inward for homing
  195. inOutStepper.setSpeed(-maxSpeed); // Adjust speed for homing
  196. while (true)
  197. {
  198. inOutStepper.runSpeed();
  199. if (inOutStepper.currentPosition() <= -inOut_total_steps * 1.1)
  200. { // Adjust distance for homing
  201. break;
  202. }
  203. }
  204. inOutStepper.setCurrentPosition(0); // Set home position
  205. currentTheta = 0.0; // Reset polar coordinates
  206. currentRho = 0.0;
  207. Serial.println("HOMED");
  208. }
  209. void movePolar(float theta, float rho)
  210. {
  211. // Convert polar coordinates to motor steps
  212. long rotSteps = theta * (rot_total_steps / (2.0 * M_PI)); // Steps for rot axis
  213. long inOutSteps = rho * inOut_total_steps; // Steps for in-out axis
  214. // Calculate offset for inOut axis
  215. float revolutions = theta / (2.0 * M_PI); // Fractional revolutions (can be positive or negative)
  216. long offsetSteps = revolutions * rot_total_steps / gearRatio; // 1600 steps inward or outward per revolution
  217. // Update the total revolutions to keep track of the offset history
  218. totalRevolutions += (theta - currentTheta) / (2.0 * M_PI);
  219. // Apply the offset to the inout axis
  220. if (!isFirstCoordinates) {
  221. inOutSteps -= offsetSteps;
  222. }
  223. // Define target positions for both motors
  224. long targetPositions[2];
  225. targetPositions[0] = rotSteps;
  226. targetPositions[1] = inOutSteps;
  227. // Move both motors synchronously
  228. multiStepper.moveTo(targetPositions);
  229. multiStepper.runSpeedToPosition(); // Blocking call
  230. // Update the current coordinates
  231. currentTheta = theta;
  232. currentRho = rho;
  233. }
  234. void interpolatePath(float startTheta, float startRho, float endTheta, float endRho, float stepSize)
  235. {
  236. // Calculate the total distance in the polar coordinate system
  237. float distance = sqrt(pow(endTheta - startTheta, 2) + pow(endRho - startRho, 2));
  238. int numSteps = max(1, (int)(distance / stepSize)); // Ensure at least one step
  239. for (int step = 0; step <= numSteps; step++)
  240. {
  241. float t = (float)step / numSteps; // Interpolation factor (0 to 1)
  242. float interpolatedTheta = startTheta + t * (endTheta - startTheta);
  243. float interpolatedRho = startRho + t * (endRho - startRho);
  244. // Move to the interpolated theta-rho
  245. movePolar(interpolatedTheta, interpolatedRho);
  246. }
  247. }