可预置十六位计数器的效果如下:
初始界面:
单刀双置开关SW1打到下面,左边的LED灯亮,上下两个按钮开始工作,按下上面的按钮显示加1,按下下面的按钮显示减1
单刀双置开关SW1打到上面,左边的LED灯不亮,4×4 矩阵键盘 KEYBOARD开始工作,从左到右,从上到下分别为0到F(第一个为0)输入是从左到右开始的,eg:要显示16这个数值,先输入1,2位共阴极数码管右边部分为0,左边部分为1;再输入6,2位共阴极数码管右边部分为1,左边部分为6.
(代码在附件中给出,格式为c语言代码,由Keil4编译运行)
单片机源程序如下:
- #include "at89x51.h"
- unsigned char low=0;
- unsigned char high=0;
- unsigned char led_disp[] = {
- 0x3f,0x06,0x5b,0x4f,
- 0x66,0x6d,0x7d,0x07,
- 0x7f,0x6f,0x77,0x7c,
- 0x39,0x5e,0x79,0x71
- }; //0-f
- void delay_ms(unsigned int a)
- {
- unsigned int i;
- while(a--)
- {
- i = 70;
- while(i--);
- }
- }
- //反转法
- unsigned char translate(unsigned char x)
- {
- unsigned char y;
- if(x==7) //0111
- y=3;
- else if(x==11) //1011
- y=2;
- else if(x==13) //1101
- y=1;
- else if(x==14) //1110
- y=0;
- return y;
- }
- unsigned char getKey(unsigned char *key)
- {
- unsigned char r, c, t;
- P3 = 0xf0; //列线置1,行线置0
- if(P3 != 0xf0) //按键按下
- {
- //消抖
- delay_ms(15);
- if(P3 != 0xf0)
- {
- t = P3;
- //取列号
- c = (t & 0xf0) >> 4;
- c = translate(c);
- //将列值输出,行线置1
- P3 = t | 0x0f;
- //取行号
- r = (P3 & 0x0f);
- r = translate(r);
- *key = r*4+c;
- //等待按键放开
- P3 = 0xf0;
- while(P3 != 0xf0);
- return 1;
- }
- }
- return 0;
- }
- void dispHigh(unsigned char v)
- {
- P2=0;
- P1_7 = 1;
- P1_6 = 0;
- P2 = led_disp[v];
- delay_ms(5);
- }
- void dispLow(unsigned char v)
- {
- P2=0;
- P1_6 = 1;
- P1_7 = 0;
- P2 = led_disp[v];
- delay_ms(5);
- }
- void main(void)
- {
- unsigned char k;
- //P2 = 0;//预置
- if(P1_5==1)
- {
- P2=0;
- P1_4=1;//左边的LED不亮,键盘计数
- while(1){
- if(getKey(&k))
- {
- high= low;
- low = k;//低位置数
- }
- dispLow(low);//低位显示
- dispHigh(high);
- if(P1_5==0)
- break;
- }
- }
- if(P1_5==0)
- {
- P2=0;
- P1_4=0;//左边的LED亮,加减计数
- while(1)
- {
- delay_ms(15);
- if(P1_0==0)
- {
- delay_ms(300);
- low++;
- if(low==16)
- {
- low=0;
- high++;
- if(high==16)
- {
- low=0;
- high=0;
- }
- }
- }
- else if(P1_1==0)
- {
- delay_ms(300);
- low--;
- if(low==-1)
- ……………………
- …………限于本文篇幅 余下代码请从51黑下载附件…………
复制代码
所有资料51hei提供下载:
可预置十六位计数器.zip
(223.04 KB, 下载次数: 41)
|