// https://forum.arduino.cc/t/controlling-stepper-and-dc-motor-with-arduino/1341679/
#define stepsPerRevolution 200
int home;
byte buttonPin = 3, stepPin = 6, dirPin = 5, dcFwdPin = 14, dcRevPin = 15;
char key;
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
digitalWrite(dirPin, HIGH);
Serial.print("Enter 'A' or 'a': ");
}
void loop() {
getinput();
if ( key == 'A' || key == 'a') { // User clicks A from Keyboard.
Serial.println(key);
fiftysteps(1); // Stepper Motor moves 50 steps.
checkbutton(); // needs limit switch
Serial.print("Pause"); pause(5); // Pause in the system for 5 seconds.
dcmotor(1); // The DC Motor moves for 3 seconds.
Serial.print("Pause"); pause(5); // Pause in the system for 5 seconds.
dcmotor(0); // DC Motor moves for 3 seconds in the opposite direction.
Serial.print("Pause"); pause(5); // Pause in the system for 5 seconds.
fiftysteps(1); // Stepper Motor moves 50 steps.
checkbutton(); // needs limit switch
Serial.print("Pause"); pause(5); // Pause in the system for 5 seconds.
dcmotor(1); // The DC Motor moves for 3 seconds.
Serial.print("Pause"); pause(5); // Pause in the system for 5 seconds.
dcmotor(0); // The DC Motor moves for 3 seconds in the opposite direction.
Serial.print("Pause"); pause(5); // Pause in the system for 5 seconds.
fiftysteps(0); // Stepper Motor moves back 100 steps so it's back to it's original place.
fiftysteps(0); // Stepper Motor moves back 100 steps so it's back to it's original place.
}
}
char getinput() {
if (Serial.available()) {
key = Serial.read();
delay(10); // let buffer clear
}
}
void fiftysteps(int dir) {
Serial.print("Stepper motor 50 steps ");
Serial.print(dir ? "fowrard." : "reverse.");
digitalWrite(dirPin, dir);
for (int i = 0; i < 50; i++) {
home += (dir ? +1 : -1);
digitalWrite(stepPin, HIGH);
delayMicroseconds(2000);
digitalWrite(stepPin, LOW);
delayMicroseconds(2000);
}
Serial.print(" Position: ");
Serial.print(home);
if (!home)
Serial.println(" I'M HOME!");
else
Serial.println();
}
void checkbutton() {
Serial.print("Limit switch... ");
while (digitalRead(buttonPin));
Serial.print("tripped. ");
}
void pause(int seconds) {
Serial.print(" ");
Serial.print(seconds);
Serial.print(" seconds: ");
for (int i = 0; i < seconds + 1; i++) {
Serial.print(i);
delay(1000);
}
Serial.println();
}
void dcmotor(int dir) {
Serial.print("DC motor ");
Serial.print(dir ? "fowrard" : "reverse");
if (dir) {
digitalWrite(dcFwdPin, HIGH);
digitalWrite(dcRevPin, LOW);
} else {
digitalWrite(dcFwdPin, LOW);
digitalWrite(dcRevPin, HIGH);
}
pause(3);
digitalWrite(dcFwdPin, LOW);
digitalWrite(dcRevPin, LOW);
}
REV
FWD
LIMIT