Hy @ all
like the title says i want to control an dc motor with limit switches.
Overall i´m planning to use 3 pushbuttons:
Button 1: Should start the motor
button 2: should stop the motor after it reaches a specific position
button 3: should do the same like button 2 only on the other end of the rotation
It should work like this:
Button 1 is pressed: the motor turns clockwise until it reaches the position of the 2nd button.
By pressing the second button the motor stops.
After hitting button 1 again: the motor spins counterclockwise until it reaches button 3, then the motor stops, a counter for button 1 gets a reset so that the loop is finished and can be restarted....
I already tried to build a sketch for that purpose but i´m not sure if it will work or if i´m missing something:
int enableA = 6; // Motor A, PWM-Pin
int out1A = 7; // Motor A, Steuerleitung 1
int out2A = 2; // Motor A, Steuerleitung 2
int buttonPin1 = 8;
int buttonPin2 = 9;
int buttonPin3 = 10;
int buttonState = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonPushCounter = 0; // counter for the number of button presses
int lastButtonState = 0; // previous state of the button
void setup() {
Serial.begin(9600);
pinMode(enableA, OUTPUT);
pinMode (out1A, OUTPUT);
pinMode (out2A, OUTPUT);
pinMode(buttonPin1,INPUT);
pinMode(buttonPin2,INPUT);
pinMode(buttonPin3,INPUT);
digitalWrite(enableA, HIGH);
}
void loop()
{
buttonState = digitalRead(buttonPin1); // read the pushbutton input pin
if (buttonState != lastButtonState) { // compare buttonState to previous state
lastButtonState = buttonState; // if the current state is 1 then the button
if (buttonState == 1) { // went from off to on:
buttonPushCounter++; // buttoncounter +1
Serial.println("on");
Serial.print(" ");
Serial.println(buttonPushCounter, DEC);
switch (buttonPushCounter) {
case 1: // If the button count is at 1
Serial.println("1"); // print 1
buttonState2 = digitalRead(buttonPin2); // check limit switch1
if (buttonState2 == HIGH) { // if limit switch1 is pressed
digitalWrite(out1A, LOW); // set pin 2 on L293D low
digitalWrite(out2A, LOW); } // set pin 7 on L293D low
else { // else
digitalWrite(out1A, HIGH); // set pin 2 on L293D high
digitalWrite(out2A, LOW); // set pin 7 on L293D low
}
break;
case 2: // If the button count is at 2
Serial.println("2"); // print 1
buttonState3 = digitalRead(buttonPin3); // check limit switch2
if (buttonState3 == HIGH) { // if limit switch2 is pressed
digitalWrite(out1A, LOW); // set pin 2 on L293D low
digitalWrite(out2A, LOW); } // set pin 7 on L293D low
else { // else
digitalWrite(out1A, LOW); // set pin 2 on L293D low
digitalWrite(out2A, HIGH); } // set pin 7 on L293D high
buttonPushCounter = 0;
break;
}
} }
}