1
0

Stepper_Rotation.ino 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <AccelStepper.h>
  2. // Define the pinss
  3. #define STEP_PIN1 5
  4. #define DIR_PIN1 4
  5. #define ENABLE_PIN1 6
  6. // Define the steps per revolution of your stepper motor
  7. const float STEPS_PER_REVOLUTION = 200.0;
  8. float i = 20; //Gear Transmission
  9. // Create an instance of the AccelStepper class
  10. AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN1, DIR_PIN1);
  11. void setup() {
  12. Serial.begin(9600); // Set the baud rate to the same value used in Python
  13. // Set the maximum speed and acceleration (you can adjust these values)
  14. stepper.setMaxSpeed(400);
  15. stepper.setAcceleration(100.0);
  16. // Set the enable pin as an output and disable the motor by default
  17. pinMode(ENABLE_PIN1, OUTPUT);
  18. digitalWrite(ENABLE_PIN1, HIGH);
  19. // Set the motor direction (0 for clockwise, 1 for counter-clockwise)
  20. stepper.setPinsInverted(false, false, true); // Adjust the last parameter if needed
  21. }
  22. void loop() {
  23. if (Serial.available() > 0) {
  24. // Read the incoming value from Python
  25. int value = Serial.parseInt();
  26. if ((value > -125) && (value < 125)) {
  27. rotateStepper(value * i);
  28. Serial.println(value);
  29. }
  30. }
  31. delay(1000);
  32. }
  33. void rotateStepper(float degrees) {
  34. // Calculate the number of steps based on the desired angle
  35. float steps = degrees * (STEPS_PER_REVOLUTION / 360.0);
  36. // Move the stepper to the specified number of steps
  37. stepper.move(steps);
  38. // Enable the motor
  39. digitalWrite(ENABLE_PIN1, LOW);
  40. // Run the stepper until it reaches the target position
  41. while (stepper.distanceToGo() != 0) {
  42. stepper.run();
  43. }
  44. // Disable the motor
  45. digitalWrite(ENABLE_PIN1, HIGH);
  46. }