1.采用两种定时方式,使发光二极管闪烁。
方法一:
#include<reg52.h>
sbit LED = P0^0;
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
void main() {
unsigned int i = 0;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 1;
ADDR1 = 1;
ADDR0 = 0;
while (1)
{
LED = 0;
for (i=0; i<30000; i++);
LED = 1;
for (i=0; i<30000; i++);
}
}
方法二:采用中断的方式,利用数码管显示,编写从100开始倒计时的程序(可显示高位0)。
#include <reg52.h>
sbit LED = P0^0;
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
void main()
{
unsigned char cnt = 0;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 1;
ADDR1 = 1;
ADDR0 = 0;
TMOD = 0x01;
TH0 = 0xB8;
TL0 = 0x00;
TR0 = 1;
while (1)
{
if (TF0 == 1)
{
TF0 = 0;
TH0 = 0xB8;
TL0 = 0x00;
cnt++;
if (cnt >= 50)
{
cnt = 0;
LED = ~LED;
}
}
}
}
2.采用中断的方式,利用数码管显示,编写从100开始倒计时的程序(可显示高位0)。
#include <reg52.h>
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
unsigned char code LedChar[] = {
0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E };
unsigned char LedBuff[3] = { 0xFF, 0xFF, 0xFF};
unsigned char i,j = 0;
unsigned int cnt = 0;
unsigned char flag1s = 0;
void main()
{
unsigned long sec = 101;
EA = 1; //使能总中断
ENLED = 0; //使能U3,选择控制数码管
ADDR3 = 1; //因为需要动态改变ADDR0-2的值,所以不需要再初始化了
TMOD = 0x01; //设置T0为模式1
TH0 = 0xFC; //为T0赋初值0xFC67,定时1ms
TL0 = 0x67;
ET0 = 1; //使能T0中断
TR0 = 1; //启动T0
while (1)
{
if (flag1s == 1)
{
flag1s = 0;
sec--;
LedBuff[0] = LedChar[sec%10];
LedBuff[1] = LedChar[sec/10%10];
LedBuff[2] = LedChar[sec/100%10];
}
}
}
void InterruptTimer0() interrupt 1
{
TH0 = 0xFC; //重新加载初值
TL0 = 0x67;
cnt++;
if (cnt >= 1000)
{
cnt = 0;
flag1s = 1;
}
P0 = 0xFF;
switch (i)
{
case 0: ADDR2=0; ADDR1=0; ADDR0=0; i++; P0=LedBuff[0]; break;
case 1: ADDR2=0; ADDR1=0; ADDR0=1; i++; P0=LedBuff[1]; break;
case 2: ADDR2=0; ADDR1=1; ADDR0=0; i=0; P0=LedBuff[2]; break;
default: break;
}
}