Current stepper motor code.
Expects:
1 byte in via USB
a 1 in the first bit for ‘revolutions’, a 0 for ‘steps’
a 1 in the 2nd bit for ‘clockwise’, a 0 for ‘anticlockwise’
the remaining 6 bits specify 0-63 clockwise or counterclockwise steps or revolutions
/* Stepper Serial Control
*/
#define COMM_SPEED 38400
int delayTime = 7;
int STEPS = 48;
int stepper = 0;
int offset = 8;
int TOTAL = 4;
void setup() {
for (int count = 0; count < TOTAL; count++) {
pinMode(count + offset, OUTPUT);
}
Serial.begin(COMM_SPEED);
rotateSteps(-1);
rotateSteps(1);
}
void rotateStep(boolean cw) {
if ( cw ) {
stepper = stepper + 1;
}
else {
stepper = stepper - 1;
}
if ( stepper < 0 ) {
stepper = TOTAL - 1;
}
else if ( stepper >= TOTAL ) {
stepper = 0;
}
for (int count = 0; count < TOTAL; count++) {
if ( count == stepper )
digitalWrite(count + offset, HIGH);
else
digitalWrite(count + offset, LOW);
}
delay(delayTime);
}
void rotateSteps(int s) {
bool cw = true;
if ( s < 0 ) {
cw = false;
s = s * -1;
}
for ( int count = 0; count < s; count++ ) {
rotateStep(cw);
}
}
void rotateRevolutions(float revs) {
boolean cw;
if ( revs > 0 ) {
cw = true;
}
else {
cw = false;
revs = revs * -1;
}
for ( int count = 0; count < STEPS * revs; count++ ) {
rotateStep(cw);
}
}
void loop() {
if (Serial.available()) {
byte val = Serial.read(); // - 0x30;
boolean revolutions = false;
byte revs = 128; // revolutions true or false
byte pos = 64; // positive true, negative false
byte mask = 63; // contains the actual data
int v = val;
// first bit is steps or revolutions ( 1 is revs )
if ( val & revs ) {
v = v - revs;
revolutions = true;
}
// second bit is positive or negative ( 1 is pos )
if ( val & pos ) {
v = v - pos;
} else {
v = v * -1;
}
// remaining 6 bits 0 - 63
if ( revolutions ) {
rotateRevolutions(v);
} else {
rotateSteps(v);
}
Serial.flush();
val = 0;
}
}