Got Stuck in an infinite loop of Mouse.click() function

Hello guys, hope you can help me.

I Got Stuck in an infinite loop of Mouse.click() function.

I wanted to use this code:

void setup(){
  pinMode(2,INPUT);
  //initiate the Mouse library
  Mouse.begin();
}

void loop(){
  //if the button is pressed, send a mouse click
  if(digitalRead(2) == HIGH){
    Mouse.click();
  } 
}

when I uploaded it I practically entered in an infinite loop and because of the functionality of the Mouse.click() instructions, I am not able to even move my mouse because it continues clicking!

Can you please help me solve this problem?

Thanks a lot, I appreciate that.

Robert

Unless you have a pull down resistor connected to pin 2 your pin is floating which means it can randomly be HIGH or LOW. To fix this you can connect your button between pin 2 and ground and change

pinMode(2,INPUT);

to

pinMode(2,INPUT_PULLUP);

and change:

if(digitalRead(2) == HIGH){

to

if(digitalRead(2) == LOW){

This will set the pin to always be HIGH unless it is pulled LOW by being connected to ground.