Go Down

Topic: Arduino Nano Start/Stop Button (Read 60 times) previous topic - next topic

Aredunio

My goal was to make a button to stop/start my program at any given time. My current program only allows me to turn it on/off at the precise times in the loop. Any suggestions on how to fix this?

Code: [Select]
#define trigPin 5
#define echoPin 6
#define Buzzer 7

long duration;
int distance;
int run;
int buttonPin;

void setup()
{
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(Buzzer, OUTPUT);
  run = 0; //starts stopped
   buttonPin = 2;

   pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{

  //check button press here and if it is pressed then toggle run variable between 0 and 255; REQUIRED!
  if(digitalRead(buttonPin) == LOW) //funcitons based off of button pulling input pin LOW
  {
     if(run == 0)
     {
         run = 255; //on
     }
     else
     {
         run = 0; //off
     }
  }

while (run == 255 && digitalRead(buttonPin)== HIGH){
     digitalWrite(trigPin, LOW);
     delayMicroseconds(2);
     digitalWrite(trigPin, HIGH);
     delayMicroseconds(10);
     digitalWrite(trigPin, LOW);

    duration = pulseIn(echoPin, HIGH);

    distance = (duration/2) / 29.1;

if (distance < 10)
{
digitalWrite(Buzzer,HIGH); //less than 10cm then buzzer will produce beep sound

}
else {
digitalWrite(Buzzer,LOW);
}

if (distance >= 20|| distance <= 0)
{
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(10);


}
}

blh64

Check out the StateChangeDetection example in the IDE (File->Examples->02 Digital) since what you really want to to know when your button has changed state, not necessarily what the current state is.  When the button goes from HIGH to LOW (a press) you toggle your run variable.  Get rid of the while() loop inside loop()

Also, your run variable could just as easily be a boolean type (true/false) vs. your integer (0/255).

Go Up