Need some help with keyboard code

I’m currently making a 2 key keypad for myself with a pro micro. I’m trying to use the keyboard function to let it print out an ASCII code at the press of a button. Instead of writing 1 character, it writes a lot of them. What did I do wrong?


#include <Keyboard.h>

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(3,INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  if (digitalRead(2) == LOW) {
    Keyboard.write(122);
  if (digitalRead(3) == LOW)
    Keyboard.write(89);
  }
}



loop() repeats very quickly so your digitalRead()s repeat very quickly

You need to detect when an input goes LOW rather than when it is LOW

See the StateChangeDetection example in the IDE

Hi,
There is an error in the placement of the braces ({) and the ifs.

Use a lock to prevent key repetition.

example:

#include <Keyboard.h>

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  while (digitalRead(2) == LOW)
  {
    if (digitalRead(2) == HIGH)
      Keyboard.write(122);
  }

  while (digitalRead(3) == LOW)
  {
    if (digitalRead(3) == HIGH)
      Keyboard.write(89);
  }
}

RV mineirin

  while (digitalRead(2) == LOW)
  {
    if (digitalRead(2) == HIGH)
      Keyboard.write(122);
  }

will pin 2 ever be HIGH while pin 2 is LOW ?

UKHeliBob You are right,
now I wrote like this:

#include <Keyboard.h>

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  if (digitalRead(2) == LOW)
  {
    delay(30);
    if (digitalRead(2) == LOW)
    {
      Keyboard.write(122);
      while (digitalRead(2) == LOW) {}
    }
  }

  if (digitalRead(3) == LOW)
  {
    delay(30);
    if (digitalRead(3) == LOW)
    {
       Keyboard.write(89);
      while (digitalRead(3) == LOW) {}
    }
  }
}

Try this: