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

[复制链接]
1305|21
 楼主| wangpe 发表于 2020-6-21 19:19 | 显示全部楼层 |阅读模式

#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,没有找出问题!
hanwe 发表于 2020-6-21 19:22 | 显示全部楼层
需要设置按键抬起标志,否则会重复计数。
yufe 发表于 2020-6-21 19:25 | 显示全部楼层
楼主这个按键程序如果用于组合键功能才有意义,否则是简单问题复杂化。
llia 发表于 2020-6-21 19:34 | 显示全部楼层
没有进行按键抖动处理,按一次单片机会检测到有多次的脉冲
langgq 发表于 2020-6-21 19:38 | 显示全部楼层
或许可以加延时在判断。
wangzsa 发表于 2020-6-21 19:41 | 显示全部楼层
你没有,消抖的代码?
wangzsa 发表于 2020-6-21 19:46 | 显示全部楼层
在原来程序加上while(Button_Scan);可以解决问题的。
zhuww 发表于 2020-6-21 19:53 | 显示全部楼层

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

这个就是消抖吧。
zhanglli 发表于 2020-6-21 19:56 | 显示全部楼层
延时防抖动,看一哈例子。
houcs 发表于 2020-6-21 19:59 | 显示全部楼层
这个是按键的控制识别问题的
chenjunt 发表于 2020-6-21 20:02 | 显示全部楼层
在识别按键的时候要加上防误触的措施的,如加时间延迟的
chuxh 发表于 2020-6-21 20:13 | 显示全部楼层
需要加入防抖动的措施的
dingy 发表于 2020-6-21 20:18 | 显示全部楼层
一般用延时就可以解决的,,或者记住当前的按键的按下状态的,跟前后几次的作比较的
liuzaiy 发表于 2020-6-21 20:23 | 显示全部楼层
这个需要对按键进行抗干扰的设计的
pangb 发表于 2020-6-21 20:29 | 显示全部楼层
让其在一定时间段内只处理响应到的其中一个主要的中断的
morrisk 发表于 2020-6-21 20:32 | 显示全部楼层
按键的抗干扰处理的,需要注意下
 楼主| wangpe 发表于 2020-6-21 20:35 | 显示全部楼层

唉,还是没有什么结果,算了,多谢大家啦
qcliu 发表于 2020-7-6 15:21 | 显示全部楼层
是不是没有去抖啊
tfqi 发表于 2020-7-6 15:22 | 显示全部楼层
上升沿和下降沿都触发了?
wiba 发表于 2020-7-6 15:22 | 显示全部楼层
去读的io口那边加一个电容试试
您需要登录后才可以回帖 登录 | 注册

本版积分规则

938

主题

9837

帖子

2

粉丝
快速回复 在线客服 返回列表 返回顶部