这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录前一修订版 | |||
ocrobot:alpha:kitone:tutorial12 [2019/07/15 02:32] – 董凯萍 | ocrobot:alpha:kitone:tutorial12 [2023/06/07 04:23] (当前版本) – 外部编辑 127.0.0.1 | ||
---|---|---|---|
行 1: | 行 1: | ||
+ | ~~NOTOC~~ | ||
+ | ====== Button State Change Detection (监测按键状态改变) ====== | ||
+ | <WRAP left round info 100%> | ||
+ | 如果你的按键工作后,通常你会需要基于按键按下多少次来做出反应。为了达到这个目的,你需要知道什么时候按键被打开或者关闭了,并且知道按键被按下的次数,这就是状态监测。 | ||
+ | </ | ||
+ | |||
+ | ===== ALPHA MEGA328-U核心 ===== | ||
+ | ==== 硬件 ==== | ||
+ | |||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | |||
+ | |||
+ | ==== 搭建电路 ==== | ||
+ | |||
+ | - ALPHA MEGA328-U模块插入并行扩展板1号槽位。 | ||
+ | - ALPHA 微动开关模块插入并行扩展版2号槽位。 | ||
+ | - USB线连接计算机与ALPHA MEGA328-U。 | ||
+ | {{ocrobot: | ||
+ | ==== 代码 ==== | ||
+ | |||
+ | <code cpp> | ||
+ | /* | ||
+ | State change detection (edge detection) | ||
+ | 通常你不需要一直知道数字输入的状态,但是你需要哪个时候知道输入状态改变了。 | ||
+ | 这个例子显示了怎么检测按键状态的改变 | ||
+ | */ | ||
+ | const int buttonPin = 15; // 按键连接的引脚 | ||
+ | const int ledPin = 2; // LED连接的引脚 | ||
+ | int buttonPushCounter = 0; // 按键按下次数的计数器 | ||
+ | int buttonState = 0; // 当前按键状态 | ||
+ | int lastButtonState = 0; // 前一次按键状态 | ||
+ | |||
+ | void setup() { | ||
+ | pinMode(buttonPin, | ||
+ | pinMode(ledPin, | ||
+ | Serial.begin(9600); | ||
+ | } | ||
+ | |||
+ | void loop() { | ||
+ | buttonState = digitalRead(buttonPin); | ||
+ | if (buttonState != lastButtonState) { // 比较两次按键状态 | ||
+ | if (buttonState == HIGH) { // 如果状态改变了增加计数器 | ||
+ | buttonPushCounter = buttonPushCounter + 1; | ||
+ | Serial.println(" | ||
+ | Serial.print(" | ||
+ | Serial.println(buttonPushCounter); | ||
+ | } | ||
+ | else { | ||
+ | Serial.println(" | ||
+ | } | ||
+ | } | ||
+ | lastButtonState = buttonState; | ||
+ | if (buttonPushCounter % 4 == 0) { // 通过取模功能,每按4次键就点亮LED | ||
+ | digitalWrite(ledPin, | ||
+ | } else { | ||
+ | digitalWrite(ledPin, | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | [[ocrobot: |