const float pi = 3.14159;
const int DirPin = 8;
const int StepPin = 9;
const int EndPin = 2; // the pin for the button sensors
const int startPin = 3;
float initializeSpeed = 0.005; // the linear speed of the motor (m/s)
int stepCount;
int currentStep;
int totalStepLength;
void setup() {
pinMode(StepPin, OUTPUT);
pinMode(DirPin, OUTPUT);
pinMode(EndPin, INPUT);
pinMode(startPin, INPUT);
Serial.begin(9600);
initialize();
Serial.print("Total Step Count= ");
Serial.println(totalStepLength);
delay(500);
Serial.print("current Step= ");
Serial.println(currentStep);
}
void loop() {
}
// This is the first function used in the set up process
// it used the button sensors to measure the length of the
// track in "step" units.
void initialize() {
float pulse = (((2*pi*0.008*0.005)/initializeSpeed)/2)*1e6;
Serial.print("pulse time = ");
Serial.print(pulse);
Serial.println(" x 10^-6");
// this section of code could be used to have the program wait till a button is pressed
while (digitalRead(startPin) == LOW) {
}
// move the stepper clockwise until the first button is clicked
while (digitalRead(EndPin) == LOW) {
digitalWrite(DirPin, HIGH);
digitalWrite(StepPin, HIGH);
delayMicroseconds(pulse);
digitalWrite(StepPin, LOW);
delayMicroseconds(pulse);
}
delay(500);
// move the stepper counter-clockwise until the second
// button is clicked while counting steps for the
// total length of the track
while (digitalRead(EndPin) == LOW) {
digitalWrite(DirPin, LOW);
digitalWrite(StepPin, HIGH);
delayMicroseconds(pulse);
digitalWrite(StepPin, LOW);
delayMicroseconds(pulse);
stepCount++;
}
// update global variables for total step length
// and calculate middle position in "step" units
delay(500);
totalStepLength = stepCount;
int middlePos = totalStepLength/2;
Serial.print("middle position steps= ");
Serial.println(middlePos);
stepCount = 0; // reseting step count to make endpoint new starting point
currentStep = stepCount;
// moving bed to center & update current step location
for(int x = 0; x < middlePos; x++) {
digitalWrite(DirPin, HIGH);
digitalWrite(StepPin, HIGH);
delayMicroseconds(pulse);
digitalWrite(StepPin, LOW);
delayMicroseconds(pulse);
currentStep++;
}
}