Arduino OneButton Library

此库展示了如何通过检测一些典型的按钮按下事件(如单击、双击和长时间按下按钮)来使用输入引脚。能够将同一按钮重用于多种功能,并降低硬件投资。

下载项目文件

可以使用git从github下载OneButton库,或者将最新版本下载为zip文件
(右侧按钮标记为“下载ZIP”),
https://github.com/mathertel/OneButton

介绍

从 Arduino 编程开始,您肯定会遇到简单的 Button 教程,了解如何从按钮读取数据,以及 Debounce 示例,该示例展示了如何通过消除接触抖动产生的短时间开/关序列从按钮获得清晰的信号。

在不阻塞程序的情况下读取按钮

上面提到的简单示例的一个缺点是,它们使用 loop() 函数,因此很难重用它们包含的代码。

我预计你的草图将不得不做更复杂的事情,并且你需要 loop() 函数来实现你自己的目的。因此,库和可重用代码的常见要求是避免实现此功能。相反,应该经常调用库的 tick() 函数。在此功能中,您将找到用于检测所有3个可用事件的编码。

对于任何已实现的事件,可以注册一个函数以将代码链接到库。然后,当检测到相应的情况时,将调用您的函数。

使用 OneButton 库的示例
下面是一个简单的示例,当双击引脚 A1 上连接的按钮时,使用 OneButton 库更改引脚 13 上的默认 LED。

#include "OneButton.h"

// Setup a new OneButton on pin A1.  
OneButton button(A1);


// setup code here, to run once:
void setup() {
  // enable the standard led on pin 13.
  pinMode(13, OUTPUT);      // sets the digital pin as output
  
  // link the doubleclick function to be called on a doubleclick event.   
  button.attachDoubleClick(doubleclick);
} // setup
  

// main code here, to run repeatedly: 
void loop() {
  // keep watching the push button:
  button.tick();

  // You can implement other code in here or just wait a while 
  delay(10);
} // loop


// this function will be called when the button was pressed 2 times in a short timeframe.
void doubleclick() {
  static int m = LOW;
  // reverse the LED 
  m = !m;
  digitalWrite(13, m);
} // doubleclick

另请阅读内联注释。您可以在那里看到双击功能如何附加到第二次释放按钮的情况。

实现细节

在 tick() 函数的 OneButton 库中,您可以找到用于检查输入引脚的实现,以检测单击、双击或长按情况。这种实现称为有限状态机 (FSM).

每次调用 tick() 函数时,都会分析当前状态和输入值,并在适用时调用外部函数和/或更改当前状态。特别是OneButton库实现从不调用delay()或类似的函数,因此在大多数情况下会快速返回。

来源:http://www.mathertel.de/Arduino/OneButtonLibrary.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值