Skip to content

Examples

The library comes with example sketches, from the smallest one to complete applications. In the Arduino IDE they are found under File → Examples → TeensyStep. All of them use pins 2 and 3 for STEP and DIR of the first motor; change the pin numbers to match the wiring. Every sketch has a README.md in its folder that says what it shows, what has to be connected and what to expect.

Basics

Sketch Shows
01_HelloStepper the smallest sketch: commands on the motor
02_SpeedAndAcceleration maximum speed and acceleration, absolute and relative targets
03_NonBlocking blocking and Async commands, the state of a motor, independent motors
04_Rotate running at a speed, changing it while running, stopping
05_ChangeTarget a new target and a new maximum speed during a move
06_TargetWithSpeed a target with a speed; chaining moves from the arrival function
07_Follower a motor follows a calculated path (a pendulum), commanded from a timer interrupt
08_Homing emergency stop from a switch interrupt, setting the position
09_HomingPrecise a more precise reference: slowly out of the switch, position set where it opens
10_Errors returned codes, an error function, the ready-made handler
11_MotorSettings pull-in speed, pulse width, polarities, DIR setup time, enable pin, separate deceleration
12_EnableFunction an enable signal on a port extender: a function switches the driver instead of a pin

Groups

Sketch Shows
13_Groups synchronized moves; the ways to give the targets; groups created where they are needed; a group that runs slower
14_SyncRotation a group rotating with a fixed speed ratio; the speed factor of a group

Applications

Sketch Shows
15_RoseFunction a slide follows the angle of a spindle and draws a rose curve
16_Winder a coil winder: two independent motors with a ratio that is trimmed while they run

Rose curve (15_RoseFunction)

A spindle rotates at constant speed. A slide moves in and out depending on the angle of the spindle: r = amplitude · cos(k · angle). A pen on the slide then draws a rose curve on a disk that turns with the spindle.

/*==========================================================================
 * 15 RoseFunction: a slide follows the angle of a spindle and draws a rose curve
 *
 * The spindle rotates at constant speed. Every 25 ms a timer gives the slide
 * its next position and the speed there:  r = amplitude * cos(k * angle).
 *==========================================================================*/

#include "TeensyStep.h"
using namespace TeensyStep;

// spindle
constexpr float spindleStpPerRev = 6400;
constexpr float spindleRPM       = 15;
constexpr float spindleSpeed     = spindleRPM / 60 * spindleStpPerRev; // steps/s
constexpr float omega            = spindleRPM / 60 * TWO_PI;           // rad/s

// slide
constexpr float amplitude = 10'000; // steps

// rose function r(phi) = amplitude * cos(k * phi) and its change per second
constexpr float k = 5.0f / 8.0f;
float slidePosition(float phi) { return amplitude * cosf(k * phi); }
float slideSpeed(float phi) { return fabsf(amplitude * k * omega * sinf(k * phi)); } // without a sign, see below

Stepper spindle(1, 2);
Stepper slide(3, 4);

IntervalTimer tickTimer;
constexpr float dt = 0.025f; // s, period of the calculation

void tick() // called every 25 ms
{
    float phiNow  = spindle.getPosition() * (TWO_PI / spindleStpPerRev); // angle of the spindle
    float phiNext = phiNow + omega * dt;                                 // angle at the next call

    slide.moveAbsAsync(slidePosition(phiNext), slideSpeed(phiNext));
}

void setup()
{
    spindle.setAcceleration(50'000);
    slide.setMaxSpeed(35'000).setAcceleration(150'000);

    slide.moveAbs(slidePosition(0));  // move the slide to its start position
    spindle.rotateAsync(spindleSpeed); // let the spindle run

    tickTimer.priority(255); // lowest priority: the calculation must not delay the step pulses
    tickTimer.begin(tick, dt * 1'000'000);
}

void loop()
{
    // print the angle [rad] and the slide position [steps], e.g. for a plot
    Serial.printf("%f\t%d\n", spindle.getPosition() * (TWO_PI / spindleStpPerRev), slide.getPosition());
    delay(20);
}

The slide follows a calculated path. Every 25 ms a timer reads the angle of the spindle, calculates where the slide has to be 25 ms later and how fast it moves there, and gives both to the slide as a target with a speed. The slide therefore does not stop at each point but runs through the points smoothly. The speed is given without a sign, so that the slide passes each point in the direction in which it comes to it.

The commands of the library may be called from a timer interrupt, as it is done here. Such a timer gets a low priority, so that it does not delay the step pulses, see Interrupts.

Coil winder (16_Winder)

A string or coil winder has two motors: the spindle rotates the core, and the feeder moves the wire along it. The pitch (1) is the ratio of the two speeds. It has to stay constant while the spindle speeds up or slows down, and it shall be trimmable while the machine winds.

  1. Pitch

    The way of the feeder for each turn of the spindle, in mm. It sets how close the turns of the wire lie to each other.

/*==========================================================================
 * 16 Winder: two motors with a ratio that can be adjusted while running
 *
 * A coil winder: the spindle turns the core, the feeder moves the wire along
 * it. The motors run independently, so that the pitch can be trimmed.
 *==========================================================================*/

#include "TeensyStep.h"
using namespace TeensyStep;

// mechanics
constexpr float spindleStpPerRev = 200 * 16;       // full steps * microstepping
constexpr float feederStpPerMM   = 200 * 8 * 5.0f; // full steps * microstepping * turns of the lead screw per mm
constexpr float spindleAcc       = 30'000;         // steps/s^2
constexpr float feederTrimAcc    = 100'000;        // steps/s^2, used for pitch changes only

Stepper spindle(0, 1);
Stepper feeder(2, 3);

float spindleSpeed = 0; // steps/s
float ratio        = 0; // feeder steps per spindle step

float toRatio(float pitch_mm) { return pitch_mm * feederStpPerMM / spindleStpPerRev; }

// new spindle speed, same pitch: both motors ramp together
void setSpindleSpeed(float rpm)
{
    spindleSpeed = rpm / 60 * spindleStpPerRev;

    feeder.setAcceleration(spindleAcc * ratio); // both ramps take the same time
    spindle.rotateAsync(spindleSpeed);
    feeder.rotateAsync(spindleSpeed * ratio); // speed 0 stops the motor
}

// new pitch, same spindle speed: only the feeder changes
void setPitch(float pitch_mm)
{
    ratio = toRatio(pitch_mm);

    feeder.setAcceleration(feederTrimAcc);
    feeder.rotateAsync(spindleSpeed * ratio);
}

void setup()
{
    spindle.setAcceleration(spindleAcc);

    setPitch(0.10f);       // mm per turn
    setSpindleSpeed(1125); // rpm: start winding

    delay(3000);
    setPitch(0.12f); // trim the pitch while winding
    delay(500);
    setPitch(0.08f);
    delay(500);
    setPitch(0.15f);

    delay(3000);
    setSpindleSpeed(300); // slow down, pitch stays at 0.15 mm

    delay(2500);
    setSpindleSpeed(0); // stop
}

void loop()
{
    if (spindle.isMoving()) // print time, both speeds and the actual pitch, e.g. for a diagram
    {
        float pitch = feeder.getSpeed() / spindle.getSpeed() * spindleStpPerRev / feederStpPerMM;
        Serial.printf("%u\t%.0f\t%.0f\t%.3f\n", millis(), spindle.getSpeed(), feeder.getSpeed(), pitch);
    }
    delay(25);
}

A rotating group keeps a ratio exactly, but the ratio cannot change while the group runs. The two motors of the winder therefore run independently, and the sketch keeps the ratio itself:

  • The spindle speed changes (setSpindleSpeed()): both motors get their new speed at the same moment, and the acceleration of the feeder is set to that of the spindle times the ratio. Both ramps then take the same time, and the pitch stays constant during the ramp.
  • The pitch changes (setPitch()): only the feeder gets a new speed, with an acceleration of its own.

The sketch winds at 1125 rpm, trims the pitch three times, slows down to 300 rpm and stops. It prints the time, both speeds and the pitch they make, for a diagram.

Advanced

Sketch Shows
advanced/GroupWaypoints a group that passes waypoints without stopping, with advanced::GroupPath; see Paths of a group
advanced/MiniPlanner a motion planner in one sketch: an x-y table draws curved figures without stopping at their points; the hardware is in files of its own. See Writing a motion planner
advanced/PathPlanner a larger motion planner with limits for each motor: an x-y table runs a path of points in mm and passes each point as fast as the motors allow; see Writing a motion planner

Sketches of version 2

Sketch Shows
17_LegacyV2 an unchanged version 2 sketch on the deprecated controllers; the translation table is in Upgrading
version2/ examples of TeensyStep 2, unchanged: HelloStepper, MultipleSteppers, StepperArray, Interfacing, Winder, RoseFunctionFollower

See Upgrading from version 2.

The simplest example

/*==========================================================================
 * 01 HelloStepper: the smallest possible sketch
 *
 * STEP on pin 2, DIR on pin 3 (any pins work).
 *==========================================================================*/

#include "TeensyStep.h"
using namespace TeensyStep;

Stepper motor(2, 3); // STEP pin 2, DIR pin 3

void setup()
{
}

void loop()
{
    motor.moveRel(1000); // 1000 steps forward
    delay(500);

    motor.moveRel(-1000); // and back
    delay(500);
}