硬件平台:PC机一台,ibox卡片电脑一只,arduino扩展板一个 软件平台:WIN7操作系统,android4.0或android4.4系统 实验目标:通过ibox中间的按键控制LED1的亮灭,要求每按四次按键,LED灯亮一次,如此反复循环。 打开arduino的IDE开发工具,依次点击文件->示例->02.Digital-> StateChangeDetection,StateChangeDetection的示例程序将会被打开,其源码如下: - // this constant won't change:
- const int buttonPin = KEY0; // the pin that the pushbutton is attached to 24(KEY0)
- const int ledPin = LED1; // the pin that the LED is attached to 22(LED1)
-
- // Variables will change:
- int buttonPushCounter = 0; // counter for the number of button presses
- int buttonState = 0; // current state of the button
- int lastButtonState = 0; // previous state of the button
-
- void setup() {
- // initialize the button pin as a input:
- pinMode(buttonPin, INPUT);
- // initialize the LED as an output:
- pinMode(ledPin, OUTPUT);
- // initialize serial communication:
- Serial.begin(9600);
- }
-
- void loop() {
- // read the pushbutton input pin:
- buttonState = digitalRead(buttonPin);
-
- // compare the buttonState to its previous state
- if (buttonState != lastButtonState) {
- // if the state has changed, increment the counter
- if (buttonState == LOW) {
- // if the current state is HIGH then the button
- // wend from off to on:
- buttonPushCounter++;
- Serial.println("on");
- Serial.print("number of button pushes: ");
- Serial.println(buttonPushCounter);
- }
- else {
- // if the current state is HIGH then the button
- // wend from on to off:
- Serial.println("off");
- }
- // Delay a little bit to avoid bouncing
- delay(50);
- }
- // save the current state as the last state,
- //for next time through the loop
- lastButtonState = buttonState;
- // turns on the LED every four button pushes by
- // checking the modulo of the button push counter.
- // the modulo function gives you the remainder of
- // the division of two numbers:
- if (buttonPushCounter % 4 == 0) {
- digitalWrite(ledPin, HIGH);
- } else {
- digitalWrite(ledPin, LOW);
- }
- }
复制代码 首先在setup函数中将按键IO设置为输入,LED控制IO设置为输出,然后在loop函数中读取按键状态,每当按键从高到低变化一次,则buttonPushCounter加1,如果buttonPushCounter能够被4整除,说明已经按了四次,则将LED灯点亮,否则关闭LED灯,从而实现预期的效果。
|