一、实验要求:
1.定时器定时中断实验,使用定时器实现1 s的定时,每秒钟数码管显示值加1,数码管显示值从0到9循环。
2、定时器计数器功能,使用定时器对按键输入进行计数,按键每按下一次,数码管显示值加1,数码管显示值从0到8循环。
二、实验内容
(1)
代码:
#include <reg51.h>
unsigned char num[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
unsigned char count=0,time=19; //因为time先使用,再自增,所以time应为19,而不是20
void main()
{
TMOD=0x10; //0001 0000
TH1=(65536-50000)/256;
TL1=(65536-50000)%256;
TR1=1;
P2=num[count];
while(1){
while(TF1==0); //1s(20*50ms=20*50000us)//超范围(>65535)
TF1=0;
if(!time--){ //判断,即先让扫描20次,每次50000us,当达到1s时,再改变P2口的值
P2=num[++count%10];
time=19;
}
TH1=(65536-50000)/256;
TH1=(65536-50000)%256;
}
}
调试结果:

仿真结果:

(2)
代码:
#include<reg51.h>
sbit b=P1^0;
unsigned char code table[]={0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90, 0x88, 0x83, 0xc6, 0xa1, 0x86, 0x8e};//共阳极
//unsigned char code table[]={0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71}; //共阴极
void delay(int sex)
{
int x,y;
for(x=sex;x>0;x--)
for(y=110;y>0;y--);
}
void main()
{
int a;
delay(5);
while(1)
{
if(b==0)
{
if(b==0)
{
a++;
P3=table[a];
while(b==0);
}
}
}
}
调试结果:

仿真结果:
