Spin DC Motor and Control Direction with Button and Speed with Potentiometer

Hello.

I am trying to control my DC motor direction by pressing a button. It is spinning foward as i want but i need to keep the button pressed to go reverse. I need help please. I want to keep the current state of the button and spin the motor based on that. For example… If(button == pressed) then spin reverse. See my code and circuit attached

int enablePin = 11;

int in1Pin = 10;

int in2Pin = 9;

int switchPin = 7;

int potPin = 0;

int statusPin= 13;

void setup()

{

pinMode(in1Pin, OUTPUT);

pinMode(in2Pin, OUTPUT);

pinMode(enablePin, OUTPUT);

pinMode(switchPin, INPUT_PULLUP);

pinMode(statusPin,OUTPUT);

}

void loop()

{

digitalWrite(13,HIGH);

int speed = analogRead(potPin) / 4;

boolean reverse = digitalRead(switchPin);

setMotor(speed, reverse);

}

void setMotor(int speed, boolean reverse)

{

analogWrite(enablePin, speed);

digitalWrite(in1Pin, ! reverse);

digitalWrite(in2Pin, reverse);

}

Have a look at the state change detect tutorial.

Each new press, toggle your boolean, reverse=!reverse.

Also look into debouncing the button. When you press it once, the Arduino is likely to detect a number of presses as the contacts bounce for a few milliseconds.

Also look into debouncing the button.

The poor man's debounce in the state change detect example may be enough, but it's a bit of an "ugly" way.

Hi,
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".
OR
http://forum.arduino.cc/index.php/topic,148850.0.html.
Then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.
Ops circuit.

Thanks.. Tom... :slight_smile: