CuriousScientist

Stepper motor control with AccelStepper library

Mar 14th, 2020
1,244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 10.07 KB | None | 0 0
  1. //If you found this code useful, please subscribe to my channel: https://www.youtube.com/c/CuriousScientist?sub_confirmation=1
  2. //It took several hours for me to prepare everything, but subscription is just a click for you. Thank you!
  3. //This code belongs to the following tutorial video: https://youtu.be/CC4nBDcz6Xs
  4.  
  5. //Transforming the motor's rotary motion into linear motion by using a threaded rod:
  6. //Threaded rod's pitch = 2 mm. This means that one revolution will move the nut 2 mm.
  7. //Default stepping = 400 step/revolution.
  8. // 400 step = 1 revolution = 8 mm linear motion. (4 start 2 mm pitch screw)
  9. // 1 cm = 10 mm =>> 10/8 * 400 = 4000/8 = 500 steps are needed to move the nut by 1 cm.
  10.  
  11.  
  12. //character for commands
  13. /*
  14.      'C' : Prints all the commands and their functions.
  15.      'P' : Rotates the motor in positive (CW) direction, relative.
  16.      'N' : Rotates the motor in negative (CCW) direction, relative.
  17.      'R' : Rotates the motor to an absolute positive position (+).
  18.      'r' : Rotates the motor to an absolute negative position (-).
  19.      'S' : Stops the motor immediately.
  20.      'A' : Sets an acceleration value.
  21.      'L' : Prints the current position/location of the motor.
  22.      'H' : Goes back to 0 position from the current position (homing).
  23.      'U' : Updates the position current position and makes it as the new 0 position.
  24.  */
  25.  
  26. #include <AccelStepper.h>
  27.  
  28. //User-defined values
  29. long receivedSteps = 0; //Number of steps
  30. long receivedSpeed = 0; //Steps / second
  31. long receivedAcceleration = 0; //Steps / second^2
  32. char receivedCommand;
  33. //-------------------------------------------------------------------------------
  34. int directionMultiplier = 1; // = 1: positive direction, = -1: negative direction
  35. bool newData, runallowed = false; // booleans for new data from serial, and runallowed flag
  36. AccelStepper stepper(1, 8, 9);// direction Digital 9 (CCW), pulses Digital 8 (CLK)
  37.  
  38. void setup()
  39. {
  40.     Serial.begin(9600); //define baud rate
  41.     Serial.println("Demonstration of AccelStepper Library"); //print a messages
  42.     Serial.println("Send 'C' for printing the commands.");
  43.  
  44.     //setting up some default values for maximum speed and maximum acceleration
  45.     Serial.println("Default speed: 400 steps/s, default acceleration: 800 steps/s^2.");
  46.     stepper.setMaxSpeed(400); //SPEED = Steps / second
  47.     stepper.setAcceleration(800); //ACCELERATION = Steps /(second)^2
  48.  
  49.     stepper.disableOutputs(); //disable outputs
  50. }
  51.  
  52. void loop()
  53. {
  54.     //Constantly looping through these 2 functions.
  55.     //We only use non-blocking commands, so something else (should also be non-blocking) can be done during the movement of the motor
  56.  
  57.     checkSerial(); //check serial port for new commands
  58.     RunTheMotor(); //function to handle the motor  
  59.  
  60. }
  61.  
  62.  
  63. void RunTheMotor() //function for the motor
  64. {
  65.     if (runallowed == true)
  66.     {
  67.         stepper.enableOutputs(); //enable pins
  68.         stepper.run(); //step the motor (this will step the motor by 1 step at each loop)  
  69.     }
  70.     else //program enters this part if the runallowed is FALSE, we do not do anything
  71.     {
  72.         stepper.disableOutputs(); //disable outputs
  73.         return;
  74.     }
  75. }
  76.  
  77.  
  78.  
  79. void checkSerial() //function for receiving the commands
  80. {  
  81.     if (Serial.available() > 0) //if something comes from the computer
  82.     {
  83.         receivedCommand = Serial.read(); // pass the value to the receivedCommad variable
  84.         newData = true; //indicate that there is a new data by setting this bool to true
  85.  
  86.         if (newData == true) //we only enter this long switch-case statement if there is a new command from the computer
  87.         {
  88.             switch (receivedCommand) //we check what is the command
  89.             {
  90.  
  91.             case 'P': //P uses the move() function of the AccelStepper library, which means that it moves relatively to the current position.              
  92.                
  93.                 receivedSteps = Serial.parseFloat(); //value for the steps
  94.                 receivedSpeed = Serial.parseFloat(); //value for the speed
  95.                 directionMultiplier = 1; //We define the direction
  96.                 Serial.println("Positive direction."); //print the action
  97.                 RotateRelative(); //Run the function
  98.  
  99.                 //example: P2000 400 - 2000 steps (5 revolution with 400 step/rev microstepping) and 400 steps/s speed
  100.                 //In theory, this movement should take 5 seconds
  101.                 break;         
  102.  
  103.             case 'N': //N uses the move() function of the AccelStepper library, which means that it moves relatively to the current position.      
  104.                
  105.                 receivedSteps = Serial.parseFloat(); //value for the steps
  106.                 receivedSpeed = Serial.parseFloat(); //value for the speed 
  107.                 directionMultiplier = -1; //We define the direction
  108.                 Serial.println("Negative direction."); //print action
  109.                 RotateRelative(); //Run the function
  110.  
  111.                 //example: N2000 400 - 2000 steps (5 revolution with 400 step/rev microstepping) and 500 steps/s speed; will rotate in the other direction
  112.                 //In theory, this movement should take 5 seconds
  113.                 break;
  114.  
  115.             case 'R': //R uses the moveTo() function of the AccelStepper library, which means that it moves absolutely to the current position.            
  116.  
  117.                 receivedSteps = Serial.parseFloat(); //value for the steps
  118.                 receivedSpeed = Serial.parseFloat(); //value for the speed     
  119.                 directionMultiplier = 1; //We define the direction
  120.                 Serial.println("Absolute position (+)."); //print the action
  121.                 RotateAbsolute(); //Run the function
  122.  
  123.                 //example: R800 400 - It moves to the position which is located at +800 steps away from 0.
  124.                 break;
  125.  
  126.             case 'r': //r uses the moveTo() function of the AccelStepper library, which means that it moves absolutely to the current position.            
  127.  
  128.                 receivedSteps = Serial.parseFloat(); //value for the steps
  129.                 receivedSpeed = Serial.parseFloat(); //value for the speed 
  130.                 directionMultiplier = -1; //We define the direction
  131.                 Serial.println("Absolute position (-)."); //print the action
  132.                 RotateAbsolute(); //Run the function
  133.  
  134.                 //example: r800 400 - It moves to the position which is located at -800 steps away from 0.
  135.                 break;
  136.  
  137.             case 'S': // Stops the motor
  138.                
  139.                 stepper.stop(); //stop motor
  140.                 stepper.disableOutputs(); //disable power
  141.                 Serial.println("Stopped."); //print action
  142.                 runallowed = false; //disable running
  143.                 break;
  144.  
  145.             case 'A': // Updates acceleration
  146.  
  147.                 runallowed = false; //we still keep running disabled, since we just update a variable
  148.                 stepper.disableOutputs(); //disable power
  149.                 receivedAcceleration = Serial.parseFloat(); //receive the acceleration from serial
  150.                 stepper.setAcceleration(receivedAcceleration); //update the value of the variable
  151.                 Serial.print("New acceleration value: "); //confirm update by message
  152.                 Serial.println(receivedAcceleration); //confirm update by message
  153.                 break;
  154.  
  155.             case 'L': //L: Location
  156.  
  157.                 runallowed = false; //we still keep running disabled
  158.                 stepper.disableOutputs(); //disable power
  159.                 Serial.print("Current location of the motor: ");//Print the message
  160.                 Serial.println(stepper.currentPosition()); //Printing the current position in steps.
  161.                 break;
  162.                
  163.             case 'H': //H: Homing
  164.  
  165.                 runallowed = true;     
  166.                 Serial.println("Homing"); //Print the message
  167.                 GoHome();// Run the function
  168.                 break;
  169.  
  170.             case 'U':
  171.  
  172.                 runallowed = false; //we still keep running disabled
  173.                 stepper.disableOutputs(); //disable power
  174.                 stepper.setCurrentPosition(0); //Reset current position. "new home"            
  175.                 Serial.print("The current position is updated to: "); //Print message
  176.                 Serial.println(stepper.currentPosition()); //Check position after reset.
  177.                 break; 
  178.  
  179.             case 'C':
  180.  
  181.                 PrintCommands(); //Print the commands for controlling the motor
  182.                 break;
  183.  
  184.             default:
  185.                
  186.                 runallowed = false; //we still keep running disabled
  187.                 stepper.disableOutputs(); //disable power
  188.                 break;
  189.             }
  190.         }
  191.         //after we went through the above tasks, newData is set to false again, so we are ready to receive new commands again.
  192.         newData = false;       
  193.     }
  194. }
  195.  
  196.  
  197. void GoHome()
  198. {  
  199.     if (stepper.currentPosition() == 0)
  200.     {
  201.         Serial.println("We are at the home position.");
  202.         stepper.disableOutputs(); //disable power
  203.     }
  204.     else
  205.     {
  206.         stepper.setMaxSpeed(400); //set speed manually to 400. In this project 400 is 400 step/sec = 1 rev/sec.
  207.         stepper.moveTo(0); //set abolute distance to move
  208.     }
  209. }
  210.  
  211. void RotateRelative()
  212. {
  213.     //We move X steps from the current position of the stepper motor in a given direction.
  214.     //The direction is determined by the multiplier (+1 or -1)
  215.    
  216.     runallowed = true; //allow running - this allows entering the RunTheMotor() function.
  217.     stepper.setMaxSpeed(receivedSpeed); //set speed
  218.     stepper.move(directionMultiplier * receivedSteps); //set relative distance and direction
  219. }
  220.  
  221.  
  222.  
  223. void RotateAbsolute()
  224. {
  225.     //We move to an absolute position.
  226.     //The AccelStepper library keeps track of the position.
  227.     //The direction is determined by the multiplier (+1 or -1)
  228.     //Why do we need negative numbers? - If you drive a threaded rod and the zero position is in the middle of the rod...
  229.  
  230.     runallowed = true; //allow running - this allows entering the RunTheMotor() function.
  231.     stepper.setMaxSpeed(receivedSpeed); //set speed
  232.     stepper.moveTo(directionMultiplier * receivedSteps); //set relative distance   
  233. }
  234.  
  235. void PrintCommands()
  236. {  
  237.     //Printing the commands
  238.     Serial.println(" 'C' : Prints all the commands and their functions.");
  239.     Serial.println(" 'P' : Rotates the motor in positive (CW) direction, relative.");
  240.     Serial.println(" 'N' : Rotates the motor in negative (CCW) direction, relative.");
  241.     Serial.println(" 'R' : Rotates the motor to an absolute positive position (+).");
  242.     Serial.println(" 'r' : Rotates the motor to an absolute negative position (-).");
  243.     Serial.println(" 'S' : Stops the motor immediately."); 
  244.     Serial.println(" 'A' : Sets an acceleration value.");
  245.     Serial.println(" 'L' : Prints the current position/location of the motor.");
  246.     Serial.println(" 'H' : Goes back to 0 position from the current position (homing).");
  247.     Serial.println(" 'U' : Updates the position current position and makes it as the new 0 position. ");   
  248. }
  249.  
  250. //If you found this code useful, please subsricbe to my channel: https://www.youtube.com/c/CuriousScientist?sub_confirmation=1
  251. //It took several hours for me to prepare everything, but subscription is just a click for you. Thank you!
Add Comment
Please, Sign In to add comment