九鼎创展论坛中文版English
登录 | 立即注册 设为首页收藏本站 切换到宽版
查看: 5277|回复: 0
打印 上一主题 下一主题

arduino ibox项目实战14-按键控制LED灯实验(二)

[复制链接]
跳转到指定楼层
楼主
发表于 2014-10-25 18:58:28 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
硬件平台:PC机一台,ibox卡片电脑一只,arduino扩展板一个
软件平台:WIN7操作系统,android4.0android4.4系统
打开arduino的IDE开发工具,依次点击文件->示例->01.Basics->Debounce,Debounce的示例程序将会被打开,其源码如下:
  1. // constants won't change. They're used here to
  2. // set pin numbers:
  3. const int buttonPin = KEY0;    // the number of the pushbutton pin 24(KEY0)
  4. const int ledPin = LED1;      // the number of the LED pin 22(LED1)

  5. // Variables will change:
  6. int ledState = HIGH;         // the current state of the output pin
  7. int buttonState;             // the current reading from the input pin
  8. int lastButtonState = LOW;   // the previous reading from the input pin

  9. // the following variables are long's because the time, measured in miliseconds,
  10. // will quickly become a bigger number than can be stored in an int.
  11. long lastDebounceTime = 0;  // the last time the output pin was toggled
  12. long debounceDelay = 50;    // the debounce time; increase if the output flickers

  13. void setup() {
  14.   pinMode(buttonPin, INPUT);
  15.   pinMode(ledPin, OUTPUT);

  16.   // set initial LED state
  17.   digitalWrite(ledPin, ledState);
  18. }

  19. void loop() {
  20.   // read the state of the switch into a local variable:
  21.   int reading = digitalRead(buttonPin);

  22.   // check to see if you just pressed the button
  23.   // (i.e. the input went from LOW to HIGH),  and you've waited
  24.   // long enough since the last press to ignore any noise:

  25.   // If the switch changed, due to noise or pressing:
  26.   if (reading != lastButtonState) {
  27.     // reset the debouncing timer
  28.     lastDebounceTime = millis();
  29.   }

  30.   if ((millis() - lastDebounceTime) > debounceDelay) {
  31.     // whatever the reading is at, it's been there for longer
  32.     // than the debounce delay, so take it as the actual current state:

  33.     // if the button state has changed:
  34.     if (reading != buttonState) {
  35.       buttonState = reading;

  36.       // only toggle the LED if the new button state is HIGH
  37.       if (buttonState == HIGH) {
  38.         ledState = !ledState;
  39.       }
  40.     }
  41.   }

  42.   // set the LED:
  43.   digitalWrite(ledPin, ledState);

  44.   // save the reading.  Next time through the loop,
  45.   // it'll be the lastButtonState:
  46.   lastButtonState = reading;
  47. }
复制代码
本程序将会采集按键数据,每按一次,将会对ledState取反一次。因此,按按一下ibox上中间的按钮,LED灯状态会变一次。注意,程序中两次通过if语句判断按键的状态,是用于消除按键抖动。否则,每按一次按键时,LED灯将会不断的开关数次,最终灯的状态也是未知的。

回复

使用道具 举报

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

本版积分规则

QQ|手机版|小黑屋|深圳市九鼎创展科技官方论坛 ( 粤ICP备11028681号-2  

GMT+8, 2024-11-22 22:27 , Processed in 0.019842 second(s), 19 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

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