interrupt while loop by pressing button

Hello.

I’m trying to stop my while loop after button is pressed (again, same buton start main program), without success :frowning:

I’m using exactly same things as described in example below.

Is it possible accomplish such a task using button (maybe switch will be better option {stay in one position} ) ?

Thank you for any advice.

My code:
{short: program prints 999 times “Hello world.” after button (pin 4) is pressed, and I want to stop it (stop = go back to begin) in given moment (in that loop) by pressing same button}

/*
 Keyboard Message test

 For the Arduino Leonardo and Micro.

 Sends a text string when a button is pressed.

 The circuit:
 * pushbutton attached from pin 4 to +5V
 * 10-kilohm resistor attached from pin 4 to ground

 created 24 Oct 2011
 modified 27 Mar 2012
 by Tom Igoe
 modified 11 Nov 2013
 by Scott Fitzgerald

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/KeyboardMessage
 */

#include "Keyboard.h"

const int buttonPin = 4;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton
int counter = 0;                  // button push counter
int counterloop = 0;           

void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
}

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
  && (buttonState == HIGH)) {
    // increment the button counter
    counter++;
    delay(50);

    while ( counterloop < 1000 ) {

        counterloop++;

         Keyboard.print("Hello world.");
         delay(350);  // waits for a milliseconds

        // Does not work as I thought
        // continually running
        if ( buttonState == HIGH ) {
            break;
            delay(100);
        }
        ////

        delay(50);
    }
    delay(50);
  } 
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

What is the point of the counter variable ?

It looks to me as though it was meant to enable the while loop to be exited when the button was pressed a second time but its value is never tested.

More importantly, the current state of the button pin is never read in the while loop so no wonder that it runs to completion.

Don’t use WHILE. Use IF and allow loop() to do the iteration.

All those delay()s prevent the Arduino from being responsive.

Have a look at how millis() is used to manage timing without blocking in several things at a time

It is completely pointless to include code immediately after break; as it can never be used.

…R

Thank you UKHeliBob, it was very helpfull (puting buttonState = digitalRead(buttonPin) inside loop).

@Robin2 I do not know whether I make myself clearly enough, I wrote “button is pressed,” but what I meant were: button is clicked (push and reales).

And as you pointed out delay makes Arduino unresponsive (It’s hard to click in a corect time to stop loop - more like luck, or push and hold).

I will look in to your link, and I will try to figure that out.

Thank You alot, cheers.

What is the point of the counter variable ?

@UKHeliBob Forgot to answer that. Really, I can't remember (it was in example), I think I forgot to remove it from the code.

It seems that @Geoxxy2000 decided to delete the Post I was referring to

@Geoxxy2000, it is not nice to hijack another person's Thread with your question. I have suggested to the Moderator to move your Post to its own Thread.
To make it easy for people to help you please modify your post and use the code button </>
codeButton.png
~~ ~~so your code looks like this~~ ~~
and is easy to copy to a text editor. See How to use the Forum
Your code is too long for me to study quickly without copying to my text editor. The text editor shows line numbers, identifies matching brackets and allows me to search for things like all instances of a particular variable or function.
Also please use the AutoFormat tool to indent your code for easier reading.

...R

@OP

Another strategy to print message on Serial Monitor while monitoring if a Button has been closed.

int counter = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(4, INPUT); //install 10k at DPin-4 side

  while (digitalRead(4) != HIGH)
  {
    ; //wait here
  }
}

void loop()
{
  while (digitalRead(4) != HIGH)
  {
    Serial.println("Hello World");
    counter++;
    if (counter > 999)
    {
      counter = 0;
      break;
    }
  }
  counter = 0;
}
        // Does not work as I thought
        // continually running
        if ( buttonState == HIGH ) {
            break;
            delay(100);
        }
        ////

Try this:

        buttonState = digitalRead(buttonPin);  // Add this line to get the button state
        if ( buttonState == HIGH ) {
            break;
            delay(100);  // This line will never be executed so it can be removed
        }

It looks like the compiler removes that unneeded delay(100), compiles as 5784 bytes with it both commented and uncommented. Not that that is a reason to leave it there, but interesting to know that the compiler tidies it up.

Metallor:
It looks like the compiler removes that unneeded delay(100), compiles as 5784 bytes with it both commented and uncommented. Not that that is a reason to leave it there, but interesting to know that the compiler tidies it up.

If you set the warning option for the compiler from none (the stupid default) to all, the compiler would warn you that the delay() call was unreachable. Unreachable code is always optimized away.