Skip to content

Instantly share code, notes, and snippets.

@cat-haines
Created September 4, 2014 15:55
Show Gist options
  • Save cat-haines/9ccdfabaf1cf6c53ecb4 to your computer and use it in GitHub Desktop.
Save cat-haines/9ccdfabaf1cf6c53ecb4 to your computer and use it in GitHub Desktop.
class Stepper {
pinArray = null;
currentPosition = null; // 0
stepsPerFullRotation = null; // 200
pin = null; // id for pinArray
delayTime = null; // seconds
constructor(_firstPin, _secondPin, _thirdPin, _fourthPin, _stepsPerFullRotation, _delayTime)
{
pinArray = [_firstPin, _secondPin, _thirdPin, _fourthPin];
for (local i = 0; i < 4; i++)
{
pinArray[i].configure(DIGITAL_OUT);
pinArray[i].write(0);
}
stepsPerFullRotation = _stepsPerFullRotation;
delayTime = _delayTime;
currentPosition = 0;
pin = 0;
}
function StepForward()
{
currentPosition++;
pin = (pin + 1);
if (pin > 3) pin = 0;
pinArray[pin].write(1);
imp.sleep(delayTime);
pinArray[pin].write(0);
}
function StepForwards(steps)
{
for (local i = 0; i < steps; i++)
StepForward();
}
function StepBackward()
{
currentPosition--;
pin = (pin - 1);
if (pin < 0) pin = 3;
pinArray[pin].write(1);
imp.sleep(delayTime);
pinArray[pin].write(0);
}
function StepBackwards(steps)
{
for (local i = 0; i < steps; i++) {
StepBackward();
}
}
function MoveTo(location)
{
local diff = currentPosition - location;
if (diff > 0)
{
if (diff < (stepsPerFullRotation/2) StepBackwards(diff);
else StepForwards(stepsPerFullRotation - diff);
}
else
{
if (diff > (stepsPerFullRotation/-2) StepForwards(math.abs(diff));
else StepBackwards(stepsPerFullRotation + diff);
}
currentPosition = location;
imp.sleep(1.0);
}
function Zero()
{
currentPosition = 0;
}
}
stepper <- Stepper(hardware.pin2, hardware.pin7, hardware.pin5, hardware.pin8, 200, 0.005);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment