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

arduino ibox项目实战15-按键状态检测实验

[复制链接]
跳转到指定楼层
楼主
发表于 2014-10-25 19:09:42 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
硬件平台:PC机一台,ibox卡片电脑一只,arduino扩展板一个
软件平台:WIN7操作系统,android4.0android4.4系统
实验目标:通过ibox中间的按键控制LED1的亮灭,要求每按四次按键,LED灯亮一次,如此反复循环。
打开arduino的IDE开发工具,依次点击文件->示例->02.Digital-> StateChangeDetection,StateChangeDetection的示例程序将会被打开,其源码如下:
  1. // this constant won't change:
  2. const int  buttonPin = KEY0;    // the pin that the pushbutton is attached to 24(KEY0)
  3. const int ledPin = LED1;       // the pin that the LED is attached to 22(LED1)

  4. // Variables will change:
  5. int buttonPushCounter = 0;   // counter for the number of button presses
  6. int buttonState = 0;         // current state of the button
  7. int lastButtonState = 0;     // previous state of the button

  8. void setup() {
  9.   // initialize the button pin as a input:
  10.   pinMode(buttonPin, INPUT);
  11.   // initialize the LED as an output:
  12.   pinMode(ledPin, OUTPUT);
  13.   // initialize serial communication:
  14.   Serial.begin(9600);
  15. }

  16. void loop() {
  17.   // read the pushbutton input pin:
  18.   buttonState = digitalRead(buttonPin);

  19.   // compare the buttonState to its previous state
  20.   if (buttonState != lastButtonState) {
  21.     // if the state has changed, increment the counter
  22.     if (buttonState == LOW) {
  23.       // if the current state is HIGH then the button
  24.       // wend from off to on:
  25.       buttonPushCounter++;
  26.       Serial.println("on");
  27.       Serial.print("number of button pushes:  ");
  28.       Serial.println(buttonPushCounter);
  29.     }
  30.     else {
  31.       // if the current state is HIGH then the button
  32.       // wend from on to off:
  33.       Serial.println("off");
  34.     }
  35.     // Delay a little bit to avoid bouncing
  36.     delay(50);
  37.   }
  38.   // save the current state as the last state,
  39.   //for next time through the loop
  40.   lastButtonState = buttonState;
  41.   // turns on the LED every four button pushes by
  42.   // checking the modulo of the button push counter.
  43.   // the modulo function gives you the remainder of
  44.   // the division of two numbers:
  45.   if (buttonPushCounter % 4 == 0) {
  46.     digitalWrite(ledPin, HIGH);
  47.   } else {
  48.     digitalWrite(ledPin, LOW);
  49.   }
  50. }
复制代码
       首先在setup函数中将按键IO设置为输入,LED控制IO设置为输出,然后在loop函数中读取按键状态,每当按键从高到低变化一次,则buttonPushCounter1,如果buttonPushCounter能够被4整除,说明已经按了四次,则将LED灯点亮,否则关闭LED灯,从而实现预期的效果。

回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-11-23 17:16 , Processed in 0.019298 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

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