It works but...

I just wrote a simple keyboard code. The code looks clean and generally working as it should but sometimes it prints double. I couldn't understand why.

#include "Keyboard.h"
int state = 0;
void setup() {
  pinMode(5, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  switch (digitalRead(5)){
    case LOW:
      Keyboard.press(120);
      state = 1;
     break;
    case HIGH:
    if (state==1){
      Keyboard.release(120);
      state=0;
    }
     break;
  }
}

When you press a button, it switches on and off many times really quickly. You need to debounce the input:

Pieter

Contact bounce ?

PieterP:
When you press a button, it switches on and off many times really quickly. You need to debounce the input:
https://www.arduino.cc/en/Tutorial/Debounce

Pieter

Ok, I looked a bit to example but I couldn't understand because I'm new in arduino world. I have just understand what the debounce is but, man that example code is too complicated and I can't compare it to my code as it includes LED and I don't want to just copy and paste the whole code and edit it, I want to learn it so can you please explain it a little bit if you have some spare time? Or maybe someone?

Did you not understand the comments in the code? It's pretty well documented.

Hi,
Welcome to the Forum

Check this link, it explains contact bounce and a library to do the debounce for you, including an example code.

https://playground.arduino.cc/Code/Buttons

also here;

https://playground.arduino.cc/Code/Button

Which ever suits.

Tom... :slight_smile: