注册会员
- 积分
- 199
- 威望
- 154
- 贡献
- 41
- 兑换币
- 0
- 注册时间
- 2011-11-19
- 在线时间
- 2 小时
|
我是新手,刚从单片机起步,然后我想理由独立按键来模拟一下密码输入的过程,比如按对四个键才能使所有的灯亮,但老出问题。请问应该如何写呢?
以下是我的程序,密码是1,2,3,4就是依次按下K1,K2,K3,K4,然后使所有按对后才能使所有灯亮。但是只有在K1-4中随便按4个键就能使全部灯亮,我有怎么办?- #include <reg51.h>
- #include <intrins.h>
- unsigned char scan_key();
- //unsigned int proc_key(unsigned char key_v);
- void delayms(unsigned char ms);
- sbit K1 = P0^0; //对应按钮K1
- sbit K2 = P0^1; //对应按钮K2
- sbit K3 = P0^2; //对应按钮K3
- sbit K4 = P0^3; //对应按钮K4
- sbit K8 = P0^7;
- main()
- {
- unsigned char key_s;
- unsigned int i=0,j=0;
- unsigned char code key_v[]={0x07,0x0b,0x0d,0x0e};
- unsigned char code key_v1[]={0xf7,0xfb,0xfd,0xfe};
- P2 = 0xff;
- while(1)
- {
- for(i=0;i<4;i+=1)
- {
- key_s = scan_key();
- if(key_s == key_v[i])
- {
- delayms(10);
- key_s = scan_key();
- if(key_s == key_v[i])
- P2=key_v1[i];
- delayms(20);
- key_s = scan_key();
- if(key_s != key_v[i]) j+=1;
- }
-
- }
- if(j==4) P2=0x00;
- if(K8==0) //复位
- {
- delayms(10);
- if(K8==0) P2=0xef;
- delayms(20);
- if(K8!=0) {j=0;i=0;}
- }
- }
- }
- unsigned char scan_key()
- {
- unsigned char key_s;
- key_s = 0x00;
- key_s |= K1;
- key_s <<= 1;
- key_s |= K2;
- key_s <<= 1;
- key_s |= K3;
- key_s <<= 1;
- key_s |= K4;
- return key_s;
- }
- void delayms(unsigned char ms) // 延时子程序
- {
- unsigned char i;
- while(ms--)
- {
- for(i = 0; i < 120; i++);
- }
- }
复制代码 |
|