wangpe 发表于 2022-9-2 21:12

每次循环增加1 怎么我这个按键次数每次都加2啊?

#include <reg52.h>

#define uchar unsigned char
#define uint unsigned int

uchar Key_Push,Key_Value=7,Key_Times=0,Key;


sbit K1 = P1^0;
sbit K2 = P1^1;
sbit K3 = P1^2;

void delay1ms(uint x)
{
   uchar i;
   while(x--)
   for(i=0;i<125;i++)
   ;
}

uchar Button_Scan()
{
   Key_Push=0x00;
   Key_Push|=K3;
   Key_Push <<= 1;
   Key_Push|=K2;
   Key_Push <<= 1;
   Key_Push|= K1;
   return(Key_Push^Key_Value);
}

void Button_Proc()            //取按键值
{
   EA = 0;
   if((Key_Value&0x01)==0)// K1按下,取键值1
   {
         Key=1;
   }
   else if((Key_Value&0x02)==0) // K2按下,取键值2
   {
          Key=2;
   }
    else if((Key_Value&0x04)==0) // K3按下,取键值3
   {
          Key=3;
   }         
   EA = 1;
}


void Button()    //取键值,并且记录按键次数
{
   if(Button_Scan())
   {
          delay1ms(10);
          if(Button_Scan())
          {
               Key_Times++;
               if(Key_Times==8)
               Key_Times=0;
               Key_Value=Key_Push;
               Button_Proc();
               
            
          }
   }
}

void main()
{
   while(1)
   {
          Button();
          P3=Key_Times;
   }
}


按键扫描程序调试过程当中,发现Key_Times怎么每次加2,没有找出问题!

wuhany 发表于 2022-9-2 21:13

需要设置按键抬起标志,否则会重复计数。

heweibig 发表于 2022-9-2 21:16

楼主这个按键程序如果用于组合键功能才有意义,否则是简单问题复杂化。

spark周 发表于 2022-9-2 21:20

或许可以加延时在判断。

morrisk 发表于 2022-9-2 21:21

你没有,消抖的代码?

morrisk 发表于 2022-9-2 21:23


在原来程序加上while(Button_Scan);可以解决问题的。

llljh 发表于 2022-9-2 21:25


if(Button_Scan())
   {
          delay1ms(10);
          if(Button_Scan())

这个就是消抖吧。

morrisk 发表于 2022-9-2 21:27

延时防抖动,看一哈例子。

morrisk 发表于 2022-9-2 21:29

这个是按键的控制识别问题的

xxrs 发表于 2022-9-2 21:31

在识别按键的时候要加上防误触的措施的,如加时间延迟的

heweibig 发表于 2022-9-2 21:34

需要加入防抖动的措施的

heweibig 发表于 2022-9-2 21:38

一般用延时就可以解决的,,或者记住当前的按键的按下状态的,跟前后几次的作比较的

pengf 发表于 2022-9-2 21:40

这个需要对按键进行抗干扰的设计的

heweibig 发表于 2022-9-2 21:43

让其在一定时间段内只处理响应到的其中一个主要的中断的

heweibig 发表于 2022-9-2 21:45

按键的抗干扰处理的,需要注意下

jiajs 发表于 2022-9-2 21:47

是不是没有去抖啊

chuxh 发表于 2022-9-2 21:49

上升沿和下降沿都触发了?

dingy 发表于 2022-9-2 21:51

去读的io口那边加一个电容试试

huangchui 发表于 2022-9-2 21:53

我也有这个问题
页: [1]
查看完整版本: 每次循环增加1 怎么我这个按键次数每次都加2啊?