极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 21485|回复: 1

按键消 抖动 含单按 和 长按两种状态

[复制链接]
发表于 2019-7-4 10:29:11 | 显示全部楼层 |阅读模式

单独按一次按钮  启动一组动作   长时间按 启动另一组动作  


  1. const int buttonPin = 11;    // the number of the pushbutton pin
  2. const int ledPin = 13;      // the number of the LED pin
  3. int ledState = HIGH;         // the current state of the output pin
  4. int buttonState;             // the current reading from the input pin
  5. int lastButtonState = HIGH;   // the previous reading from the input pin
  6. long lastDebounceTime = 0;  // the last time the output pin was toggled
  7. long debounceDelay = 50;    // the debounce time; increase if the output flickers
  8. long debounceDelay2 = 1050;    // the debounce time; increase if the output flickers
  9. int ttt;   
  10. void setup() {
  11.   pinMode(buttonPin, INPUT_PULLUP);
  12.   pinMode(ledPin, OUTPUT);
  13.   digitalWrite(ledPin, ledState);
  14.   Serial.begin(9600);
  15. }
  16. void loop() {
  17.   int reading = digitalRead(buttonPin);//读取按键电平高低
  18.   if (reading != lastButtonState) {    //如果电瓶如之前翻转了.说明按键状态改变.
  19.     lastDebounceTime = millis();        //记录翻转时候的时间
  20. //     Serial.println("1111");
  21.   }
  22.   
  23.   if ((millis() - lastDebounceTime) > debounceDelay)
  24.   {  

  25.     if (reading != buttonState) {
  26.       buttonState = reading;
  27.       if (buttonState == LOW) {
  28.         ledState = !ledState;
  29.         ttt++;
  30.         Serial.println(ttt);
  31.       }
  32.     }
  33.   }
  34.   if ((millis() - lastDebounceTime) > debounceDelay2)  
  35.   {  
  36.       if (reading == LOW) {
  37.         Serial.println(ttt);
  38.     }
  39.   }
  40.    
  41.   digitalWrite(ledPin, ledState);
  42.   lastButtonState = reading;
  43. }
复制代码
回复

使用道具 举报

发表于 2020-3-11 12:22:11 | 显示全部楼层
显示编译有误
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-23 14:56 , Processed in 0.051060 second(s), 18 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表