Button press to keyboard input

I'm trying to have a button press input a keystroke. I'm using the MKR Zero board, and it is not currently working properly. The LED lights up when the button is pressed, but no keystroke is inputted. Eventually, I plan on integrating flex sensors as an additional prerequisite for the input later down the road, but I feel like I should pass this hurdle first.

#include <Keyboard.h>

const int buttonPin = 6;
int buttonState = 0;
int prevButtonState = LOW;
int LEDGre = 8;


void setup()
{
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(LEDGre, OUTPUT);
  digitalWrite(buttonPin,HIGH);
  Keyboard.begin();
  Serial.begin(9600);
}


void loop()
{
  buttonState = digitalRead(buttonPin);
  Serial.print(buttonState);
  Keyboard.begin();

  if((buttonState != prevButtonState) && (buttonState == HIGH))
  {
    Keyboard.press('C');
    digitalWrite(LEDGre,HIGH);

  }
  else if((buttonState != prevButtonState) && (buttonState == LOW))
  {
    delay(100);
    Keyboard.releaseAll();
    digitalWrite(LEDGre,LOW);
  }
  prevButtonState = buttonState;
}


Keyboard.begin();

Do this once in setup(), not repeatedly in loop()

As to your code, because buttonPin is set to use INPUT_PULLUP its state will be HIGH unless the button is pressed, assuming that your circuit takes the pin LOW when the button is pressed.

Assuming that you want to send 'c' when the button is pressed is the logic of your sketch correct ?

I changed the placement of Keyboard.begin() to setup(), and changed INPUT_PULLUP to just INPUT, but I'm receiving the same results. The logic makes sense to me, but I'm completely new to c++ and have been mashing together what I've researched from the Arduino reference pages.

Please explain the sequence of events that you want

What should happen whilst the button is not pressed ?
What should happen when the button is pressed ?

You are using INPUT_PULLUP so why is there a resistor connected to the pushbutton ?

Please post your sketch as it is now

So, I tried it on a different computer, and it works. Could be a driver issue on my end.

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