interrupt while loop by pressing button


hello.

i'm trying stop while loop after button pressed (again, same buton start main program), without success :(

i'm using same things described in example below.


is possible accomplish such task using button (maybe switch better option {stay in 1 position} ) ?

thank advice.

my code:
{short: program prints 999 times "hello world." after button (pin 4) pressed, , want stop (stop = go begin) in given moment (in loop) pressing same button}

code: [select]
/*
 keyboard message test

 for arduino leonardo , micro.

 sends text string when button pressed.

 the circuit:
 * pushbutton attached pin 4 +5v
 * 10-kilohm resistor attached pin 4 ground

 created 24 oct 2011
 modified 27 mar 2012
 by tom igoe
 modified 11 nov 2013
 by scott fitzgerald

 this example code in public domain.

 http://www.arduino.cc/en/tutorial/keyboardmessage
 */

#include "keyboard.h"

const int buttonpin = 4;          // input pin pushbutton
int previousbuttonstate = high;   // checking state of pushbutton
int counter = 0;                  // button push counter
int counterloop = 0;           

void setup() {
  // make pushbutton pin input:
  pinmode(buttonpin, input);
  // initialize control on keyboard:
  keyboard.begin();
}

void loop() {
  // read pushbutton:
  int buttonstate = digitalread(buttonpin);
  // if button state has changed,
  if ((buttonstate != previousbuttonstate)
      // , it's pressed:
  && (buttonstate == high)) {
    // increment button counter
    counter++;
    delay(50);

    while ( counterloop < 1000 ) {

        counterloop++;

         keyboard.print("hello world.");
         delay(350);  // waits milliseconds

        // not work thought
        // continually running
        if ( buttonstate == high ) {
            break;
            delay(100);
        }
        ////

        delay(50);
    }
    delay(50);
  }
  // save current button state comparison next time:
  previousbuttonstate = buttonstate;
}

what point of counter variable ?

it looks me though meant enable while loop exited when button pressed second time value never tested.

more importantly, current state of button pin never read in while loop no wonder runs completion.


Arduino Forum > Using Arduino > Programming Questions > interrupt while loop by pressing button


arduino

Comments

Popular posts from this blog

DHT11 Time out error using v0.4.1library

Sketch upload fails with Java error (___REMOVE___/bin/avrdude)!

Arduino Uno + KTY81/210 temperature sensor