Motor runs and wont stop.

So basically my project does exactly what i want it to except one thing, Im not sure how to get it to only run once.

int run;
int buttonPin;
int dir1 = 4;
int dir2 = 3;
int mSpeed = 255;
int Stspeed = 0;
int Speedpin = 5;

void setup()
{
  run = 0; 
   buttonPin = 7; 

  pinMode(buttonPin, INPUT_PULLUP);

  pinMode(Speedpin, OUTPUT);
  pinMode(dir1, OUTPUT);
  pinMode(dir2, OUTPUT);
  Serial.begin(96000);
}

void loop()
{
 
  if(digitalRead(buttonPin) == LOW) 
  {
     if(run == 0)
     {
         run = 255;
     }
     else
     {
         run = 0;
     }
  }

  if(run > 0)
  {
    digitalWrite(dir1, HIGH);
  digitalWrite(dir2, LOW);
  analogWrite(Speedpin, mSpeed);
  delay(4000);
  analogWrite(Speedpin, Stspeed);
  delay(1000);
  digitalWrite(dir1, LOW);
  digitalWrite(dir2, HIGH);
  analogWrite(Speedpin, mSpeed);
  delay(4000);
  analogWrite(Speedpin, Stspeed);
  digitalWrite(run, LOW)

  }
}

If i run this it doesn't do anything , once i press the button is run the motor, great that's what I want then it run the motor loop agian.... no good idiealy it will run once until the button is pressed again.
Any ideas on how to do that?

Change:

digitalWrite(run, LOW) // set pin number 255 LOW

To:

run = 0;

I would write:

int buttonPin = 7;
int dir1 = 4;
int dir2 = 3;
int mSpeed = 255;
int Stspeed = 0;
int Speedpin = 5;

void setup()
{
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(Speedpin, OUTPUT);
  pinMode(dir1, OUTPUT);
  pinMode(dir2, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  while(digitalRead(buttonPin) == HIGH); // loop here while
                                         // button is not pressed 
  digitalWrite(dir1, HIGH);
  digitalWrite(dir2, LOW);
  analogWrite(Speedpin, mSpeed);
  delay(4000);
  analogWrite(Speedpin, Stspeed);
  delay(1000);
  digitalWrite(dir1, LOW);
  digitalWrite(dir2, HIGH);
  analogWrite(Speedpin, mSpeed);
  delay(4000);
  analogWrite(Speedpin, Stspeed);
  digitalWrite(dir1, LOW);
  digitalWrite(dir2, LOW);
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.