ccarrasco
ccarrasco

Reputation: 3

Infinite Loop in Arduino Leonardo

i loaded a basic program to my Arduino Leonardo:

void setup() {
  // make pin 2 an input and turn on the 
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  //if the button is pressed
  if(digitalRead(2)==LOW){
    //Send the message
    Keyboard.print("Hello!");
  }
}

This example works, but it generate a infinite loop printing "Hello!". How can i control the loop?

The basic example is: http://arduino.cc/en/Reference/KeyboardPrint

Thanks !

Upvotes: 0

Views: 131

Answers (1)

paxdiablo
paxdiablo

Reputation: 882206

If you want to say hello whenever the button transitions from off to on, you need to remember the previous state in a variable.

Then you only say hello when the current state is pressed and the previous state was not-pressed.

That would be something like:

int curr, prev = HIGH;
void loop () {
    curr = digitalRead (2);
    if ((prev == HIGH) && (curr == LOW)) {
        Keyboard.print("Hello!");
    }
    prev = curr;
}

Upvotes: 1

Related Questions