Created
July 18, 2023 16:28
-
-
Save oliverswitzer/a7e62504025e4bacfdc8abe3d48d60db to your computer and use it in GitHub Desktop.
POC For an async stepper in Arduino
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Stepper.h" | |
Stepper stepper; | |
long currentTime; | |
long lastBeginStep; | |
void setup() {} | |
void loop() { | |
stepper.step() | |
currentTime = millis(); | |
if(currentTime - lastBeginStep > 5000) { | |
lastBeginStep = currentTime; | |
stepper.beginStep(1000, Stepper::StepDirection::FORWARD, 500); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Stepper { | |
public: | |
enum StepDirection { FORWARD, REVERSE }; | |
// ... Other members ... | |
void beginStep(int numSteps, StepDirection direction, int speed) { | |
// Ignore beginStep if the stepper is already stepping | |
if (_inMotion) { | |
return; | |
} | |
Serial.println("Beginning a new step process..."); | |
// Initialize step parameters | |
_numSteps = numSteps; | |
_direction = direction; | |
_speed = speed; | |
_stepsMade = 0; | |
_lastStepTime = micros(); | |
_inMotion = true; | |
Serial.println("_numSteps: "); | |
Serial.print(_numSteps); | |
Serial.println("_direction: "); | |
Serial.print(_direction); | |
Serial.println("_speed"); | |
Serial.print(_speed); | |
} | |
void step() { | |
// Check if a step is due | |
unsigned long currentMicros = micros(); | |
if (currentMicros - _lastStepTime >= 1000000/_speed) { | |
// Time for a step | |
if (_stepsMade < _numSteps) { | |
// Do the step | |
digitalWrite(_stpPin, _direction == StepDirection::FORWARD ? LOW : HIGH); | |
digitalWrite(_stpPin, LOW); | |
_stepsMade++; | |
} else { | |
// All steps made, disable motor | |
digitalWrite(_enablePin, HIGH); | |
_inMotion = false; | |
} | |
_lastStepTime = currentMicros; | |
} | |
} | |
private: | |
// Placeholder pin definitions, update with your actual pin assignments | |
const int _stpPin = 9; | |
const int _enablePin = 10; | |
// ... Other members ... | |
volatile int _numSteps; | |
volatile StepDirection _direction; | |
volatile int _speed; | |
volatile int _stepsMade; | |
volatile unsigned long _lastStepTime; | |
volatile bool _inMotion; // Flag indicating whether a stepping sequence is currently in progress | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment