Arduino环境下ESP8266使用[OneButton]库

OneButton介绍

[OneButton]库,是用于检测单个按钮上的按钮点击、双击和长按模式的库。这个库是在Arduino环境使用而实现的。。

OneButton.h 文件内容

具体的内置方法可以参见:OneButton.h 文件内容:

// -----
// OneButton.h - Library for detecting button clicks, doubleclicks and long
// press pattern on a single button. This class is implemented for use with the
// Arduino environment. Copyright (c) by Matthias Hertel,
// http://www.mathertel.de This work is licensed under a BSD style license. See
// http://www.mathertel.de/License.aspx More information on:
// http://www.mathertel.de/Arduino
// -----
// 02.10.2010 created by Matthias Hertel
// 21.04.2011 transformed into a library
// 01.12.2011 include file changed to work with the Arduino 1.0 environment
// 23.03.2014 Enhanced long press functionalities by adding longPressStart and
// longPressStop callbacks
// 21.09.2015 A simple way for debounce detection added.
// 14.05.2017 Debouncing improvements.
// 25.06.2018 Optional third parameter for deactivating pullup.
// 26.09.2018 Anatoli Arkhipenko: Included solution to use library with other
// sources of input.
// 26.09.2018 Initialization moved into class declaration.
// 26.09.2018 Jay M Ericsson: compiler warnings removed.
// 29.01.2020 improvements from ShaggyDog18
// -----

#ifndef OneButton_h
#define OneButton_h

#include "Arduino.h"

// ----- Callback function types -----

extern "C" {
typedef void (*callbackFunction)(void);
typedef void (*parameterizedCallbackFunction)(void *);
}


class OneButton
{
public:
  // ----- Constructor -----
  OneButton();

  /**
   * Initialize the OneButton library.
   * @param pin The pin to be used for input from a momentary button.
   * @param activeLow Set to true when the input level is LOW when the button is pressed, Default is true.
   * @param pullupActive Activate the internal pullup when available. Default is true.
   */
  OneButton(const int pin, const boolean activeLow = true, const bool pullupActive = true);

  // ----- Set runtime parameters -----

  /**
   * set # millisec after safe click is assumed.
   */
  void setDebounceTicks(const int ticks);

  /**
   * set # millisec after single click is assumed.
   */
  void setClickTicks(const int ticks);

  /**
   * set # millisec after press is assumed.
   */
  void setPressTicks(const int ticks);

  /**
   * Attach an event to be called when a single click is detected.
   * @param newFunction This function will be called when the event has been detected.
   */
  void attachClick(callbackFunction newFunction);
  void attachClick(parameterizedCallbackFunction newFunction, void *parameter);

  /**
   * Attach an event to be called after a double click is detected.
   * @param newFunction This function will be called when the event has been detected.
   */
  void attachDoubleClick(callbackFunction newFunction);
  void attachDoubleClick(parameterizedCallbackFunction newFunction, void *parameter);

  /**
   * Attach an event to be called after a multi click is detected.
   * @param newFunction This function will be called when the event has been detected.
   */
  void attachMultiClick(callbackFunction newFunction);
  void attachMultiClick(parameterizedCallbackFunction newFunction, void *parameter);

  /**
   * Attach an event to fire when the button is pressed and held down.
   * @param newFunction
   */
  void attachLongPressStart(callbackFunction newFunction);
  void attachLongPressStart(parameterizedCallbackFunction newFunction, void *parameter);

  /**
   * Attach an event to fire as soon as the button is released after a long press.
   * @param newFunction
   */
  void attachLongPressStop(callbackFunction newFunction);
  void attachLongPressStop(parameterizedCallbackFunction newFunction, void *parameter);

  /**
   * Attach an event to fire periodically while the button is held down.
   * @param newFunction
   */
  void attachDuringLongPress(callbackFunction newFunction);
  void attachDuringLongPress(parameterizedCallbackFunction newFunction, void *parameter);

  // ----- State machine functions -----

  /**
   * @brief Call this function every some milliseconds for checking the input
   * level at the initialized digital pin.
   */
  void tick(void);


  /**
   * @brief Call this function every time the input level has changed.
   * Using this function no digital input pin is checked because the current
   * level is given by the parameter.
   */
  void tick(bool level);


  /**
   * Reset the button state machine.
   */
  void reset(void);


  /*
   * return number of clicks in any case: single or multiple clicks
   */
  int getNumberClicks(void);


  /**
   * @return true if we are currently handling button press flow
   * (This allows power sensitive applications to know when it is safe to power down the main CPU)
   */
  bool isIdle() const { return _state == OCS_INIT; }

  /**
   * @return true when a long press is detected
   */
  bool isLongPressed() const { return _state == OCS_PRESS; };


private:
  int _pin;                         // hardware pin number.
  unsigned int _debounceTicks = 50; // number of ticks for debounce times.
  unsigned int _clickTicks = 400;   // number of msecs before a click is detected.
  unsigned int _pressTicks = 800;   // number of msecs before a long button press is detected

  int _buttonPressed;

  // These variables will hold functions acting as event source.
  callbackFunction _clickFunc = NULL;
  parameterizedCallbackFunction _paramClickFunc = NULL;
  void *_clickFuncParam = NULL;

  callbackFunction _doubleClickFunc = NULL;
  parameterizedCallbackFunction _paramDoubleClickFunc = NULL;
  void *_doubleClickFuncParam = NULL;

  callbackFunction _multiClickFunc = NULL;
  parameterizedCallbackFunction _paramMultiClickFunc = NULL;
  void *_multiClickFuncParam = NULL;

  callbackFunction _longPressStartFunc = NULL;
  parameterizedCallbackFunction _paramLongPressStartFunc = NULL;
  void *_longPressStartFuncParam = NULL;

  callbackFunction _longPressStopFunc = NULL;
  parameterizedCallbackFunction _paramLongPressStopFunc = NULL;
  void *_longPressStopFuncParam;

  callbackFunction _duringLongPressFunc = NULL;
  parameterizedCallbackFunction _paramDuringLongPressFunc = NULL;
  void *_duringLongPressFuncParam = NULL;

  // These variables that hold information across the upcoming tick calls.
  // They are initialized once on program start and are updated every time the
  // tick function is called.

  // define FiniteStateMachine
  enum stateMachine_t : int {
    OCS_INIT = 0,
    OCS_DOWN = 1,
    OCS_UP = 2,
    OCS_COUNT = 3,
    OCS_PRESS = 6,
    OCS_PRESSEND = 7,
    UNKNOWN = 99
  };

  /**
   *  Advance to a new state and save the last one to come back in cas of bouncing detection.
   */
  void _newState(stateMachine_t nextState);

  stateMachine_t _state = OCS_INIT;
  stateMachine_t _lastState = OCS_INIT; // used for debouncing

  unsigned long _startTime; // start of current input change to checking debouncing
  int _nClicks;             // count the number of clicks with this variable
  int _maxClicks = 1;       // max number (1, 2, multi=3) of clicks of interest by registration of event functions.
};

#endif

下面是示例程序:

//接线说明:
//1、在ESP8266 GPIO 0引脚上接一点触按钮,,按钮另一端接GND。即,按钮按下时GPIO 0引脚为低电平。
//2、编译烧写程序。
//3、打开串口监视器或串口调试助手。
//4、分别按下1次、2次、3次、4次、5次、6次、7次、8次、长按。
//5、观察串口输出状态。

#define BUTTON_PIN 0 //将按钮引脚绑定到GPIO 0
#include <Arduino.h>
#include "OneButton.h"//引用库函数

//函数原形: OneButton(const int pin, const boolean activeLow = true, const bool pullupActive = true);
              /**
               * Initialize the OneButton library.
               * @param pin The pin to be used for input from a momentary button.
               * @param activeLow Set to true when the input level is LOW when the button is pressed, Default is true.
               * @param pullupActive Activate the internal pullup when available. Default is true.
               */
OneButton button(BUTTON_PIN,true);//
        //实例化一个OneButton对象
        //里面可以传三个参数:
        //pin : 按钮的pin角
        //activeLow : true:按下为低电平; false : 按下为高电平;不设置时默认值为:true
        //pullupActive : 如果有上拉电阻就激活上拉电阻

//按键事件回调函数
//单击
void attachClick()
{
  	Serial.println("click-单击");
}

//双击
void attachDoubleClick()
{
  	Serial.println("doubleclick-双击");
}

//长铵开始
void attachLongPressStart()
{
    Serial.println("longPressStart-长按开始");
}
//长按过程
void attachDuringLongPress()
{
  if (button.isLongPressed())
  {
    	Serial.println("duringLongPress-长按期间");
  }
}

//长按结束
void attachLongPressStop()
{
    Serial.println("longPressStop-长按结束");
}

//按下多次
void attachMultiClick()
{
  Serial.printf("getNumberClicks-总共按了:%d次。\r\n",button.getNumberClicks());
  switch(button.getNumberClicks()){
    	case 3:{Serial.printf("switch语句判断出打印3次。\r\n");break;}
    	case 4:{Serial.printf("switch语句判断出打印4次。\r\n");break;}
    	case 5:{Serial.printf("switch语句判断出打印5次。\r\n");break;}
    	case 6:{Serial.printf("switch语句判断出打印6次。\r\n");break;}
    	default:{Serial.printf("switch语句判断出打印其它次数:[%d]。\r\n",button.getNumberClicks());break;}
  
  
  }
}

//回调函数绑定子程序
void button_event_init(){

  button.reset();//清除一下按钮状态机的状态
   /**
   * set # millisec after safe click is assumed.
   */
  //void setDebounceTicks(const int ticks);
  button.setDebounceTicks(80);//设置消抖时长为80毫秒,默认值为:50毫秒

  /**
   * set # millisec after single click is assumed.
   */
  //void setClickTicks(const int ticks);
  button.setClickTicks(500);//设置单击时长为500毫秒,默认值为:400毫秒

  /**
   * set # millisec after press is assumed.
   */
  //void setPressTicks(const int ticks);
  button.setPressTicks(1000);设置长按时长为1000毫秒,默认值为:800毫秒
  
  button.attachClick(attachClick);//初始化单击回调函数
  button.attachDoubleClick(attachDoubleClick);//初始化双击回调函数
  button.attachLongPressStart(attachLongPressStart);//初始化长按开始回调函数
  button.attachDuringLongPress(attachDuringLongPress);//初始化长按期间回调函数
  button.attachLongPressStop(attachLongPressStop);//初始化长按结束回调函数
  button.attachMultiClick(attachMultiClick);//初始化按了多次(3次或以上)回调函数
}

//按钮检测状态子程序
void button_attach_loop(){
    //不断检测按钮按下状态
    button.tick();
}

void setup() {
    Serial.begin(115200);//初始化串口波特率为115200
    button_event_init();//按钮事件初始化

}

void loop() {
    //不断检测按钮按下状态
    button_attach_loop();
    
}

接线说明
  • 1、在ESP8266 GPIO 0引脚上接一点触按钮,,按钮另一端接GND。即,按钮按下时GPIO 0引脚为低电平。
  • 2、编译烧写程序。
  • 3、打开串口监视器或串口调试助手。
  • 4、分别按下1次、2次、3次、4次、5次、6次、7次、8次、长按。
  • 5、观察串口输出状态。
调试截图

在这里插入图片描述

库文件下载

下载页面链接:https://www.arduinolibraries.info/libraries/one-button
当前示例使用版本:OneButton-2.0.1.zip
示例匹配版本下载链接:https://downloads.arduino.cc/libraries/github.com/mathertel/OneButton-2.0.1.zip

  • 8
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值