Sparkfun Pro Micro(ATMega32u4)作为USB键盘的控制器

时间:2016-06-03 19:50:02

标签: arduino keyboard usb avr atmega

我试图使用Sparkfun Pro Micro作为键盘的控制器。我无法实现普通键盘的行为。这是我的代码:

#include <Keyboard.h>

int firstButtonPin = 18, secondButtonPin = 19;
char firstButtonChar = 'z', secondButtonChar = 'x';
bool firstButtonPressed = false, secondButtonPressed = true;

void setup() {
  pinMode(firstButtonPin, INPUT);
  pinMode(secondButtonPin, INPUT);

  Keyboard.begin();
}

void loop() {
  if(digitalRead(firstButtonPin) == HIGH && firstButtonPressed == false) Keyboard.press(firstButtonChar), firstButtonPressed = true;
  else if(digitalRead(firstButtonPin) != HIGH && firstButtonPressed) Keyboard.release(firstButtonChar), firstButtonPressed = false;

  if(digitalRead(secondButtonPin) == HIGH && secondButtonPressed == false) Keyboard.press(secondButtonChar), secondButtonPressed = true;
  else if(digitalRead(secondButtonPin) != HIGH && secondButtonPressed) Keyboard.release(secondButtonChar), secondButtonPressed = false;
}

YT链接:https://youtu.be/VfHNOtq4HHo。 正如您所看到的,普通键盘输出一个键,一段时间后它就会发送垃圾邮件。当我切换AVR时,我总是收到垃圾邮件(看起来这些按键没有固定,只是在很短的时间内按下并释放。我怎样才能实现真正的键盘行为?我想用它在奥苏等游戏中!我希望你能帮助我。提前致谢

2 个答案:

答案 0 :(得分:0)

问题是按钮弹跳。

答案 1 :(得分:0)

u可以使用millis()处理反跳。

uint32_t time = millis(); //must be 32 bit or greater
uint8_t debounceTime = 50 //this is in milli seconds
void loop() {
    if (millis() - time > debounceTime) {

        //put your if-else-if code here (for keypress and release)
        time = millis();
    }
}

您可以使用debounceTime。对于大多数按钮,只需50毫秒即可。但是如果您使用的是键盘开关(例如Cherry mx,gateron等),则可以低至5毫秒