Library to run 4-wire half stepper in asynchronous mode
Diff: Async_4pin_Stepper.cpp
- Revision:
- 0:252d645cfc5d
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Async_4pin_Stepper.cpp Thu Jun 03 21:38:34 2021 +0000 @@ -0,0 +1,128 @@ +/* Asynchronous Stepper with 4-pin output + * + * Written by Simon Krogedal + * 31/05/2021 + * Team 9 4th Year project + * + * for NUCLEO-F401RE + * + * Version 0.1 + * + */ + +#include "Async_4pin_Stepper.h" + +// Constructor takes 4 pins and a steps/rev in float presicion +Async_4pin_Stepper::Async_4pin_Stepper( PinName StepperPin1, + PinName StepperPin2, + PinName StepperPin3, + PinName StepperPin4, + float StepsPerRev) : + + output(StepperPin1, + StepperPin2, + StepperPin3, + StepperPin4) +{ + SPR = StepsPerRev; + setSpeed(500); + currentPos = 0; + relax(); +} + +void Async_4pin_Stepper::setZeroPos() {currentPos = 0;} + +void Async_4pin_Stepper::setSpeed(int speed) { + if(speed > 0) { + speed_ = speed; + stepInterval = 1.0/speed; + } + else { + speed_ = 0; + stepInterval = 0; + } +} + +int Async_4pin_Stepper::getPos() {return currentPos;} +int Async_4pin_Stepper::getTarget() {return targetPos;} +int Async_4pin_Stepper::getSpeed() {return speed_;} +int Async_4pin_Stepper::distanceToGo() {return targetPos-currentPos;} + +void Async_4pin_Stepper::step(int step) { + switch (step & 0x7) { + case 0: // 1000 + output = 0b0001; + break; + + case 1: // 1010 + output = 0b0101; + break; + + case 2: // 0010 + output = 0b0100; + break; + + case 3: // 0110 + output = 0b0110; + break; + + case 4: // 0100 + output = 0b0010; + break; + + case 5: //0101 + output = 0b1010; + break; + + case 6: // 0001 + output = 0b1000; + break; + + case 7: //1001 + output = 0b1001; + break; + } +} + +void Async_4pin_Stepper::stepOnceCCW() { + // Update current position + currentPos++; + // Step to new position + step(currentPos); +} + +void Async_4pin_Stepper::stepOnceCW() { + // Update current position + currentPos--; + // Step to new position + step(currentPos); +} + +void Async_4pin_Stepper::setTarget(int target) {targetPos = target;} + +void Async_4pin_Stepper::goToTarget() { + // Check if at target or standstill + if(!distanceToGo() || !stepInterval || running) + return; + else { // Attach ticker to callback function + ticker.attach(callback(this, &Async_4pin_Stepper::stepCB), stepInterval); + running = true; + } +} + +void Async_4pin_Stepper::stepCB() { + // check error value for driction + int error = distanceToGo(); + if(error == 0) { + ticker.detach(); + running = false; + } + else if(error > 0) + stepOnceCCW(); + else + stepOnceCW(); +} + +void Async_4pin_Stepper::relax() {output = 0;} +bool Async_4pin_Stepper::isRunning() {return running;} +void Async_4pin_Stepper::stop() {ticker.detach();} \ No newline at end of file