基于LinkIt one的Arduino编程学习-按键操作

根据Arduino官方的例子实现的:

const int PIN_KEY_CARD   = 2;
const int PIN_KEY_RETURN = 3;

// LinkIt one SDK没有实现该方法,这里需要手动实现
int digitalPinToInterrupt(int pin) {
  int num = -1;
  switch(pin) {
     case PIN_KEY_CARD:
       num = 0;
       break;
     case PIN_KEY_RETURN:
       num = 1;
       break;
  }
  return num;
}

void setup() {
  Serial.begin(9600);
  pinMode(PIN_KEY_CARD, INPUT_PULLUP);
  pinMode(PIN_KEY_RETURN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_KEY_CARD), onCardKeyEvent, FALLING);//当int.0电平改变时,触发中断函数blink
  attachInterrupt(digitalPinToInterrupt(PIN_KEY_RETURN), onReturnKeyEvent, FALLING);//当int.0电平改变时,触发中断函数blink
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("...");
  delay(1000 * 1);
}
void onCardKeyEvent() {
  Serial.println("onCardKeyEvent");
}

void onReturnKeyEvent() {
  Serial.println("onReturnKeyEvent");
}

这种实现没有考虑到消除按键的硬件抖动即消抖,会出现这种情况:
(后补图)

根据消抖的英文关键词Debounce,搜索到已经有库实现了软件消抖,名字叫Bounce2。链接地址:


// Detect the falling edge

// Include the Bounce2 library found here :
// https://github.com/thomasfredericks/Bounce-Arduino-Wiring
#include <Bounce2.h>

// Instantiate a Bounce object :
Bounce debouncer1 = Bounce(); 
// Instantiate a Bounce object :
Bounce debouncer2 = Bounce(); 

const int PIN_KEY_CARD   = 2;
const int PIN_KEY_RETURN = 3;

void setup() {
  Serial.begin(9600);
  pinMode(PIN_KEY_CARD, INPUT_PULLUP);
  pinMode(PIN_KEY_RETURN, INPUT_PULLUP);
  // After setting up the button, setup the Bounce instance :
  debouncer1.attach(PIN_KEY_CARD);
  debouncer1.interval(50); // interval in ms
  // After setting up the button, setup the Bounce instance :
  debouncer2.attach(PIN_KEY_RETURN);
  debouncer2.interval(50); // interval in ms
}

void loop() {
//  Serial.println("loop");
  // Update the Bounce instance :
   debouncer1.update();
   debouncer2.update();

   // Call code if Bounce fell (transition from HIGH to LOW) :
   if ( debouncer1.fell() ) {
      Serial.println("debouncer1");
   }
      // Call code if Bounce fell (transition from HIGH to LOW) :
   if ( debouncer2.fell() ) {
      Serial.println("debouncer2");
   }
}
void onCardKeyEvent() {
  Serial.println("onCardKeyEvent");
  delay(50); // 50ms works for most switches - adjustable
}

void onReturnKeyEvent() {
  Serial.println("onReturnKeyEvent");
  delay(50); // 50ms works for most switches - adjustable
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁保康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值