DC motor control

Hello every, I'm working on a project in order to control a DC motor.

The basic functions are:

  • The motor spun clockwise by pressing button 1

  • The motor spun counterclockwise by pressing button 2

  • The button 3 is a stop button

  • When the motor is turning, you must press the stop button before you press another button to change the direction of rotation.

Below is my Arduino code:

int pin5 = 5; // MOTOR connected to digital pin 5
int pin6 = 6; // MOTOR connected to digital pin 6
bool motor_run = false; // variable to check motor-run state

#define button1 A1
#define button2 A2
#define button3 A3

void setup()
{
pinMode(pin5, OUTPUT);
pinMode(pin6, OUTPUT);
}

void loop()
{

if (digitalRead(button1) == 1 && digitalRead(button2)==0 && motor_run == false)
{
analogWrite(pin5,0);
motor_run = true;
delay(300);
}

if (digitalRead(button2) == 1 && digitalRead(button1)==0 && motor_run == false)
{
analogWrite(pin6, 0);
motor_run = true;
delay(300);
}

if (digitalRead(button3) == 1 && motor_run==true) // motor stop
{
digitalWrite(pin5, HIGH);
digitalWrite(pin6, HIGH);
motor_run = false;
}
}

I would like to add a function to this project.

  • When the motor is spinning, I can press button 1 to lower the motor speed, or press button 2 to increase the motor speed.

  • At the same time, it does not change the current direction of the motor.

  • Button 3 can also be pressed at any time to stop the motor from rotating.

How should I modify my Arduino code to achieve my above goals?

Thank you very much

what have you tried? Give it a try and if you have trouble, post your code and people can help. People aren't here to write code for you.

int pin5 = 5;    // MOTOR connected to digital pin 5
int pin6 = 6;    // MOTOR connected to digital pin 6

Those are pretty dumb names. If you need to move the motors to pins 9 and 10, do you plan to rename the variables?

Using names like motor1 and motor2 will tell us which motor is being acted on later.

Of course, those names are not all that much better, because the purpose of the 1st motor is not to one, and the purpose of the 2nd motor is not to two.

Use names for the variables that make sense, given the unstated purpose(s) of the motor(s).

  • When the motor is turning, you must press the stop button before you press another button to change the direction of rotation.

Nothing in your code requires that.

    if (digitalRead(button3) == 1 && motor_run==true)  // motor stop
  {
    digitalWrite(pin5, HIGH);
    digitalWrite(pin6, HIGH);
    motor_run = false;
  }

You seem to think that the motor will stop instantaneously. I'd be very surprised if that happened.