//Stepper motor control using A4988 Stepper motor controller.
const int dirPinx = 2;// Direction pin for the x-axis motor
const int stepPinx = 3;//Step pin for the x-axis motor.
const int dirPiny = 4;//Direction pin for the y-axis motor
const int stepPiny = 5;// Step pin for the y-axis motor.
//LEDs for troubleshooting and to observe whether motion is on the x or y axis
const int LEDy = 6;//Used for troubleshooting purposes
const int LEDx = 7;//Used for troubleshooting purposes
//Start button
const int button = 8;
const int automatic = 9;
const int manual = 10;
const int fwdbutton = 11;
const int bwdbutton = 12;
//Cycles for the entire control scheme
const int i = 8;//number of times the process cycles through
//Functions used in the code
void forward(int k);
void backward(int k);
void upward(int k);
void downward(int k);
void setup()
{
// Declare pins as Outputs
pinMode(stepPinx, OUTPUT);
pinMode(dirPinx, OUTPUT);
pinMode(stepPiny, OUTPUT);
pinMode(dirPiny, OUTPUT);
pinMode(LEDy, OUTPUT);
pinMode(LEDx, OUTPUT);
pinMode(button, INPUT);
pinMode(automatic, INPUT);
pinMode(manual, INPUT);
pinMode(fwdbutton, INPUT);
pinMode(bwdbutton, INPUT);
Serial.begin(9600);
}
void loop()
{
int autostate = digitalRead(automatic);
int manstate = digitalRead(manual);
if (autostate == HIGH)
{
Serial.println("Automatic");
int buttonstate = digitalRead(button);
if (buttonstate == HIGH)
{
for (int n = 0; n < 8; n++)
{
forward(500);
delay(500);
downward(400);
delay(2000);
}
backward(4000);
delay(2000);
}
}
else if (manstate == HIGH)
{
Serial.println("Manual State");
int fwd = digitalRead(fwdbutton);
int bwd = digitalRead(bwdbutton);
if (fwd == HIGH)
{
forward(10);
}
else if ( bwd == HIGH)
{
backward(10);
}
else {
Serial.println("Manual State");
}
}
}
void forward(int k)
{
digitalWrite(dirPinx, LOW);
digitalWrite(LEDx, HIGH);
for (int x = 0; x < k; x++)
{
digitalWrite(stepPinx, HIGH);
delayMicroseconds(1000);
digitalWrite(stepPinx, LOW);
delayMicroseconds(1000);
}
digitalWrite(LEDx, LOW);
}
void backward(int k) {
digitalWrite(dirPinx, HIGH);
digitalWrite(LEDx, HIGH);
for (int x = 0; x < k; x++)
{
digitalWrite(stepPinx, HIGH);
delayMicroseconds(1000);
digitalWrite(stepPinx, LOW);
delayMicroseconds(1000);
}
digitalWrite(LEDx, LOW);
}
void upward(int k) {
digitalWrite(dirPiny, HIGH);
digitalWrite(LEDy, HIGH);
for (int x = 0; x < k; x++)
{
digitalWrite(stepPiny, HIGH);
delayMicroseconds(1000);
digitalWrite(stepPiny, LOW);
delayMicroseconds(1000);
}
digitalWrite(LEDy, LOW);
}
void downward(int k) {
digitalWrite(dirPiny, LOW);
digitalWrite(LEDy, HIGH);
for (int x = 0; x < k; x++)
{
digitalWrite(stepPiny, HIGH);
delayMicroseconds(1000);
digitalWrite(stepPiny, LOW);
delayMicroseconds(1000);
}
digitalWrite(LEDy, LOW);
}