案例一:编写程序,实现每次按下按键,红色LED灯改变状态(初始点亮),在窗口监视窗中显示按击次数。[要求用计时器实现按键消抖]
#include"Timer.h" //包含计时器头文件volatile int state=HIGH; //灯的状态 volatile int flag=LOW; //按键按下的标志int curButtonState=HIGH; //当前按键状态 int lastButtonState=HIGH; //上一按键状态 int count=0;void setup() {// put your setup code here, to run once:Serial.begin(9600);pinMode(RED_LED,OUTPUT);digitalWrite(RED_LED,state); //初始灯亮pinMode(PUSH2,INPUT_PULLUP); SetTimer(isrTimer,20); //用于按键消抖 }void loop() {if(flag){flag=LOW;digitalWrite(RED_LED,state);count++;Serial.println(count);}}void isrTimer() {//读取按键状态curButtonState=digitalRead(PUSH2);if(curButtonState!=lastButtonState){//按键按下时,在主程序中改变灯的状态if(curButtonState==LOW){state=!state;flag=HIGH;}}lastButtonState=curButtonState; //更新按键状态 }
案例2:
//版本一:使用delay
缺点:无法实现快速切换至新的闪烁周期,堵塞式编程
#include "Timer.h"volatile int Period=2000; //初始闪烁周期为4s
//volatile flag=LOW; //ISR标志
int buttonState=HIGH; //当前按键状态
int LastButtonState=HIGH; //上一按键状态void setup() {// put your setup code here, to run once:pinMode(RED_LED,OUTPUT);pinMode(PUSH2,INPUT_PULLUP);SetTimer(isrTimer,20);
}void loop() {// put your main code here, to run repeatedly:digitalWrite(RED_LED,HIGH);delay(Period);digitalWrite(RED_LED,LOW);delay(Period);
}void isrTimer()
{buttonState=digitalRead(PUSH2);if(buttonState!=LastButtonState){if(buttonState=LOW){Period=100; //修改闪烁周期//flag=HIGH;}else{Period=2000;}}buttonState=LastButtonState;
}
//版本二: 创建计时器,实现即时切换灯的闪烁状态(周期开始灯亮)
#include "Timer.h"int buttonState=HIGH; //当前按键状态
int LastButtonState=HIGH; //上一按键状态//clock:用硬件计时器实现的软件计时器
int clock_MAX = 100;int clock_Times= 0;
volatile int clock_flag=LOW;int state=HIGH; //LED灯的状态void setup() {// put your setup code here, to run once:pinMode(RED_LED,OUTPUT);digitalWrite(RED_LED,state);pinMode(PUSH2,INPUT_PULLUP);SetTimer(isrTimer,20);
}void loop() {// put your main code here, to run repeatedly:if(clock_flag){clock_flag=LOW;state=!state;digitalWrite(RED_LED,state);}}void isrTimer()
{
//定时器功能实现
if(++clock_Times>=clock_MAX)
{clock_Times=0;clock_flag=HIGH;
}//判断按键状态buttonState=digitalRead(PUSH2);if(buttonState!=LastButtonState){if(buttonState==LOW){clock_MAX=5;clock_Times=0;clock_flag=HIGH;state=LOW;}else{clock_MAX=100;clock_Times=0;clock_flag=HIGH;state=LOW;}}LastButtonState=buttonState;
}