Keyboard write Issue

Real newbie here. I need to write a 'P' character with my Leonardo chip controller. I have been successful but I need a tweek or new method. here is my code:

#include <Keyboard.h>

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 an ASCII 'P',
Keyboard.write(80);
}
}
The problem is I'm getting multiple writes every time I activate the pull down. I'm getting a hundred 'P's . I just want one. Please help.

Your loop happens many times before you can release the button.
You need to check the state of the button and compare it to a previous state to differentiate between when the button just became pressed vs when it is being held down.

What you want is State Change Detection. See: File -> Examples -> 02.Digital -> StateChangeDetection

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.