- Main Page
- Classes
- Files

# AccelStepper.h

    00001 // AccelStepper.h
    00002 //
    00003 /// \mainpage AccelStepper library for Arduino
    00004 ///
    00005 /// This is the Arduino AccelStepper library.
    00006 /// It provides an object-oriented interface for 2 or 4 pin stepper motors.
    00007 ///
    00008 /// The standard Arduino IDE includes the Stepper library
    00009 /// (http://arduino.cc/en/Reference/Stepper) for stepper motors. It is
    00010 /// perfectly adequate for simple, single motor applications.
    00011 ///
    00012 /// AccelStepper significantly improves on the standard Arduino Stepper library in several ways:
    00013 /// \li Supports acceleration and deceleration
    00014 /// \li Supports multiple simultaneous steppers, with independent concurrent stepping on each stepper
    00015 /// \li API functions never delay() or block
    00016 /// \li Supports 2 and 4 wire steppers, plus 4 wire half steppers.
    00017 /// \li Supports alternate stepping functions to enable support of AFMotor (https://github.com/adafruit/Adafruit-Motor-Shield-library)
    00018 /// \li Supports stepper drivers such as the Sparkfun EasyDriver (based on 3967 driver chip)
    00019 /// \li Very slow speeds are supported
    00020 /// \li Extensive API
    00021 /// \li Subclass support
    00022 ///
    00023 /// The latest version of this documentation can be downloaded from
    00024 /// http://www.open.com.au/mikem/arduino/AccelStepper
    00025 ///
    00026 /// Example Arduino programs are included to show the main modes of use.
    00027 ///
    00028 /// The version of the package that this documentation refers to can be downloaded
    00029 /// from http://www.open.com.au/mikem/arduino/AccelStepper/AccelStepper-1.11.zip
    00030 /// You can find the latest version at http://www.open.com.au/mikem/arduino/AccelStepper
    00031 ///
    00032 /// Tested on Arduino Diecimila and Mega with arduino-0018 & arduino-0021
    00033 /// on OpenSuSE 11.1 and avr-libc-1.6.1-1.15,
    00034 /// cross-avr-binutils-2.19-9.1, cross-avr-gcc-4.1.3_20080612-26.5.
    00035 ///
    00036 /// \par Installation
    00037 /// Install in the usual way: unzip the distribution zip file to the libraries
    00038 /// sub-folder of your sketchbook.
    00039 ///
    00040 /// This software is Copyright (C) 2010 Mike McCauley. Use is subject to license
    00041 /// conditions. The main licensing options available are GPL V2 or Commercial:
    00042 ///
    00043 /// \par Open Source Licensing GPL V2
    00044 /// This is the appropriate option if you want to share the source code of your
    00045 /// application with everyone you distribute it to, and you also want to give them
    00046 /// the right to share who uses it. If you wish to use this software under Open
    00047 /// Source Licensing, you must contribute all your source code to the open source
    00048 /// community in accordance with the GPL Version 2 when your application is
    00049 /// distributed. See http://www.gnu.org/copyleft/gpl.html
    00050 ///
    00051 /// \par Commercial Licensing
    00052 /// This is the appropriate option if you are creating proprietary applications
    00053 /// and you are not prepared to distribute and share the source code of your
    00054 /// application. Contact info@open.com.au for details.
    00055 ///
    00056 /// \par Revision History
    00057 /// \version 1.0 Initial release
    00058 ///
    00059 /// \version 1.1 Added speed() function to get the current speed.
    00060 /// \version 1.2 Added runSpeedToPosition() submitted by Gunnar Arndt.
    00061 /// \version 1.3 Added support for stepper drivers (ie with Step and Direction inputs) with _pins == 1
    00062 /// \version 1.4 Added functional contructor to support AFMotor, contributed by Limor, with example sketches.
    00063 /// \version 1.5 Improvements contributed by Peter Mousley: Use of microsecond steps and other speed improvements
    00064 ///              to increase max stepping speed to about 4kHz. New option for user to set the min allowed pulse width.
    00065 ///              Added checks for already running at max speed and skip further calcs if so.
    00066 /// \version 1.6 Fixed a problem with wrapping of microsecond stepping that could cause stepping to hang.
    00067 ///              Reported by Sandy Noble.
    00068 ///              Removed redundant _lastRunTime member.
    00069 /// \version 1.7 Fixed a bug where setCurrentPosition() did always work as expected. Reported by Peter Linhart.
    00070 ///              Reported by Sandy Noble.
    00071 ///              Removed redundant _lastRunTime member.
    00072 /// \version 1.8 Added support for 4 pin half-steppers, requested by Harvey Moon
    00073 /// \version 1.9 setCurrentPosition() now also sets motor speed to 0.
    00074 /// \version 1.10 Builds on Arduino 1.0
    00075 /// \version 1.11 Improvments from Michael Ellison:
    00076 ///   Added optional enable line support for stepper drivers
    00077 ///   Added inversion for step/direction/enable lines for stepper drivers
    00078 ///
    00079 /// \author  Mike McCauley (mikem@open.com.au)
    00080 // Copyright (C) 2009 Mike McCauley
    00081 // $Id: AccelStepper.h,v 1.5 2011/03/21 00:42:15 mikem Exp mikem $
    00082
    00083 #ifndef AccelStepper_h
    00084 #define AccelStepper_h
    00085
    00086 #include <stdlib.h>
    00087 #if ARDUINO >= 100
    00088 #include <Arduino.h>
    00089 #else
    00090 #include <wiring.h>
    00091 #endif
    00092
    00093 // These defs cause trouble on some versions of Arduino
    00094 #undef round
    00095
    00096 /////////////////////////////////////////////////////////////////////
    00097 /// \class AccelStepper AccelStepper.h <AccelStepper.h>
    00098 /// \brief Support for stepper motors with acceleration etc.
    00099 ///
    00100 /// This defines a single 2 or 4 pin stepper motor, or stepper moter with fdriver chip, with optional
    00101 /// acceleration, deceleration, absolute positioning commands etc. Multiple
    00102 /// simultaneous steppers are supported, all moving
    00103 /// at different speeds and accelerations.
    00104 ///
    00105 /// \par Operation
    00106 /// This module operates by computing a step time in microseconds. The step
    00107 /// time is recomputed after each step and after speed and acceleration
    00108 /// parameters are changed by the caller. The time of each step is recorded in
    00109 /// microseconds. The run() function steps the motor if a new step is due.
    00110 /// The run() function must be called frequently until the motor is in the
    00111 /// desired position, after which time run() will do nothing.
    00112 ///
    00113 /// \par Positioning
    00114 /// Positions are specified by a signed long integer. At
    00115 /// construction time, the current position of the motor is consider to be 0. Positive
    00116 /// positions are clockwise from the initial position; negative positions are
    00117 /// anticlockwise. The curent position can be altered for instance after
    00118 /// initialization positioning.
    00119 ///
    00120 /// \par Caveats
    00121 /// This is an open loop controller: If the motor stalls or is oversped,
    00122 /// AccelStepper will not have a correct
    00123 /// idea of where the motor really is (since there is no feedback of the motor's
    00124 /// real position. We only know where we _think_ it is, relative to the
    00125 /// initial starting point).
    00126 ///
    00127 /// The fastest motor speed that can be reliably supported is 4000 steps per
    00128 /// second (4 kHz) at a clock frequency of 16 MHz. However, any speed less than that
    00129 /// down to very slow speeds (much less than one per second) are also supported,
    00130 /// provided the run() function is called frequently enough to step the motor
    00131 /// whenever required for the speed set.
    00132 class AccelStepper
    00133 {
    00134 public:
    00135     /// Constructor. You can have multiple simultaneous steppers, all moving
    00136     /// at different speeds and accelerations, provided you call their run()
    00137     /// functions at frequent enough intervals. Current Position is set to 0, target
    00138     /// position is set to 0. MaxSpeed and Acceleration default to 1.0.
    00139     /// The motor pins will be initialised to OUTPUT mode during the
    00140     /// constructor by a call to enableOutputs().
    00141     /// \param[in] pins Number of pins to interface to. 1, 2 or 4 are
    00142     /// supported. 1 means a stepper driver (with Step and Direction pins).
    00143     /// If an enable line is also needed, call setEnablePin() after construction.
    00144     /// You may also invert the pins using setPinsInverted().
    00145     /// 2 means a 2 wire stepper. 4 means a 4 wire stepper. 8 means a 4 wire half stepper
    00146     /// Defaults to 4 pins.
    00147     /// \param[in] pin1 Arduino digital pin number for motor pin 1. Defaults
    00148     /// to pin 2. For a driver (pins==1), this is the Step input to the driver. Low to high transition means to step)
    00149     /// \param[in] pin2 Arduino digital pin number for motor pin 2. Defaults
    00150     /// to pin 3. For a driver (pins==1), this is the Direction input the driver. High means forward.
    00151     /// \param[in] pin3 Arduino digital pin number for motor pin 3. Defaults
    00152     /// to pin 4.
    00153     /// \param[in] pin4 Arduino digital pin number for motor pin 4. Defaults
    00154     /// to pin 5.
    00155     AccelStepper(uint8_t pins = 4, uint8_t pin1 = 2, uint8_t pin2 = 3, uint8_t pin3 = 4, uint8_t pin4 = 5);
    00156
    00157     /// Alternate Constructor which will call your own functions for forward and backward steps.
    00158     /// You can have multiple simultaneous steppers, all moving
    00159     /// at different speeds and accelerations, provided you call their run()
    00160     /// functions at frequent enough intervals. Current Position is set to 0, target
    00161     /// position is set to 0. MaxSpeed and Acceleration default to 1.0.
    00162     /// Any motor initialization should happen before hand, no pins are used or initialized.
    00163     /// \param[in] forward void-returning procedure that will make a forward step
    00164     /// \param[in] backward void-returning procedure that will make a backward step
    00165     AccelStepper(void (*forward)(), void (*backward)());
    00166
    00167     /// Set the target position. The run() function will try to move the motor
    00168     /// from the current position to the target position set by the most
    00169     /// recent call to this function.
    00170     /// \param[in] absolute The desired absolute position. Negative is
    00171     /// anticlockwise from the 0 position.
    00172     void    moveTo(long absolute);
    00173
    00174     /// Set the target position relative to the current position
    00175     /// \param[in] relative The desired position relative to the current position. Negative is
    00176     /// anticlockwise from the current position.
    00177     void    move(long relative);
    00178
    00179     /// Poll the motor and step it if a step is due, implementing
    00180     /// accelerations and decelerations to achive the ratget position. You must call this as
    00181     /// fequently as possible, but at least once per minimum step interval,
    00182     /// preferably in your main loop.
    00183     /// \return true if the motor is at the target position.
    00184     boolean run();
    00185
    00186     /// Poll the motor and step it if a step is due, implmenting a constant
    00187     /// speed as set by the most recent call to setSpeed().
    00188     /// \return true if the motor was stepped.
    00189     boolean runSpeed();
    00190
    00191     /// Sets the maximum permitted speed. the run() function will accelerate
    00192     /// up to the speed set by this function.
    00193     /// \param[in] speed The desired maximum speed in steps per second. Must
    00194     /// be > 0. Speeds of more than 1000 steps per second are unreliable.
    00195     void    setMaxSpeed(float speed);
    00196
    00197     /// Sets the acceleration and deceleration parameter.
    00198     /// \param[in] acceleration The desired acceleration in steps per second
    00199     /// per second. Must be > 0.
    00200     void    setAcceleration(float acceleration);
    00201
    00202     /// Sets the desired constant speed for use with runSpeed().
    00203     /// \param[in] speed The desired constant speed in steps per
    00204     /// second. Positive is clockwise. Speeds of more than 1000 steps per
    00205     /// second are unreliable. Very slow speeds may be set (eg 0.00027777 for
    00206     /// once per hour, approximately. Speed accuracy depends on the Arduino
    00207     /// crystal. Jitter depends on how frequently you call the runSpeed() function.
    00208     void    setSpeed(float speed);
    00209
    00210     /// The most recently set speed
    00211     /// \return the most recent speed in steps per second
    00212     float   speed();
    00213
    00214     /// The distance from the current position to the target position.
    00215     /// \return the distance from the current position to the target position
    00216     /// in steps. Positive is clockwise from the current position.
    00217     long    distanceToGo();
    00218
    00219     /// The most recently set target position.
    00220     /// \return the target position
    00221     /// in steps. Positive is clockwise from the 0 position.
    00222     long    targetPosition();
    00223
    00224
    00225     /// The currently motor position.
    00226     /// \return the current motor position
    00227     /// in steps. Positive is clockwise from the 0 position.
    00228     long    currentPosition();
    00229
    00230     /// Resets the current position of the motor, so that wherever the motor
    00231     /// happens to be right now is considered to be the new 0 position. Useful
    00232     /// for setting a zero position on a stepper after an initial hardware
    00233     /// positioning move.
    00234     /// Has the side effect of setting the current motor speed to 0.
    00235     /// \param[in] position The position in steps of wherever the motor
    00236     /// happens to be right now.
    00237     void    setCurrentPosition(long position);
    00238
    00239     /// Moves the motor to the target position and blocks until it is at
    00240     /// position. Dont use this in event loops, since it blocks.
    00241     void    runToPosition();
    00242
    00243     /// Runs at the currently selected speed until the target position is reached
    00244     /// Does not implement accelerations.
    00245     boolean runSpeedToPosition();
    00246
    00247     /// Moves the motor to the new target position and blocks until it is at
    00248     /// position. Dont use this in event loops, since it blocks.
    00249     /// \param[in] position The new target position.
    00250     void    runToNewPosition(long position);
    00251
    00252     /// Disable motor pin outputs by setting them all LOW
    00253     /// Depending on the design of your electronics this may turn off
    00254     /// the power to the motor coils, saving power.
    00255     /// This is useful to support Arduino low power modes: disable the outputs
    00256     /// during sleep and then reenable with enableOutputs() before stepping
    00257     /// again.
    00258     void    disableOutputs();
    00259
    00260     /// Enable motor pin outputs by setting the motor pins to OUTPUT
    00261     /// mode. Called automatically by the constructor.
    00262     void    enableOutputs();
    00263
    00264     /// Sets the minimum pulse width allowed by the stepper driver.
    00265     /// \param[in] minWidth The minimum pulse width in microseconds.
    00266     void    setMinPulseWidth(unsigned int minWidth);
    00267
    00268     /// Sets the enable pin number for stepper drivers.
    00269         /// 0xFF indicates unused (default).
    00270     /// Otherwise, if a pin is set, the pin will be turned on when
    00271     /// enableOutputs() is called and switched off when disableOutputs()
    00272     /// is called.
    00273     /// \param[in] enablePin Arduino digital pin number for motor enable
    00274     /// \sa setPinsInverted
    00275     void    setEnablePin(uint8_t enablePin = 0xff);
    00276
    00277     /// Sets the inversion for stepper driver pins
    00278     /// \param[in] direction True for inverted direction pin, false for non-inverted
    00279     /// \param[in] step      True for inverted step pin, false for non-inverted
    00280     /// \param[in] enable    True for inverted enable pin, false (default) for non-inverted
    00281     void    setPinsInverted(bool direction, bool step, bool enable = false);
    00282
    00283 protected:
    00284
    00285     /// Forces the library to compute a new instantaneous speed and set that as
    00286     /// the current speed. Calls
    00287     /// desiredSpeed(), which can be overridden by subclasses. It is called by
    00288     /// the library:
    00289     /// \li  after each step
    00290     /// \li  after change to maxSpeed through setMaxSpeed()
    00291     /// \li  after change to acceleration through setAcceleration()
    00292     /// \li  after change to target position (relative or absolute) through
    00293     /// move() or moveTo()
    00294     void           computeNewSpeed();
    00295
    00296     /// Called to execute a step. Only called when a new step is
    00297     /// required. Subclasses may override to implement new stepping
    00298     /// interfaces. The default calls step1(), step2(), step4() or step8() depending on the
    00299     /// number of pins defined for the stepper.
    00300     /// \param[in] step The current step phase number (0 to 7)
    00301     virtual void   step(uint8_t step);
    00302
    00303     /// Called to execute a step using stepper functions (pins = 0) Only called when a new step is
    00304     /// required. Calls _forward() or _backward() to perform the step
    00305     virtual void   step0(void);
    00306
    00307     /// Called to execute a step on a stepper drover (ie where pins == 1). Only called when a new step is
    00308     /// required. Subclasses may override to implement new stepping
    00309     /// interfaces. The default sets or clears the outputs of Step pin1 to step,
    00310     /// and sets the output of _pin2 to the desired direction. The Step pin (_pin1) is pulsed for 1 microsecond
    00311     /// which is the minimum STEP pulse width for the 3967 driver.
    00312     /// \param[in] step The current step phase number (0 to 7)
    00313     virtual void   step1(uint8_t step);
    00314
    00315     /// Called to execute a step on a 2 pin motor. Only called when a new step is
    00316     /// required. Subclasses may override to implement new stepping
    00317     /// interfaces. The default sets or clears the outputs of pin1 and pin2
    00318     /// \param[in] step The current step phase number (0 to 7)
    00319     virtual void   step2(uint8_t step);
    00320
    00321     /// Called to execute a step on a 4 pin motor. Only called when a new step is
    00322     /// required. Subclasses may override to implement new stepping
    00323     /// interfaces. The default sets or clears the outputs of pin1, pin2,
    00324     /// pin3, pin4.
    00325     /// \param[in] step The current step phase number (0 to 7)
    00326     virtual void   step4(uint8_t step);
    00327
    00328     /// Called to execute a step on a 4 pin half-steper motor. Only called when a new step is
    00329     /// required. Subclasses may override to implement new stepping
    00330     /// interfaces. The default sets or clears the outputs of pin1, pin2,
    00331     /// pin3, pin4.
    00332     /// \param[in] step The current step phase number (0 to 7)
    00333     virtual void   step8(uint8_t step);
    00334
    00335     /// Compute and return the desired speed. The default algorithm uses
    00336     /// maxSpeed, acceleration and the current speed to set a new speed to
    00337     /// move the motor from teh current position to the target
    00338     /// position. Subclasses may override this to provide an alternate
    00339     /// algorithm (but do not block). Called by computeNewSpeed whenever a new speed neds to be
    00340     /// computed.
    00341     virtual float  desiredSpeed();
    00342
    00343 private:
    00344     /// Number of pins on the stepper motor. Permits 2 or 4. 2 pins is a
    00345     /// bipolar, and 4 pins is a unipolar.
    00346     uint8_t        _pins;          // 2 or 4
    00347
    00348     /// Arduino pin number for the 2 or 4 pins required to interface to the
    00349     /// stepper motor.
    00350     uint8_t        _pin1, _pin2, _pin3, _pin4;
    00351
    00352     /// The current absolution position in steps.
    00353     long           _currentPos;    // Steps
    00354
    00355     /// The target position in steps. The AccelStepper library will move the
    00356     /// motor from the _currentPos to the _targetPos, taking into account the
    00357     /// max speed, acceleration and deceleration
    00358     long           _targetPos;     // Steps
    00359
    00360     /// The current motos speed in steps per second
    00361     /// Positive is clockwise
    00362     float          _speed;         // Steps per second
    00363
    00364     /// The maximum permitted speed in steps per second. Must be > 0.
    00365     float          _maxSpeed;
    00366
    00367     /// The acceleration to use to accelerate or decelerate the motor in steps
    00368     /// per second per second. Must be > 0
    00369     float          _acceleration;
    00370
    00371     /// The current interval between steps in microseconds
    00372     unsigned long  _stepInterval;
    00373
    00374     /// The last step time in microseconds
    00375     unsigned long  _lastStepTime;
    00376
    00377     /// The minimum allowed pulse width in microseconds
    00378     unsigned int   _minPulseWidth;
    00379
    00380     /// Is the direction pin inverted?
    00381     bool           _dirInverted;
    00382
    00383     /// Is the step pin inverted?
    00384     bool           _stepInverted;
    00385
    00386     /// Is the enable pin inverted?
    00387     bool           _enableInverted;
    00388
    00389         /// Enable pin for stepper driver, or 0xFF if unused.
    00390     uint8_t        _enablePin;
    00391
    00392     // The pointer to a forward-step procedure
    00393     void (*_forward)();
    00394
    00395     // The pointer to a backward-step procedure
    00396     void (*_backward)();
    00397 };
    00398
    00399 #endif