1、定时器中断方式
#define LONG_PRESS 100 // 20ms*100=2s,
#define SHORT_PRESS 5 // 20ms*5=100ms,
InterruptIn btn(USER_BUTTON);
int btn_now = 0;
int btn_last = 0;
bool btn_long = false;
bool btn_short = false;
bool btn_sta;
int count = 0;
float interval = 0.02;
void key_scan()
{
btn_last = btn_now;
btn_now = btn.read();
if (btn_last==1 && btn_now ==0 ) //°´ÏÂ
btn_sta = true;
if (btn_last==0 && btn_now ==1 ) //µ¯Æð
btn_sta = false;
//printf("btn_sta= %d\r\n",btn_sta);
if (btn_now == btn_last && btn_sta) {
count++;
//printf("count= %d \r\n",count);
if (count > LONG_PRESS) {
printf("button is a long press \r\n");
btn_sta = false;
count = 0;
i2c.write(0xA0, NULL, sizeof(struct stm32f411xx_baseboard_id) + 2);
wait(0.02);
SoftReset();
}
}
else {
if (count > SHORT_PRESS) {
printf("button is a short press \r\n");
btn_sta = false;
count = 0;
}
else {
count = 0;
}
}
//printf("button is %d \r\n",btn.read());
}
timer_key.attach(&key_scan,interval);
2、按键中断和定时器中断结合方式
#include "mbed.h"
Serial pc(USBTX, USBRX);
InterruptIn mybutton(USER_BUTTON);
DigitalOut myled(LED1);
Timeout timer1;
Timeout timer2;
bool flag;
float delay = 1.0; // 1 sec
void long_press()
{
if (!mybutton.read())
//myled = !myled;
pc.printf("long pressed \r\n");
else
pc.printf("short pressed \r\n");
}
void short_press()
{
if (mybutton.read())
//myled = !myled;
pc.printf("short pressed \r\n");
}
void pressed()
{
timer1.attach(&long_press,0.2*10);
timer2.attach(&short_press,0.2);
}
int main()
{
pc.baud(115200);
mybutton.fall(&pressed);
while (1) {
wait(0.1);
}
}