【问题标题】:Arduino When keep pressing button a continuous Letter is showArduino 当按住按钮时,会显示一个连续的字母
【发布时间】:2020-02-04 18:06:54
【问题描述】:

首先对不起我的英语不好

我有 Arduino Leonardo 我有一个按钮好吗?

当我单击按钮时,字母“W”会打印到记事本上 好吗?

我想要当我一直按住按钮时打印出 'w' 字母 为什么?就像在游戏中,当我按住“W”字母时,玩家会移动,然后当我松开手指时,玩家会停止。 请拜托,我需要你的帮助,因为我是初学者

这是我的代码

#include "Keyboard.h"

const int buttonPin = 4;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton

void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
}

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {
    // type out a message
    Keyboard.print("W");
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
} 

【问题讨论】:

标签: arduino arduino-uno arduino-c++


【解决方案1】:

首先,您的代码仅表现得好像按钮被按下一次的原因是以下几行

// if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {

所以,这只会在按下按钮后发生一次。如果您删除先前的状态检查,并且仅检查按钮当前是否为高电平,则每次程序循环时都会触发一次按下。不过这会有副作用,比如短按可能会触发多次。

幸运的是,键盘库提供了另一个函数来解决这个问题:Keyboard.press()

当被调用时,Keyboard.press() 的作用就像在您的键盘上按下并按住一个键。使用修饰键时很有用。要结束按键,请使用 Keyboard.release() 或 Keyboard.releaseAll()。 https://www.arduino.cc/reference/en/language/functions/usb/keyboard/keyboardpress/

所以,如果你像这样修改你的代码:

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);

  // if the button state has changed,
  if (buttonState != previousButtonState){
    if( buttonState == HIGH ) {
      Keyboard.press('w');
    }else{
      Keyboard.release('w');
    }
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

它的行为就像键盘按钮一直被按下一样。

请注意,由于弹跳,目前脚本可能会表现得好像每次按下按钮都会被按下几次。您可以通过在按钮按下和释放部分后添加一小段延迟来解决此问题。这将使按钮有时间适应新状态。在此处阅读有关弹跳的更多信息:https://www.allaboutcircuits.com/textbook/digital/chpt-4/contact-bounce/

【讨论】:

  • 我添加了你的循环,但是当我点击按钮时,字母“W”一直打印,直到我拔掉 Arduino 电源才能停止。
猜你喜欢
  • 2021-07-18
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多