Push Button Activated While Loop

Hello,

I want to write a while loop that gets activated and runs only once when I press a push button connected to a digital pin; something like "wait for push button and when activated do the rest".
This should work in a way that if I release the push button in the middle of while loop, the while loop should continue till it finishes naturally. The while loop has a condition like this:

while(analogRead(linsense) <= maxdistance)
{
// do something
}

I want to write a while loop that gets activated and runs only once when I press a push button connected to a digital pin; something like "wait for push button and when activated do the rest".

A while loop says to do something over and over, until a condition is met. It is not intended for a one-time operation. An if statement is.

You probably want to consider doing something only when the transition from released to pressed occurs, not just if the switch is pressed. If you hold the switch down, should the task, whatever it is, be repeated until the switch is released, or should it be done just once?

If it is to be done just once, you need to keep track of the previous state of the switch, so that you can detect the transition (the current state does not match the previous state). The current state then defines whether the transition was pressed-to-released or released-to-pressed.

Hi Paul,

Thank you for your response.

If it is to be done just once, you need to keep track of the previous state of the switch, so that you can detect the transition (the current state does not match the previous state). The current state then defines whether the transition was pressed-to-released or released-to-pressed.

This is exactly what I want to do except only on the released-to-pressed state. I need help on how to do it.

Thanks

This is exactly what I want to do except only on the released-to-pressed state. I need help on how to do it.

int currState = HIGH;
int prevState = HIGH;

void loop()
{
   currState = digitalRead(somePin);
   if(currState != prevState)
   {
      // A transition occurred
      if(currState == LOW)
      {
         // Switch is now pressed
      }
      else
      {
          // Switch is now released
      }
   }
   prevState = currState;
}

If you are using pullup resistors, this code should give you an idea. If you are using pulldown resistors, change all LOWs to HIGHs, and all HIGHs to LOWs, and ask yourself why you are using external hardware, when the Arduino has built in (pullup) resistors.

Examples/digital/buttom

const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);      
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);     
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {     
    // turn LED on:    
    digitalWrite(ledPin, HIGH);  
  } 
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW); 
  }
}

here is the code of how to read a button state, u need to turn on the loop and off presing a button? like pres 1 times do the loop press it again stop the loop?

I need the loop to run only once on the rising edge of my push button. Code?

Something like this?

buttonState = digitalRead(buttonPin);

while(buttonState == HIGH)
{
// do something
}

here the while loop "do something" if the button is presed and stop if u realease the button

but if u whant to do the while loop once

int state = 0;
buttonState = digitalRead(buttonPin);

while(buttonState == HIGH && state == 0)
{
    int = 1;
// do something
} 

while(buttonState == LOW && state == 1)
{
    int = 0;
// do something or nothing xD
}

something like this? xD u can use "if" instead of "while"

buttonState = digitalRead(buttonPin);

while(buttonState == HIGH)
{
// do something
}

That won't work because there is no way for buttonState to change once in the loop. In other words you have to read buttonState each time through the loop to detect the change.

buttonState = digitalRead(buttonPin);

while(buttonState == HIGH)
{
// do something
buttonState = digitalRead(buttonPin); // read the button
}

or something like this

while(digitalRead(buttonPin) == HIGH)
{
// do something
}

I think you guys are missing the question.
I have a set of instruction that needs to run ONLY ONCE when I have a RISING EDGE on the push button input. I dont care about if the button is on or off. The TRANSITION from low to high (or high to low with pullup resistor) matters.
I already got the answer from PaulS... Thank you Paul.

Hi guys and gals

I've a really simple problem that I just cannot seem to get my head around !

I'm looking for a sketch that :

On startup gives a PWM output of 50

On the push of a button (rising edge) the PWM output rises at a definable rate to 255

Then after a set time or the button is released the PWM value drops at the same rate as before down to 50

That's literally it and I just can't work it out ! - major mind block happening right now !

Any help would be greatly appreciated :slight_smile:

Sam

Sam00Cleveland:
Hi guys and gals

I've a really simple problem that I just cannot seem to get my head around !

I'm looking for a sketch that :

On startup gives a PWM output of 50

On the push of a button (rising edge) the PWM output rises at a definable rate to 255

Then after a set time or the button is released the PWM value drops at the same rate as before down to 50

That's literally it and I just can't work it out ! - major mind block happening right now !

Any help would be greatly appreciated :slight_smile:

Sam

This appears to be a duplicate of another post in the thread Momentary push button and loops - Programming Questions - Arduino Forum

Here you go bud, ejoy:

http://forum.arduino.cc/index.php?topic=418302.0

Scroll down to get the answer

That won't work because there is no way for buttonState to change once in the loop. In other words you have to read buttonState each time through the loop to detect the change.

buttonState = digitalRead(buttonPin);

while(buttonState == HIGH)
{
// do something
buttonState = digitalRead(buttonPin); // read the button
}




or something like this



while(digitalRead(buttonPin) == HIGH)
{
// do something
}

I have a similiar question. I want to control a led with an button. If i use the "if/else" function it works fine.
Here is the "if/else" code:

void loop() {
int status_taster01 = digitalRead(taster01);
if (status_taster01 == 1){  
digitalWrite(blau, HIGH);
 }
else {
 digitalWrite(blau, LOW);
 }
}

the other code with the "while" function doesn't work fine:

void loop() {
int status_button_01 = digitalRead(button_01);

while(status_button_01 == HIGH) {
 digitalWrite(blue_led, HIGH);
 status_button_01 = digitalRead(button_01);
}
}

I don't understand why the led just keep working with the while-code.

I hope someone can see the error. Thank u very much.

Nothing turns off the led in your last example using the while loop.

/Mogens

Ahh okay. I think now I understand it. Only because the condition for the while-loop is not true the led dont go off from herself. The while-loop is false but I still need to turn off the led after that.

Thank u

i have a LCD keypad on top of my arduino uno and i want to be able to push the SELECT button on the LCD keypad shield to generate random numbers to be able to simulate rolling the dice on a board game, the problem i'm having is whenever i upload the code to my arduino, it is generating the numbers by itself, plz help and whenever I upload the code to the Arduino I get,
Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

In file included from C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:3:0:

C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void loop()':

C:\Users\taran\Documents\Arduino\libraries\DFR_LCD_Keypad-master/DFR_LCD_Keypad.h:35:35: error: expected '(' before numeric constant

#define DFR_LCD_KEYPAD_KEY_SELECT 4

^

C:\Users\taran\Documents\Arduino\libraries\DFR_LCD_Keypad-master/DFR_LCD_Keypad.h:55:20: note: in expansion of macro 'DFR_LCD_KEYPAD_KEY_SELECT'

#define KEY_SELECT DFR_LCD_KEYPAD_KEY_SELECT

^

C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:31:10: note: in expansion of macro 'KEY_SELECT'

if KEY_SELECT:{

^

demo_simple:50: error: expected '}' at end of input

}

^

exit status 1
expected '}' at end of input

@tarbear124

That last line gives it away, you're missing a } somewhere.

Use tools -> auto format in the IDE and it will show that (but not magically fix it).

I fixed the previous s problem but now I get
Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void loop()':

demo_simple:27: error: expected primary-expression before ')' token

if (btnSELECT)

^

exit status 1
expected primary-expression before ')' token

and the code is

// this is factory config shield initialisation
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// initialise the keypad
DFR_LCD_Keypad keypad(A0, &lcd);
#define btnSELECT 4);
int abc_key_in;
int read_LCD_buttons;
int diceOne;
int diceTwo;

void setup() {
lcd.begin(16, 2);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Press to dice");
abc_key_in = analogRead(0);
}

void loop() {
if (btnSELECT)
diceOne = random(1, 7);
diceTwo = random(1, 7);

if (diceOne + diceTwo == 7) {
lcd.clear();
lcd.setCursor(7, 0);
lcd.print("7");
lcd.setCursor(3, 1);

Next time, add
** **[code]** **
before your code and
** **[/code]** **
after your code. Makes it easier to read and easier to copy.

This is what your code now looks like

// this is factory config shield initialisation
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// initialise the keypad
DFR_LCD_Keypad keypad(A0, &lcd);
#define btnSELECT 4);
int abc_key_in;
int read_LCD_buttons;
int  diceOne;
int  diceTwo;

void setup() {
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  abc_key_in = analogRead(0);
}

void loop() {
  if  (btnSELECT)
  diceOne = random(1, 7);
  diceTwo = random(1, 7);



  if (diceOne + diceTwo == 7) {
    lcd.clear();
    lcd.setCursor(7, 0);
    lcd.print("7");
    lcd.setCursor(3, 1);

That does not seem to be your complete code or there are big parts missing. Each { needs to have a matching }. You will need to fix that first.

The line #define btnSELECT 4); should not have a semi-colon at the end. I suspect that you're missing a #include for the DFR_LCD_Keypad.

Have a look at this example: Arduino_LCD_KeyPad_Shield__SKU__DFR0009_-DFRobot

I fixed the code and now when I upload it to the Arduino, it's running the code by itself, plz help