forked from section77/EggDuino
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Stepper.cpp
42 lines (34 loc) · 888 Bytes
/
Stepper.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "Stepper.h"
#include <Arduino.h>
Stepper::Stepper(char stepPin, char dirPin)
: mStepPin(stepPin)
, mDirPin(dirPin)
, mNumSteps(0)
{
pinMode(mDirPin, OUTPUT);
digitalWrite(mDirPin, HIGH);
pinMode(mStepPin, OUTPUT);
digitalWrite(mStepPin, LOW);
}
void Stepper::setTarget(int numSteps, unsigned long duration)
{
if (numSteps == 0 || duration <= 0)
return;
digitalWrite(mDirPin, (numSteps < 0) ? LOW : HIGH);
mNumSteps = abs(numSteps);
mStepInterval = duration * 1000 / mNumSteps;
mStartTime = micros();
}
void Stepper::update()
{
if (mNumSteps == 0)
return;
const unsigned long now = micros();
const unsigned long elapsed = now - mStartTime;
if (elapsed < mStepInterval)
return;
digitalWrite(mStepPin, HIGH);
digitalWrite(mStepPin, LOW);
mNumSteps--;
mStartTime = now;
}