Created
September 23, 2018 13:18
-
-
Save davidji/6e3cc242467fd7e5e6e13983156113cc to your computer and use it in GitHub Desktop.
Driving a bipolar stepper motor using an ATTiny85
This file contains 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 <Arduino.h> | |
constexpr int DRV_IN1 = PIN_B0; | |
constexpr int DRV_IN2 = PIN_B1; | |
constexpr int DRV_IN3 = PIN_B2; | |
constexpr int DRV_IN4 = PIN_B5; | |
class Winding { | |
public: | |
const int pin1, pin2; | |
constexpr Winding(int pin1, int pin2) : pin1(pin1), pin2(pin2) {} | |
void setup() { | |
pinMode(pin1, OUTPUT); | |
pinMode(pin2, OUTPUT); | |
coast(); | |
} | |
void coast() { | |
digitalWrite(pin1, false); | |
digitalWrite(pin2, false); | |
} | |
void forward() { | |
digitalWrite(pin1, false); | |
digitalWrite(pin2, true); | |
} | |
void backward() { | |
digitalWrite(pin1, true); | |
digitalWrite(pin2, false); | |
} | |
void brake() { | |
digitalWrite(pin1, true); | |
digitalWrite(pin2, false); | |
} | |
}; | |
class Stepper { | |
public: | |
Winding a,b; | |
constexpr Stepper(Winding a, Winding b) : a(a), b(b) {} | |
const void setup() { | |
a.setup(); | |
b.setup(); | |
} | |
void nthstepfwd(int n) { | |
switch(n%8) { | |
case 0: | |
a.backward(); b.coast(); | |
break; | |
case 1: | |
a.backward(); b.forward(); | |
break; | |
case 2: | |
a.coast(); b.forward(); | |
break; | |
case 3: | |
a.forward(); b.forward(); | |
break; | |
case 4: | |
a.forward(); b.coast(); | |
break; | |
case 5: | |
a.forward(); b.backward(); | |
break; | |
case 6: | |
a.coast(); b.backward(); | |
break; | |
case 7: | |
a.backward(); b.backward(); | |
break; | |
} | |
delayMicroseconds(1000); | |
} | |
void stepfwd(int n) { | |
for(int i = 0; i != n; ++n) { | |
nthstepfwd(n); | |
} | |
} | |
}; | |
Stepper stepper(Winding(DRV_IN1, DRV_IN2), Winding(DRV_IN3, DRV_IN4)); | |
void setup() { | |
stepper.setup(); | |
} | |
void loop() { | |
for(int n=0; n != 8; ++n) { | |
stepper.nthstepfwd(n); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment