├── library.properties ├── keywords.txt ├── examples ├── 01_Driver │ └── 01_Driver.ino ├── 04_Sync │ └── 04_Sync.ino ├── 00_Basic │ └── 00_Basic.ino ├── 03_OnFinish │ └── 03_OnFinish.ino └── 02_NonDriver │ └── 02_NonDriver.ino ├── README.md ├── LICENSE └── src └── AsyncStepper.hpp /library.properties: -------------------------------------------------------------------------------- 1 | name=AsyncStepperLib 2 | version=2.0.0 3 | author=Luis Llamas 4 | maintainer=Luis Llamas 5 | sentence=AsyncStepper Library 6 | paragraph= 7 | category=Other 8 | url=https://www.luisllamas.es 9 | architectures=* 10 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map AsyncStepper 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | AsyncStepper KEYWORD1 9 | 10 | ####################################### 11 | # Methods and Functions (KEYWORD2) 12 | ####################################### 13 | Rotate KEYWORD2 14 | RotateToAngle KEYWORD2 15 | RotateContinuous KEYWORD2 16 | SetSpeedRpm KEYWORD2 17 | SetSpeedDegreesBySecond KEYWORD2 18 | SetSpeedRadiansBySecong KEYWORD2 19 | SetMetersBySecond KEYWORD2 20 | Stop KEYWORD2 21 | GetCurrentAngle KEYWORD2 22 | Update KEYWORD2 23 | ActionCW KEYWORD2 24 | ActionCCW KEYWORD2 25 | PinCW KEYWORD2 26 | PinCCW KEYWORD2 27 | 28 | ####################################### 29 | # Constants (LITERAL1) 30 | ####################################### 31 | -------------------------------------------------------------------------------- /examples/01_Driver/01_Driver.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Copyright (c) 2021 Luis Llamas 3 | (www.luisllamas.es) 4 | 5 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 9 | 10 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see 14 | 15 | const int stepper_dir_pin = 8; 16 | const int stepper_step_pin = 9; 17 | 18 | const int stepper_steps = 200; 19 | 20 | AsyncStepper stepper1(stepper_steps, stepper_dir_pin, stepper_step_pin); 21 | 22 | void setup() 23 | { 24 | Serial.begin(115200); 25 | 26 | stepper1.SetSpeedRpm(10); 27 | stepper1.RotateContinuous(AsyncStepper::CCW); 28 | } 29 | 30 | void loop() 31 | { 32 | stepper1.Update(); 33 | } 34 | -------------------------------------------------------------------------------- /examples/04_Sync/04_Sync.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Copyright (c) 2021 Luis Llamas 3 | (www.luisllamas.es) 4 | 5 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 9 | 10 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see 14 | 15 | const int stepper_dir_pin = 8; 16 | const int stepper_step_pin = 9; 17 | 18 | const int stepper_steps = 200; 19 | 20 | AsyncStepper stepper1(stepper_steps, stepper_dir_pin, stepper_step_pin); 21 | 22 | void setup() { 23 | stepper1.SetSpeed(200); 24 | stepper1.SetAcceleration(50, 50); 25 | stepper1.RotateAngleInTime(270.0f, 5, AsyncStepper::CW); 26 | } 27 | 28 | void loop() 29 | { 30 | stepper1.Update(); 31 | } -------------------------------------------------------------------------------- /examples/00_Basic/00_Basic.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Copyright (c) 2021 Luis Llamas 3 | (www.luisllamas.es) 4 | 5 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 9 | 10 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see 14 | 15 | const int stepper_steps = 200; 16 | int angle1 = 0; 17 | 18 | AsyncStepper stepper1(stepper_steps, 19 | []() { angle1++; if (angle1 >= 360) angle1 = 0; }, 20 | []() { angle1--; if (angle1 < 0) angle1 = 359; } 21 | ); 22 | 23 | void setup() 24 | { 25 | Serial.begin(115200); 26 | 27 | stepper1.SetSpeedRpm(10); 28 | stepper1.RotateAngle(270.0f, AsyncStepper::CW); 29 | 30 | stepper1.OnFinish = []() 31 | { 32 | Serial.println("Stopped"); 33 | }; 34 | } 35 | 36 | void loop() 37 | { 38 | stepper1.Update(); 39 | } 40 | -------------------------------------------------------------------------------- /examples/03_OnFinish/03_OnFinish.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Copyright (c) 2021 Luis Llamas 3 | (www.luisllamas.es) 4 | 5 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 9 | 10 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see 14 | 15 | const int stepper_dir = 8; 16 | const int stepper_step = 9; 17 | 18 | const int stepper_steps = 200; 19 | 20 | AsyncStepper stepper1(stepper_steps, stepper_dir, stepper_step); 21 | 22 | void rotateCW() 23 | { 24 | stepper1.RotateAngle(90, AsyncStepper::CW, rotateCCW); 25 | } 26 | 27 | void rotateCCW() 28 | { 29 | stepper1.RotateAngle(90, AsyncStepper::CCW, rotateCW); 30 | } 31 | 32 | void setup() 33 | { 34 | Serial.begin(115200); 35 | 36 | pinMode(stepper_dir, OUTPUT); 37 | pinMode(stepper_step, OUTPUT); 38 | 39 | stepper1.SetSpeedRpm(10); 40 | rotateCW(); 41 | } 42 | 43 | void loop() 44 | { 45 | stepper1.Update(); 46 | } 47 | -------------------------------------------------------------------------------- /examples/02_NonDriver/02_NonDriver.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Copyright (c) 2021 Luis Llamas 3 | (www.luisllamas.es) 4 | 5 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 9 | 10 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see 14 | 15 | const int motorPin1 = 8; 16 | const int motorPin2 = 9; 17 | const int motorPin3 = 10; 18 | const int motorPin4 = 11; 19 | 20 | int stepCounter = 0; 21 | const int numSteps = 8; 22 | const int stepsLookup[8] = { B1000, B1100, B0100, B0110, B0010, B0011, B0001, B1001 }; 23 | 24 | // Code to drive the NoDrive stepper 25 | void setOutput(int step) 26 | { 27 | digitalWrite(motorPin1, bitRead(stepsLookup[step], 0)); 28 | digitalWrite(motorPin2, bitRead(stepsLookup[step], 1)); 29 | digitalWrite(motorPin3, bitRead(stepsLookup[step], 2)); 30 | digitalWrite(motorPin4, bitRead(stepsLookup[step], 3)); 31 | } 32 | 33 | void clockwise() 34 | { 35 | stepCounter++; 36 | if (stepCounter >= numSteps) stepCounter = 0; 37 | setOutput(stepCounter); 38 | } 39 | 40 | void anticlockwise() 41 | { 42 | stepCounter--; 43 | if (stepCounter < 0) stepCounter = numSteps - 1; 44 | setOutput(stepCounter); 45 | } 46 | 47 | const int stepper_steps = 4076; 48 | 49 | AsyncStepper stepper1(stepper_steps, 50 | []() { clockwise(); }, 51 | []() { anticlockwise(); } 52 | ); 53 | 54 | void setup() 55 | { 56 | Serial.begin(115200); 57 | 58 | pinMode(motorPin1, OUTPUT); 59 | pinMode(motorPin2, OUTPUT); 60 | pinMode(motorPin3, OUTPUT); 61 | pinMode(motorPin4, OUTPUT); 62 | 63 | stepper1.SetSpeedRpm(10); 64 | stepper1.RotateContinuous(AsyncStepper::CCW); 65 | } 66 | 67 | void loop() 68 | { 69 | stepper1.Update(); 70 | } 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Librería Arduino AsyncStepper v2.1 2 | Librería para Arduino que permite mover un motor paso a paso de forma no bloqueante, con aceleración y deceleración lineal. De esta forma se tiene un motor paso a paso que tiene un cierto comportamiento "asíncrono". 3 | 4 | Más información https://www.luisllamas.es/libreria-arduino-asyncstepper/ 5 | 6 | ## Instrucciones de uso 7 | La clase AsyncStepper implementa un motor paso a paso cuyos movimientos están temporizados, en lugar de ser bloqueantes. El objetivo de la librería es poder mover uno o varios motores paso a paso en un proyecto, incluso a diferentes velocidades, mientras que no se impide la ejecución otras tareas en el bucle de control principal. 8 | 9 | La clase AsyncStepper no realiza el control del motor paso a paso, únicamente realiza la temporaización de los pasos. Esto permite que sea muy versatil, ya que es independiente del motor paso a paso o controlador empleado. 10 | 11 | Para conseguir controlar el motor paso a paso, debemos proporcionar las funciones de CallBack `actionCW` y `actionCCW` que contangan, respectivamente, el código necesario para avanzar un paso en sentido horario y anti horario. 12 | 13 | La clase AsyncStepper está especialmente pensada para funcionar de forma conjunta con controladores como el A4988 o el DRV8825. Este tipo de controladores avanzan un paso al recibir un pulso. 14 | 15 | Para que el uso de estos controladores sea más sencillo, la clase AsyncStepper proporciona un constructor que recibe dos pines. En este caso, las acciones de CallBack por defecto se inicializan a la generación de un pulso digital para actuar sobre el controlador. 16 | 17 | La actualización la posición del motor paso a paso se debe llamar a la función `Update()`, que comprueba el tiempo transcurrido y llama a las acciones de CallBack en caso necesario. Esta función se deberá invocar lo más frecuentemente posible desde el bucle principal. 18 | 19 | 20 | ### Constructor 21 | La clase AsyncStepper se instancia a través de uno de sus constructores 22 | ```c++ 23 | AsyncStepper(uint16_t motorSteps, int pinDir, int pinStep) 24 | AsyncStepper(uint16_t motorSteps, StepperCallback actionCW, StepperCallback actionCCW) 25 | ``` 26 | 27 | ### Uso de AsyncStepper 28 | ```c++ 29 | // Mover un cierto ángulo 30 | void Rotate(float angleDelta, StepDirection direction); 31 | void Rotate(float angleDelta, StepDirection direction, StepCallback callback); 32 | 33 | // Mover hasta un cierto angulo 34 | void RotateToAngle(float angle, StepDirection direction, StepCallback callback); 35 | void RotateToAngle(float angle, StepDirection direction); 36 | 37 | // Mover en un cierto tiempo en segundos 38 | void RotateAngleInTime(float angle, float time, StepperDirection direction, StepperCallback onFinish = nullptr); 39 | void RotateToAngleInTime(float angle, float time, StepperDirection direction, StepperCallback onFinish = nullptr); 40 | 41 | // Mover de forma continua 42 | void RotateContinuous(StepDirection direction); 43 | 44 | // Cambiar velocidad y aceleración 45 | void SetSpeed(long speed); 46 | void SetSpeedRpm(float rpm); 47 | void SetSpeedDegreesBySecond(float degreesBySecond); 48 | void SetAcceleration(long acceleration); 49 | void SetAcceleration(long acceleration, long deceleration); 50 | 51 | // Inicion manual del frenado del motor paso a paso 52 | void Break(); 53 | 54 | // Detener manualmente el motor paso a paso 55 | void Stop(); 56 | 57 | // Actualiza la posicion del motor paso a paso 58 | // Es necesario llamar a este metodo frecuentemente desde el bucle principal 59 | bool Update(); 60 | 61 | //Obtener información 62 | long GetRemainSteps(); 63 | unsigned long GetTimeTraveling(); 64 | float GetCurrentAngle(); 65 | long GetCurrentInterval(); 66 | long GetTravelCurrentStep(); 67 | long GetTravelSteps(); 68 | long GetAbsoluteStep(); 69 | long GetMaxSpeed(); 70 | long GetCurrentSpeed(); 71 | float GetCurrentSpeedRpm(); 72 | float GetCurrentSpeedDegreesBySecond(); 73 | float GetSpeedForMove(long steps, float time); 74 | float GetTimeForMove(long steps); 75 | float GetTimeForMove(long steps, unsigned long speed); 76 | ``` 77 | 78 | ## Referencias 79 | Cálculos para aceleración y deceleración lineal del motor paso a paso basado en el artículo "Linear speed control of stepper motor" de Atmel 80 | [http://ww1.microchip.com/downloads/en/appnotes/doc8017.pdf](http://ww1.microchip.com/downloads/en/appnotes/doc8017.pdf) 81 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/AsyncStepper.hpp: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Copyright (c) 2021 Luis Llamas 3 | (www.luisllamas.es) 4 | 5 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 9 | 10 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see 19 | 20 | typedef void(*StepperCallback)(); 21 | 22 | class AsyncStepper 23 | { 24 | 25 | public: 26 | enum StepperMode 27 | { 28 | Constant, 29 | Linear 30 | }; 31 | 32 | enum StepperDirection 33 | { 34 | CW, 35 | CCW, 36 | }; 37 | 38 | enum StepperState 39 | { 40 | Stopped, 41 | Accelerating, 42 | Running, 43 | Breaking 44 | }; 45 | 46 | 47 | AsyncStepper(uint16_t motorSteps, StepperCallback actionCW, StepperCallback actionCCW) 48 | { 49 | MotorSteps = motorSteps; 50 | 51 | ActionCW = actionCW; 52 | ActionCCW = actionCCW; 53 | OnFinish = nullptr; 54 | } 55 | 56 | AsyncStepper(uint16_t motorSteps, int pinDir, int pinStep) 57 | { 58 | MotorSteps = motorSteps; 59 | 60 | PinDir = pinDir; 61 | PinStep = pinStep; 62 | OnFinish = nullptr; 63 | 64 | pinMode(PinDir, OUTPUT); 65 | pinMode(PinStep, OUTPUT); 66 | } 67 | 68 | 69 | 70 | void Rotate(long steps, StepperDirection direction, StepperCallback onFinish = nullptr) 71 | { 72 | Direction = direction; 73 | OnFinish = onFinish; 74 | 75 | ContinuousMove = false; 76 | TravelSteps = labs(steps); 77 | 78 | InitRotation(MaxSpeed); 79 | } 80 | 81 | void RotateAngle(float angle, StepperDirection direction, StepperCallback onFinish = nullptr) 82 | { 83 | Rotate(angle / 360.0f * 200, direction, onFinish); 84 | } 85 | 86 | void RotateToAngle(float angle, StepperDirection direction, StepperCallback onFinish = nullptr) 87 | { 88 | auto currentAngle = GetCurrentAngle(); 89 | float angleDelta = direction == CW ? currentAngle - angle : angle - currentAngle; 90 | if (angleDelta < 0) angleDelta = -angleDelta; 91 | RotateAngle(angleDelta, direction, OnFinish); 92 | } 93 | 94 | void RotateInTime(long steps, float time, StepperDirection direction, StepperCallback onFinish = nullptr) 95 | { 96 | auto requiredTime = GetTimeForMove(steps); 97 | 98 | auto speed = requiredTime > time ? MaxSpeed : GetSpeedForMove(steps, time); 99 | 100 | Direction = direction; 101 | OnFinish = onFinish; 102 | 103 | ContinuousMove = false; 104 | TravelSteps = labs(steps); 105 | 106 | InitRotation(speed); 107 | } 108 | 109 | void RotateAngleInTime(float angle, float time, StepperDirection direction, StepperCallback onFinish = nullptr) 110 | { 111 | RotateInTime(angle / 360.0f * 200, time, direction, onFinish); 112 | } 113 | 114 | void RotateToAngleInTime(float angle, float time, StepperDirection direction, StepperCallback onFinish = nullptr) 115 | { 116 | auto currentAngle = GetCurrentAngle(); 117 | float angleDelta = direction == CW ? currentAngle - angle : angle - currentAngle; 118 | if (angleDelta < 0) angleDelta = -angleDelta; 119 | RotateAngleInTime(angleDelta, time, direction, OnFinish); 120 | } 121 | 122 | void RotateContinuous(StepperDirection direction) 123 | { 124 | Direction = direction; 125 | OnFinish = nullptr; 126 | 127 | ContinuousMove = true; 128 | TravelSteps = 0; 129 | 130 | InitRotation(MaxSpeed); 131 | } 132 | 133 | void Stop() 134 | { 135 | State = StepperState::Stopped; 136 | } 137 | 138 | void Break() 139 | { 140 | DecSteps = GetRampSteps(GetCurrentSpeed(), Deceleration); 141 | TravelSteps = DecSteps; 142 | ContinuousMove = false; 143 | TravelCurrentStep = 1; 144 | State = StepperState::Breaking; 145 | } 146 | 147 | 148 | uint16_t Update() 149 | { 150 | if (State == StepperState::Stopped) return false; 151 | 152 | uint16_t stepsDone = 0; 153 | while (static_cast(micros() - LastStepTime) >= Interval) 154 | { 155 | LastStepTime += Interval; 156 | Step(); 157 | 158 | if (stepsDone > 0) delayMicroseconds(PulseOffWidth); 159 | stepsDone++; 160 | } 161 | return stepsDone; 162 | } 163 | 164 | void SetSpeed(long speed) 165 | { 166 | MaxSpeed = speed; 167 | } 168 | 169 | void SetSpeedRpm(float rpm) 170 | { 171 | SetSpeed(rpm / 60.0f * MotorSteps); 172 | } 173 | 174 | void SetSpeedDegreesBySecond(float degreesBySecond) 175 | { 176 | SetSpeed(degreesBySecond / 360.0f * MotorSteps); 177 | } 178 | 179 | void SetAcceleration(long acceleration) 180 | { 181 | Acceleration = acceleration; 182 | Deceleration = acceleration; 183 | } 184 | 185 | void SetAcceleration(long acceleration, long deceleration) 186 | { 187 | Acceleration = acceleration; 188 | Deceleration = deceleration; 189 | } 190 | 191 | 192 | 193 | long GetRemainSteps() const 194 | { 195 | return TravelSteps - TravelCurrentStep; 196 | } 197 | 198 | unsigned long GetTimeTraveling() const 199 | { 200 | return micros() - TravelStartTime; 201 | } 202 | 203 | float GetCurrentAngle() const 204 | { 205 | return 360.0f * (AbsoluteStep % MotorSteps) / MotorSteps; 206 | } 207 | 208 | long GetCurrentInterval() const 209 | { 210 | return Interval; 211 | } 212 | 213 | long GetTravelCurrentStep() const 214 | { 215 | return TravelCurrentStep; 216 | } 217 | 218 | long GetTravelSteps() const 219 | { 220 | return TravelSteps; 221 | } 222 | 223 | long GetAbsoluteStep() const 224 | { 225 | return AbsoluteStep; 226 | } 227 | 228 | long GetMaxSpeed() const 229 | { 230 | return MaxSpeed; 231 | } 232 | 233 | long GetCurrentSpeed() const 234 | { 235 | if (State == StepperState::Stopped) return 0; 236 | return 1e+6 / Interval; 237 | } 238 | 239 | float GetCurrentSpeedRpm() const 240 | { 241 | return GetCurrentSpeed() / MotorSteps * 60.0f; 242 | } 243 | 244 | float GetCurrentSpeedDegreesBySecond() const 245 | { 246 | return GetCurrentSpeed() / MotorSteps * 360.0f; 247 | } 248 | 249 | float GetSpeedForMove(long steps, float time) 250 | { 251 | float speed = 0; 252 | 253 | if (Mode == AsyncStepper::Linear) 254 | { 255 | float a_2 = 1.0 / Acceleration + 1.0 / Deceleration; 256 | float discriminant = time * time - 2 * a_2 * steps; 257 | if (discriminant >= 0) 258 | { 259 | speed = (time - (float)sqrt(discriminant)) / a_2; 260 | }; 261 | } 262 | else 263 | { 264 | speed = steps / time; 265 | } 266 | 267 | return speed; 268 | } 269 | 270 | float GetTimeForMove(long steps) 271 | { 272 | return GetTimeForMove(steps, MaxSpeed); 273 | } 274 | 275 | float GetTimeForMove(long steps, unsigned long speed) 276 | { 277 | float time; 278 | if (steps == 0) 279 | { 280 | return 0; 281 | } 282 | else 283 | { 284 | if (Mode == AsyncStepper::Linear) 285 | { 286 | auto accSteps = (float)GetRampSteps(MaxSpeed, Acceleration); 287 | auto decSteps = (float)GetRampSteps(MaxSpeed, Deceleration); 288 | 289 | float ramps = accSteps + decSteps; 290 | float runSteps = 0; 291 | 292 | if (steps < ramps) { 293 | accSteps = steps * Deceleration / (Acceleration + Deceleration); 294 | decSteps = steps - accSteps; 295 | } 296 | else 297 | { 298 | runSteps = steps - ramps; 299 | } 300 | time = (runSteps / speed) + sqrt(2.0 * accSteps / Acceleration) + sqrt(2.0 * decSteps / Deceleration); 301 | } 302 | else 303 | { 304 | time = steps / speed; 305 | } 306 | } 307 | return time; 308 | } 309 | 310 | int PinDir; 311 | int PinStep; 312 | 313 | uint16_t MotorSteps; 314 | 315 | StepperCallback ActionCW = nullptr; 316 | StepperCallback ActionCCW = nullptr; 317 | 318 | StepperCallback OnFinish = nullptr; 319 | 320 | StepperMode Mode = StepperMode::Linear; 321 | StepperState State = StepperState::Stopped; 322 | StepperDirection Direction = StepperDirection::CW; 323 | 324 | private: 325 | unsigned long Speed = 200; 326 | unsigned long Acceleration = 100; 327 | unsigned long Deceleration = 100; 328 | unsigned long MaxSpeed = 200; 329 | 330 | bool ContinuousMove; 331 | 332 | long AbsoluteStep = 0; 333 | 334 | unsigned long TravelSteps; 335 | unsigned long AccSteps; 336 | unsigned long DecSteps; 337 | unsigned long TravelCurrentStep; 338 | 339 | long Interval = 0; 340 | long IntervalRest = 0; 341 | long RunInterval = 0; 342 | 343 | unsigned long TravelStartTime; 344 | unsigned long LastStepTime; 345 | 346 | unsigned long PulseOnWidth = 10; 347 | unsigned long PulseOffWidth = 250; 348 | 349 | void InitRotation(unsigned long speed) 350 | { 351 | State = Mode == StepperMode::Constant ? StepperState::Running : StepperState::Accelerating; 352 | 353 | AccSteps = GetRampSteps(speed, Acceleration); 354 | Interval = 1e+6f * 0.956f * sqrt(1.0f / Acceleration); 355 | RunInterval = 1e+6f / speed; 356 | IntervalRest = 0; 357 | 358 | TravelCurrentStep = 0; 359 | TravelStartTime = micros(); 360 | LastStepTime = TravelStartTime; 361 | } 362 | 363 | void Step() 364 | { 365 | if (Direction == StepperDirection::CW) StepCW(); 366 | else StepCCW(); 367 | 368 | TravelCurrentStep++; 369 | 370 | UpdateState(); 371 | UpdateInterval(); 372 | } 373 | 374 | void UpdateState() 375 | { 376 | if (State == StepperState::Stopped) return; 377 | 378 | const auto remaining = GetRemainSteps(); 379 | if (ContinuousMove == false && remaining <= 0) 380 | { 381 | State = StepperState::Stopped; 382 | if (OnFinish != nullptr) OnFinish(); 383 | } 384 | else 385 | { 386 | if (Mode == StepperMode::Linear) 387 | { 388 | if (State == StepperState::Breaking) return; 389 | 390 | DecSteps = GetRampSteps(GetCurrentSpeed(), Deceleration); 391 | if (ContinuousMove == false && remaining <= DecSteps) 392 | { 393 | State = StepperState::Breaking; 394 | } 395 | else if (TravelCurrentStep <= AccSteps) 396 | { 397 | State = StepperState::Accelerating; 398 | } 399 | else 400 | { 401 | State = StepperState::Running; 402 | } 403 | } 404 | } 405 | } 406 | 407 | void UpdateInterval() 408 | { 409 | if (State == StepperState::Accelerating && TravelCurrentStep > 0) 410 | { 411 | Interval = Interval - (2 * Interval + IntervalRest) / (4 * TravelCurrentStep + 1); 412 | IntervalRest = (TravelCurrentStep < AccSteps) ? (2 * Interval + IntervalRest) % (4 * TravelCurrentStep + 1) : 0; 413 | } 414 | 415 | else if (State == StepperState::Breaking && TravelCurrentStep > 0) 416 | { 417 | const long remain = GetRemainSteps(); 418 | Interval = Interval - (2 * Interval + IntervalRest) / (-4 * remain + 1); 419 | IntervalRest = (2 * Interval + IntervalRest) % (-4 * remain + 1); 420 | } 421 | 422 | else if (State == StepperState::Running) 423 | { 424 | Interval = RunInterval; 425 | } 426 | 427 | if (Interval < RunInterval) 428 | { 429 | Interval = RunInterval; 430 | } 431 | } 432 | 433 | static unsigned long GetRampSteps(unsigned long speed, unsigned long acceleration) 434 | { 435 | return (speed * speed) / (2.0f * acceleration); 436 | } 437 | 438 | void StepCW() 439 | { 440 | if (ActionCW != nullptr) ActionCW(); 441 | else 442 | { 443 | digitalWrite(PinDir, HIGH); 444 | DigitalPulse(PinStep); 445 | } 446 | 447 | AbsoluteStep++; 448 | } 449 | 450 | void StepCCW() 451 | { 452 | if (ActionCCW != nullptr) ActionCCW(); 453 | else 454 | { 455 | digitalWrite(PinDir, LOW); 456 | DigitalPulse(PinStep); 457 | } 458 | 459 | AbsoluteStep--; 460 | } 461 | 462 | void DigitalPulse(int pin) const 463 | { 464 | digitalWrite(pin, HIGH); 465 | delayMicroseconds(PulseOnWidth); 466 | digitalWrite(pin, LOW); 467 | } 468 | }; 469 | #endif 470 | 471 | --------------------------------------------------------------------------------