|
统计一分钟按键次数
#include <reg51.h>
sbit P2_0 = P2^0;//数码管选定位
sbit P2_1 = P2^1;//数码管选定位
sbit P2_2 = P2^2;//数码管选定位
sbit P2_3 = P2^3;//数码管选定位
sbit k1=P1^0;
sbit k2=P1^1;
//共阳数码管
unsigned char code table[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90, 0x88, 0x83, 0xc6, 0xa1, 0x86, 0x8e};
//unsigned int motorspeed = 0;
unsigned int bcf = 0;
unsigned char GE, SHI, BAI, QIAN;
//unsigned int counter = 0;//脉冲数
unsigned char calsp;//多长时间计数一次
unsigned char num1=60;//秒数
unsigned char Button_count=0;//按键次数
unsigned char da;
void display(unsigned char da);//数码管显示
void delay();//延迟函数
//void calspeed();
void Button_sum(bcf);//按键总次数
void scankey();//按键扫描
void Init();//初始化
void main()
{
//EA = 1;//开启部中断
// EX0 = 1;//开启外部中断0
//IT0 = 1;//设置成下降沿触发方式
// TMOD = 0x01;//设置定时器0为模式1,即16位计数模式
// TH0 = (65536-10000)/256;//计数时间为10ms
// TL0 = (65536-10000)%256;
// ET0 = 1;//开启定时器0中断
// TR0 = 1;//启动定时器0
P2 = P2&0xf0;//将P2的1-4置为1
Init();//初始化子函数
while(1)
{
scankey();
Button_sum(bcf);
if(num1==0)
{
TR0=0;
bcf=1;
ET0=0;
//k1=1;
}
display(Button_count);
//display(bcf);
//display(num1);
}
return ;
}
void Init() //初始化子函数
{
TMOD=0X01; //设定定时器0的工作方式为1
TH0=(65536-50000)/256; //定时器装初值一个周期50ms
TL0=(65536-50000)%256;
EA=1; //开总中断
ET0=1; //开定时器0中断
TR0=1; //启动定时器0
EX0=1;//开启外部中断
IT0=1;//设置成下降沿触发方法
}
void Button_sum(bcf)
{
/*if(k1==0&&bcf==0){
delay();
if(k1==0&&bcf==0){
Button_count++;
if(Button_count>=10000)
Button_count=0;
while(!k1 && bcf==0);
}
}*/
if(bcf==0){
if(k1==0){
delay();
if(k1==0){
Button_count++;
if(Button_count>=10000)
Button_count=0;
while(!k1);
}
}
}
else{
Button_count=0;
}
//Button_count=bcf;
}//统计按键总次数
void scankey() //键盘检测子函数
{
if(k1==0) //检测键是否被按下
{
delay(); //延时消除抖动
if(k1==0) //重新读取k1的值
{
Button_count++; //num2为按次数标志位
while(!k1); //等待按键释放
if(Button_count==1) //按键一次计时开始
TR0=1;
}
}
if(k2==0)
{
delay();
if(k2==0)
{
TR0=0;
num1=60;
calsp=0;
Button_count=0;
bcf=0;
}
}
}
//数码管显示函数,依次点亮数码管
void display(unsigned char da)
{
GE = da%10;
SHI = da/10%10;
BAI = da/100%10;
QIAN = da/1000%10;
P2_0 = 1;
P0 = table[QIAN];
delay();
P2_0 = 0;
P2_1 = 1;
P0 = table[BAI];
delay();
P2_1 = 0;
P2_2 = 1;
P0 = table[SHI];
delay();
P2_2 = 0;
P2_3 = 1;
P0 = table[GE];
delay();
P2_3 = 0;
}
//延迟函数
void delay()
{
unsigned char i = 10;
while(i--)
;
}
void _TIMER0() interrupt 1
{
TH0 = (65536-50000)/256;//重新装入初值,计数时间为50ms
TL0 = (65536-50000)%256;
calsp++;
if(calsp==20)
{
calsp=0;
num1--;
/* if(num1==0)
TR0=0;,
bcf=1;*/
}
}
|
|