A class for driving a stepper motor via driver with indexer.

Dependents:   StepperTest

Committer:
tbjazic
Date:
Thu Dec 01 13:35:45 2016 +0000
Revision:
0:12be56dc6182
Child:
1:9888802e71b9
Initial commit.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
tbjazic 0:12be56dc6182 1 #include "mbed.h"
tbjazic 0:12be56dc6182 2 #include "StepperDriver.h"
tbjazic 0:12be56dc6182 3
tbjazic 0:12be56dc6182 4 StepperDriver::StepperDriver(PinName outputPin, PinName directionPin) : output(outputPin), direction(directionPin) {
tbjazic 0:12be56dc6182 5 currentPosition = previousPosition = desiredPosition = 0;
tbjazic 0:12be56dc6182 6 maxPosition = 500;
tbjazic 0:12be56dc6182 7 minPosition = 0;
tbjazic 0:12be56dc6182 8 homePosition = (maxPosition - minPosition) / 2;
tbjazic 0:12be56dc6182 9 }
tbjazic 0:12be56dc6182 10
tbjazic 0:12be56dc6182 11 void StepperDriver::setPosition(uint32_t position) {
tbjazic 0:12be56dc6182 12 if (position >= minPosition && position <= maxPosition) {
tbjazic 0:12be56dc6182 13 desiredPosition = position;
tbjazic 0:12be56dc6182 14 }
tbjazic 0:12be56dc6182 15 if (desiredPosition != currentPosition && !isTickerAttached) {
tbjazic 0:12be56dc6182 16 attachTicker();
tbjazic 0:12be56dc6182 17 }
tbjazic 0:12be56dc6182 18 }
tbjazic 0:12be56dc6182 19
tbjazic 0:12be56dc6182 20 void StepperDriver::update() {
tbjazic 0:12be56dc6182 21 if (desiredPosition > currentPosition) {
tbjazic 0:12be56dc6182 22 direction = 1;
tbjazic 0:12be56dc6182 23 currentPosition++;
tbjazic 0:12be56dc6182 24 generateImpulse();
tbjazic 0:12be56dc6182 25 } else if (desiredPosition < currentPosition) {
tbjazic 0:12be56dc6182 26 direction = 0;
tbjazic 0:12be56dc6182 27 currentPosition--;
tbjazic 0:12be56dc6182 28 generateImpulse();
tbjazic 0:12be56dc6182 29 } else {
tbjazic 0:12be56dc6182 30 detachTicker();
tbjazic 0:12be56dc6182 31 }
tbjazic 0:12be56dc6182 32 previousPosition = currentPosition;
tbjazic 0:12be56dc6182 33 }
tbjazic 0:12be56dc6182 34
tbjazic 0:12be56dc6182 35 void StepperDriver::attachTicker() {
tbjazic 0:12be56dc6182 36 ticker.attach(this, &StepperDriver::update, 4e-3);
tbjazic 0:12be56dc6182 37 isTickerAttached = true;
tbjazic 0:12be56dc6182 38 }
tbjazic 0:12be56dc6182 39
tbjazic 0:12be56dc6182 40 void StepperDriver::detachTicker() {
tbjazic 0:12be56dc6182 41 ticker.detach();
tbjazic 0:12be56dc6182 42 isTickerAttached = false;
tbjazic 0:12be56dc6182 43 }
tbjazic 0:12be56dc6182 44
tbjazic 0:12be56dc6182 45 void StepperDriver::generateImpulse() {
tbjazic 0:12be56dc6182 46 output = 1;
tbjazic 0:12be56dc6182 47 timeout.attach(this, &StepperDriver::turnOutputOff, 100e-6);
tbjazic 0:12be56dc6182 48 }
tbjazic 0:12be56dc6182 49
tbjazic 0:12be56dc6182 50 void StepperDriver::turnOutputOff() {
tbjazic 0:12be56dc6182 51 output = 0;
tbjazic 0:12be56dc6182 52 }