Can't figure out how to get only one key press

Newbie here, so please be gentle!

I am programming an Adafruit Trinket to convert an analog signal from a momentary switch to a spacebar. I am almost there, except whenever I depress the analog button, I get a bunch of spaces. I'd like it to only produce one space with each push, and ideally not produce another until the button is released and depressed again. Here is my code - what am I missing? Thanks so much for anything you can tell me!

#include <TrinketKeyboard.h>

#define PIN_BUTTON_SPACE 0

void setup()
{

  pinMode(PIN_BUTTON_SPACE, INPUT_PULLUP);

  digitalWrite(PIN_BUTTON_SPACE, HIGH);

  TrinketKeyboard.begin();
}

void loop()
{

  TrinketKeyboard.poll();

  if (digitalRead(PIN_BUTTON_SPACE) == LOW)
  {
    TrinketKeyboard.pressKey(0, KEYCODE_SPACE);
    TrinketKeyboard.pressKey(0, 0);
  }
}

Welcome to the forum

You need to detect when the button becomes pressed rather than when it is pressed
See the StateChangeDetection example in the IDE

I feel you pain. The best thing for you to do is look at a few tutorials on debouncing inputs. Also there is a section on this in the Arduino Cookbook. There are a lot of solutions, pick one or two that you understand.

2 things... keep track of what the button value was in the previous loop, and look for changes from HIGH to LOW... like this:

#include <TrinketKeyboard.h>

#define PIN_BUTTON_SPACE 0

int prevVal = HIGH;
int currVal = HIGH;


void setup()
{

  pinMode(PIN_BUTTON_SPACE, INPUT_PULLUP);

  digitalWrite(PIN_BUTTON_SPACE, HIGH);

  TrinketKeyboard.begin();
}

void loop()
{
  
  TrinketKeyboard.poll();

  currVal = digitalRead(PIN_BUTTON_SPACE);

  if (currVal == LOW && prevVal == HIGH)
  {
    TrinketKeyboard.pressKey(0, KEYCODE_SPACE);
    TrinketKeyboard.pressKey(0, 0);
  }

  prevVal = currVal;
}

The other thing to worry about is button bounce... the easiest (not necessarily the best) way to handle that is to put a small delay (say 100ms) when you detect a key press.

Eureka! That gives me the exact functionality I was looking for. Many thanks!!!

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