仿真原理图如下(proteus仿真工程文件可到本帖附件中下载)
1.尽量不要一个一个位的设置,通过P0,P1,P2设置输出状态
2.P1 = 0x0f;
delay(1);
Tmp = P1 ^ 0x0f;
P1 = 0xf0;
delay(1);
Tmp = P1 >> 4 ^ 0x0f
3.P1=0x0f->芯片内部对外输出状态
单片机源程序如下:
- #include <reg51.h>
- typedef unsigned char uint8;
- typedef unsigned int uint16;
- code uint8 LED_CODE1[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
- 0x7f,0x6f,0x3f,0x06,0x5b,0x4f,0x66,0x6d};
- //个位:0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5
- code uint8 LED_CODE2[] = {0x3f,0x3f,0x3f,0x3f,0x3f,0x3f,0x3f,0x3f,
- 0x3f,0x3f,0x06,0x06,0x06,0x06,0x06,0x06};
- //十位:0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1
- uint8 KeyValue; //存放读取的键值
- uint8 KeyState; //存放键的状态
- void delay(uint16 x)
- {
- uint16 i,j;
- for(i = x; i > 0; i --)
- for(j = 114; j > 0; j --);
- }
- void Beep()
- {
- uint8 i;
- for(i=0;i<100;i++)
- {
- delay(1);
- P3 ^= 0x01;
- }
- }
- void DigDisplay()
- {
- P2 = 0x01;
- P0 = LED_CODE1[KeyValue];
- delay(10);
- P2 = 0x02;
- P0 = LED_CODE2[KeyValue];
- delay(10);
- }
- void KeyDown()
- {
- uint8 Tmp;
- P1=0xf0; //对于并行口,不算赋值,是输出状态;
- if(P1!=0xf0)
- {
- KeyState=1;
- P1=0x0f;
- Tmp = P1 ^ 0x0f; //检测低四位
- switch(Tmp)
- {
- case 1: KeyValue = 0; break;
- case 2: KeyValue = 1; break;
- case 4: KeyValue = 2; break;
- case 8: KeyValue = 3; break;
- default: KeyValue = 16;
- }
- P1=0xf0;
- Tmp = P1 >> 4 ^ 0x0f;//检测高四位
- switch(Tmp)
- {
- case 1: KeyValue += 0; break;
- case 2: KeyValue += 4; break;
- case 4: KeyValue += 8; break;
- case 8: KeyValue += 12;
- }
- while(P1!=0xf0);
- Beep();
- }
- }
- void main()
- {
- KeyState = 0;
- KeyValue = 0;
- while(1)
- {
- KeyDown();
- if(KeyState==1)
- KeyState = 0;
- DigDisplay();
- }
- }
复制代码
所有资料51hei附件下载:
实验四.zip
(192.67 KB, 下载次数: 13)
|