arduino_code.ino 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. #define buttonPin 11 // Z- signal pin on the CNC shield
  15. #define pot1 A1 // Potentiometer 1, Abort pin on the CNC shield
  16. #define pot2 A0 // Potentiometer 2, Hold pint on the CNC shield
  17. #define MODE_APP 0
  18. #define MODE_SPIROGRAPH 1
  19. // Create stepper motor objects
  20. AccelStepper rotStepper(rotInterfaceType, stepPin_rot, dirPin_rot);
  21. AccelStepper inOutStepper(inOutInterfaceType, stepPin_InOut, dirPin_InOut);
  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 = 5000;
  34. float maxAcceleration = 5000;
  35. long interpolationResolution = 0.001;
  36. float userDefinedSpeed = maxSpeed; // Store user-defined speed
  37. // Running Mode
  38. int currentMode = MODE_APP; // Default mode is app mode.
  39. // FIRMWARE VERSION
  40. const char* firmwareVersion = "1.4.0";
  41. const char* motorType = "DRV8825";
  42. void setup()
  43. {
  44. // Set maximum speed and acceleration
  45. rotStepper.setMaxSpeed(maxSpeed); // Adjust as needed
  46. rotStepper.setAcceleration(maxAcceleration); // Adjust as needed
  47. inOutStepper.setMaxSpeed(maxSpeed); // Adjust as needed
  48. inOutStepper.setAcceleration(maxAcceleration); // Adjust as needed
  49. // Add steppers to MultiStepper
  50. multiStepper.addStepper(rotStepper);
  51. multiStepper.addStepper(inOutStepper);
  52. // Configure the buttons and potentiometers for Spirograph mode
  53. pinMode(buttonPin, INPUT_PULLUP); // Configure button pin with internal pull-up
  54. pinMode(A0, INPUT); // Potentiometer 1 input
  55. pinMode(A1, INPUT); // Potentiometer 2 input
  56. // Initialize serial communication
  57. Serial.begin(115200);
  58. Serial.println("R");
  59. homing();
  60. }
  61. void getVersion()
  62. {
  63. Serial.println("Table: Dune Weaver");
  64. Serial.println("Drivers: DRV8825");
  65. Serial.println("Version: 1.4.0");
  66. }
  67. void resetTheta()
  68. {
  69. isFirstCoordinates = true; // Set flag to skip interpolation for the next movement
  70. Serial.println("THETA_RESET"); // Notify Python
  71. }
  72. void loop() {
  73. updateModeSwitch(); // Check and handle mode switching
  74. // Call the appropriate mode function based on the current mode
  75. if (currentMode == MODE_SPIROGRAPH) {
  76. spirographMode();
  77. } else if (currentMode == MODE_APP) {
  78. appMode();
  79. }
  80. }
  81. void updateModeSwitch() {
  82. // Read the current state of the latching switch
  83. bool currentSwitchState = digitalRead(buttonPin);
  84. int newMode = currentSwitchState == LOW ? MODE_SPIROGRAPH : MODE_APP;
  85. if (newMode != currentMode) {
  86. handleModeChange(newMode); // Handle mode-specific transitions
  87. currentMode = newMode; // Update the current mode
  88. }
  89. }
  90. void handleModeChange(int newMode) {
  91. // Print mode switch information
  92. if (newMode == MODE_SPIROGRAPH) {
  93. Serial.println("Spirograph Mode Active");
  94. rotStepper.setMaxSpeed(userDefinedSpeed * 0.5); // Use 50% of user-defined speed
  95. inOutStepper.setMaxSpeed(userDefinedSpeed * 0.5);
  96. isFirstCoordinates = false;
  97. } else if (newMode == MODE_APP) {
  98. Serial.println("App Mode Active");
  99. rotStepper.setMaxSpeed(userDefinedSpeed); // Restore user-defined speed
  100. inOutStepper.setMaxSpeed(userDefinedSpeed);
  101. resetTheta();
  102. }
  103. movePolar(currentTheta, 0); // Move to the center
  104. }
  105. void spirographMode() {
  106. static float currentFrequency = 2.95; // Track the current frequency (default value)
  107. static float phaseShift = 0.0; // Track the phase shift for smooth transitions
  108. // Read potentiometer for frequency adjustment
  109. int pot1Value = analogRead(pot1);
  110. float newFrequency = mapFloat(pot1Value, 0, 1023, 0.5, 6); // Map to range
  111. newFrequency = round(newFrequency * 10) / 10.0; // Round to one decimal place
  112. // Force the value to x.95 or x.10 to have a slight variation each revolution
  113. if (fmod(newFrequency, 1.0) >= 0.5) {
  114. newFrequency = floor(newFrequency) + 0.95; // Round up to x.95
  115. } else {
  116. newFrequency = floor(newFrequency) + 0.10; // Round down to x.10
  117. }
  118. // Adjust phase shift if frequency changes
  119. if (newFrequency != currentFrequency) {
  120. phaseShift += currentTheta * (currentFrequency - newFrequency);
  121. currentFrequency = newFrequency; // Update the current frequency
  122. }
  123. // Read variation knob to adjust the minimum rho
  124. int pot2Value = analogRead(pot2);
  125. float minRho = round(mapFloat(pot2Value, 0, 1023, 0, 0.5) * 20) / 20.0; // Minimum rho in steps of 0.05
  126. // Calculate amplitude and offset for the sine wave
  127. float amplitude = (1.0 - minRho) / 2.0; // Half of the oscillation range
  128. float offset = minRho + amplitude; // Center the wave within the range [minRho, 1]
  129. // Calculate the next target theta
  130. float stepSize = maxSpeed * (2 * M_PI / rot_total_steps) / 10; // Smaller steps for finer control
  131. float nextTheta = currentTheta + stepSize;
  132. // Count total revolutions
  133. totalRevolutions = (nextTheta / (2 * M_PI));
  134. // Calculate rho using the adjusted sine wave with phase shift
  135. currentRho = offset + amplitude * cos((currentTheta * currentFrequency) + phaseShift);
  136. float nextRho = offset + amplitude * cos((nextTheta * currentFrequency) + phaseShift);
  137. // Move the steppers to the calculated position
  138. movePolar(nextTheta, constrain(nextRho, 0, 1));
  139. // Update the current theta to the new position
  140. currentTheta = nextTheta;
  141. }
  142. float mapFloat(long x, long inMin, long inMax, float outMin, float outMax) {
  143. if (inMax == inMin) {
  144. Serial.println("Error: mapFloat division by zero");
  145. return outMin; // Return the minimum output value as a fallback
  146. }
  147. return (float)(x - inMin) * (outMax - outMin) / (float)(inMax - inMin) + outMin;
  148. }
  149. void appMode()
  150. {
  151. // Check for incoming serial commands or theta-rho pairs
  152. if (Serial.available() > 0)
  153. {
  154. String input = Serial.readStringUntil('\n');
  155. // Ignore invalid messages
  156. if (input != "HOME" && input != "RESET_THETA" && input != "GET_VERSION" && !input.startsWith("SET_SPEED") && !input.endsWith(";"))
  157. {
  158. Serial.print("IGNORED: ");
  159. Serial.println(input);
  160. return;
  161. }
  162. if (input == "GET_VERSION")
  163. {
  164. getVersion();
  165. }
  166. if (input == "RESET_THETA")
  167. {
  168. resetTheta(); // Reset currentTheta
  169. Serial.println("THETA_RESET"); // Notify Python
  170. Serial.println("READY");
  171. return;
  172. }
  173. if (input == "HOME")
  174. {
  175. homing();
  176. return;
  177. }
  178. // Example: The user calls "SET_SPEED 60" => 60% of maxSpeed
  179. if (input.startsWith("SET_SPEED"))
  180. {
  181. // Parse out the speed value from the command string
  182. int spaceIndex = input.indexOf(' ');
  183. if (spaceIndex != -1)
  184. {
  185. String speedStr = input.substring(spaceIndex + 1);
  186. float speedPercentage = speedStr.toFloat();
  187. // Make sure the percentage is valid
  188. if (speedPercentage >= 1.0 && speedPercentage <= 100.0)
  189. {
  190. // Convert percentage to actual speed
  191. long newSpeed = (speedPercentage / 100.0) * maxSpeed;
  192. userDefinedSpeed = newSpeed;
  193. // Set the stepper speeds
  194. rotStepper.setMaxSpeed(newSpeed);
  195. inOutStepper.setMaxSpeed(newSpeed);
  196. Serial.println("SPEED_SET");
  197. }
  198. else
  199. {
  200. Serial.println("INVALID_SPEED");
  201. }
  202. }
  203. else
  204. {
  205. Serial.println("INVALID_COMMAND");
  206. }
  207. return;
  208. }
  209. // If not a command, assume it's a batch of theta-rho pairs
  210. if (!batchComplete)
  211. {
  212. int pairIndex = 0;
  213. int startIdx = 0;
  214. // Split the batch line into individual theta-rho pairs
  215. while (pairIndex < BUFFER_SIZE)
  216. {
  217. int endIdx = input.indexOf(";", startIdx);
  218. if (endIdx == -1)
  219. break; // No more pairs in the line
  220. String pair = input.substring(startIdx, endIdx);
  221. int commaIndex = pair.indexOf(',');
  222. // Parse theta and rho values
  223. float theta = pair.substring(0, commaIndex).toFloat(); // Theta in radians
  224. float rho = pair.substring(commaIndex + 1).toFloat(); // Rho (0 to 1)
  225. buffer[pairIndex][0] = theta;
  226. buffer[pairIndex][1] = rho;
  227. pairIndex++;
  228. startIdx = endIdx + 1; // Move to next pair
  229. }
  230. bufferCount = pairIndex;
  231. batchComplete = true;
  232. }
  233. }
  234. // Process the buffer if a batch is ready
  235. if (batchComplete && bufferCount > 0)
  236. {
  237. // Start interpolation from the current position
  238. float startTheta = currentTheta;
  239. float startRho = currentRho;
  240. for (int i = 0; i < bufferCount; i++)
  241. {
  242. if (isFirstCoordinates)
  243. {
  244. // Directly move to the first coordinate of the new pattern
  245. long initialRotSteps = buffer[0][0] * (rot_total_steps / (2.0 * M_PI));
  246. rotStepper.setCurrentPosition(initialRotSteps);
  247. inOutStepper.setCurrentPosition(inOutStepper.currentPosition() - totalRevolutions * rot_total_steps / gearRatio);
  248. currentTheta = buffer[0][0];
  249. totalRevolutions = 0;
  250. isFirstCoordinates = false; // Reset the flag after the first movement
  251. movePolar(buffer[0][0], buffer[0][1]);
  252. }
  253. else
  254. {
  255. // Use interpolation for subsequent movements
  256. interpolatePath(
  257. startTheta, startRho,
  258. buffer[i][0], buffer[i][1],
  259. interpolationResolution
  260. );
  261. }
  262. // Update the starting point for the next segment
  263. startTheta = buffer[i][0];
  264. startRho = buffer[i][1];
  265. }
  266. batchComplete = false; // Reset batch flag
  267. bufferCount = 0; // Clear buffer
  268. Serial.println("R");
  269. }
  270. }
  271. void homing()
  272. {
  273. Serial.println("HOMING");
  274. // Move inOutStepper inward for homing
  275. inOutStepper.setSpeed(-maxSpeed); // Adjust speed for homing
  276. while (true)
  277. {
  278. inOutStepper.runSpeed();
  279. if (inOutStepper.currentPosition() <= -inOut_total_steps * 1.1)
  280. { // Adjust distance for homing
  281. break;
  282. }
  283. }
  284. inOutStepper.setCurrentPosition(0); // Set home position
  285. currentTheta = 0.0; // Reset polar coordinates
  286. currentRho = 0.0;
  287. Serial.println("HOMED");
  288. }
  289. void movePolar(float theta, float rho)
  290. {
  291. // Define different scaling factors for rho <= 0.5 and rho > 0.5
  292. float speedScalingFactorLow = 0.7; // Scaling factor for rho <= 0.5
  293. float speedScalingFactorHigh = 0.4; // Scaling factor for rho > 0.5
  294. float speedScalingFactor;
  295. // Determine which factor to use
  296. if (rho <= 0.5) {
  297. speedScalingFactor = speedScalingFactorLow;
  298. } else {
  299. speedScalingFactor = speedScalingFactorHigh;
  300. }
  301. // Scale speed dynamically based on rho
  302. long dynamicSpeed = maxSpeed * (1.0 + speedScalingFactor * (1.0 - 2.0 * rho));
  303. // Ensure the speed is within a valid range
  304. dynamicSpeed = constrain(dynamicSpeed, 1, maxSpeed);
  305. // Set stepper speeds dynamically
  306. rotStepper.setMaxSpeed(dynamicSpeed);
  307. inOutStepper.setMaxSpeed(dynamicSpeed);
  308. // Convert polar coordinates to motor steps
  309. long rotSteps = theta * (rot_total_steps / (2.0 * M_PI)); // Steps for rot axis
  310. long inOutSteps = rho * inOut_total_steps; // Steps for in-out axis
  311. // Calculate offset for inOut axis
  312. float revolutions = theta / (2.0 * M_PI); // Fractional revolutions (can be positive or negative)
  313. long offsetSteps = revolutions * rot_total_steps / gearRatio; // 1600 steps inward or outward per revolution
  314. // Update the total revolutions to keep track of the offset history
  315. totalRevolutions += (theta - currentTheta) / (2.0 * M_PI);
  316. // Apply the offset to the inout axis
  317. if (!isFirstCoordinates) {
  318. inOutSteps -= offsetSteps;
  319. }
  320. // Define target positions for both motors
  321. long targetPositions[2];
  322. targetPositions[0] = rotSteps;
  323. targetPositions[1] = inOutSteps;
  324. // Move both motors synchronously
  325. multiStepper.moveTo(targetPositions);
  326. multiStepper.runSpeedToPosition(); // Blocking call
  327. // Update the current coordinates
  328. currentTheta = theta;
  329. currentRho = rho;
  330. }
  331. void interpolatePath(float startTheta, float startRho, float endTheta, float endRho, float stepSize)
  332. {
  333. // Calculate the total distance in the polar coordinate system
  334. float distance = sqrt(pow(endTheta - startTheta, 2) + pow(endRho - startRho, 2));
  335. int numSteps = max(1, (int)(distance / stepSize)); // Ensure at least one step
  336. for (int step = 0; step <= numSteps; step++)
  337. {
  338. float t = (float)step / numSteps; // Interpolation factor (0 to 1)
  339. float interpolatedTheta = startTheta + t * (endTheta - startTheta);
  340. float interpolatedRho = startRho + t * (endRho - startRho);
  341. // Move to the interpolated theta-rho
  342. movePolar(interpolatedTheta, interpolatedRho);
  343. }
  344. }