//ME 460 Design Project 1 - Stepper Motor Homing
//Create variables for the pins and switch
#define A 3
#define Am 12
#define B 11
#define Bm 13
#define OFF 0
#define N 1
#define S 2
#define BUTTON 7
void setup() {
//Defining what pins are being used
pinMode(Am,OUTPUT); //Coil A
pinMode(A,OUTPUT);
pinMode(Bm,OUTPUT); //COIL B
pinMode(B,OUTPUT);
pinMode(BUTTON, INPUT_PULLUP); //Makes pin 7 corrsepond to terminal
shutdown(); //Turn off the coils
while(digitalread(7)){} //Begins pushbutton monitoring if button is pushed or not
delay(1500);
//Variable Definition
int smax=1; //Defines fastest motor can run
int slow=3; //Defines slowest motor can run
int ct=1;
int T0=0; //zero time variable
void loop() {
//Part 1: Plate moves back towards button at max speed full-stepping
while(digitalRead(BUTTON)){
fullCCW(smax);
}
delay(1000);
//Part 2: Plate moves away from button at slow speed full-stepping
for(int ct=1; ct<=31; ct++){
fullCW(slow);
}
delay(1000);
//Part 3: Plate moves back toward button at slow speed half-stepping
while(digitalRead(BUTTON)){
halfCCW(slow);
}
delay(1000);
//Part 4: Plate moves 30 mm away from button at slow speed and half-stepping
for (int ct=1; ct<=187; ct++){
fullCW(slow);
}
shutdown(); //make sure it turns off when program finishes
while(1);
}
//Full, Half-Step, Shutdown Functions (Both directions)
//Creates a function to shutdown the motor, low voltages to all pins
void shutdown(){
digitalWrite(12,LOW);
digitalWrite(3,LOW);
digitalWrite(13,LOW);
digitalWrite(11,LOW);
}
//Terminal B polarity function
void tb(int polarity){
if (polarity==N){
digitalWrite(Bm, HIGH);
digitalWrite(B, HIGH);
}
if (polarity==S){
digitalWrite(Bm, LOW);
digitalWrite(B, HIGH);
}
else{
digitalWrite(Bm, LOW);
digitalWrite(B, LOW);
}
}
//Term A
void ta(int polarity){
if (polarity==N){
digitalWrite(Am, HIGH);
digitalWrite(A, HIGH);
}
if (polarity==S){
digitalWrite(Am, LOW);
digitalWrite(A, HIGH);
}
else{
digitalWrite(Am, LOW);
digitalWrite(A, LOW);
}
}
//Full step functions
void fullCW(int d){
ta(S);
tb(OFF);
delay(d);
ta(OFF);
tb(N);
delay(d);
ta(N);
tb(OFF);
delay(d);
ta(OFF);
tb(S);
delay(d);
}
void fullCCW(int d){
ta(S);
tb(OFF);
delay(d);
ta(OFF);
tb(S);
delay(d);
ta(N);
tb(OFF);
delay(d);
ta(OFF);
tb(N);
delay(d);
}
//Half-Step Functions
void halfCW(int d){
ta(S);
tb(OFF);
delay(d);
ta(S);
tb(N);
delay(d);
ta(OFF);
tb(N);
delay(d);
ta(N);
tb(N);
delay(d);
ta(N);
tb(OFF);
delay(d);
ta(S);
tb(S);
delay(d);
ta(OFF);
tb(S);
delay(d);
ta(N);
tb(S);
delay(d);
}
void halfCCW(int d){
ta(S);
tb(OFF);
delay(d);
ta(S);
tb(S);
delay(d);
ta(OFF);
tb(S);
delay(d);
ta(N);
tb(S);
delay(d);
ta(N);
tb(OFF);
delay(d);
ta(S);
tb(N);
delay(d);
ta(OFF);
tb(N);
delay(d);
ta(N);
tb(N);
delay(d);
}