用户工具

站点工具


ocrobot:alpha:kitone:tutorial12

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录前一修订版
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%>
 +如果你的按键工作后,通常你会需要基于按键按下多少次来做出反应。为了达到这个目的,你需要知道什么时候按键被打开或者关闭了,并且知道按键被按下的次数,这就是状态监测。
 +</WRAP>
 +
 +===== ALPHA MEGA328-U核心 =====
 +==== 硬件 ====
 +
 +  * [[ocrobot:alpha:parallelexpansion:index|ALPHA 并行扩展板]]
 +  * [[ocrobot:alpha:mega328-u:main|ALPHA MEGA328-U]]
 +  * [[ocrobot:alpha:microswitch:index|ALPHA 微动开关模块]]
 +
 +
 +==== 搭建电路 ====
 +
 +  - ALPHA MEGA328-U模块插入并行扩展板1号槽位。
 +  - ALPHA 微动开关模块插入并行扩展版2号槽位。
 +  - USB线连接计算机与ALPHA MEGA328-U。
 +{{ocrobot:alpha:kitone:按键435.png?nolink|}}
 +==== 代码 ====
 +
 +<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, INPUT);  // 初始化按键为输入:
 +  pinMode(ledPin, OUTPUT);  // 初始化LED为输出:
 +  Serial.begin(9600);  // 初始化串口通讯:
 +}
 +
 +void loop() {
 +  buttonState = digitalRead(buttonPin);  // 读取按键输入:
 +  if (buttonState != lastButtonState) { // 比较两次按键状态
 +    if (buttonState == HIGH) {    // 如果状态改变了增加计数器      // 如果当前的状态是high,按键就从关到开
 +      buttonPushCounter = buttonPushCounter + 1;
 +      Serial.println("on");
 +      Serial.print("number of button pushes:  ");
 +      Serial.println(buttonPushCounter);
 +    }
 +    else {
 +      Serial.println("off");   //如果当前的状态是low,按键就从开到关
 +    }
 +  }
 +  lastButtonState = buttonState;  // 保存当前的状态到上一次
 +  if (buttonPushCounter % 4 == 0) {  // 通过取模功能,每按4次键就点亮LED
 +    digitalWrite(ledPin, HIGH);
 +  } else {
 +    digitalWrite(ledPin, LOW);
 +  }
 +}
 +</code>
 +
 +[[ocrobot:alpha:kitone:main|返回上一级]]
ocrobot/alpha/kitone/tutorial12.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1