使用的是蓝桥杯单片机CT107D实训平台:
555定时器内部,有3个5K的电阻分压。
NE555是一个纯硬件的设计,一旦电路确定了,其功能也就定了。
在蓝桥杯的板子上,555定时器是一个信号发生电路,通过定位器Rb3可改变输出信号的频率。
频率就是信号1s产生的信号或者周期。
1HZ就是1s有一个信号(脉冲)
P34引脚计算外部脉冲的个数,但是有时间要求,1s之内。
我们需要两个定时器,一个用来计数,一个用来定时。
定时器最多能计时间65.355ms 所以需要先50ms 然后✖20就是1s。
计数我们可以选择8位自动重装计数,只要来一个脉冲,他就溢出,溢出就会来到中断函数。
按照上述思路,首先,我们需要三个变量,一个变量count_f用来计数,一个count_t用来作为计时,一个dat_f用来最后显示到数码管上的数。
其次,我们初始化定时器:
void init_Timer()
{
TH0=0xff;
TL0=0xff;
TH1=(65535-50000+1)/256;
TL1=(65535-50000+1)%256;
TMOD=0x16;
ET0=1;
ET1=1;
EA=1;
TR0=1;
TR1=1;
}
定时器0用来计数,定时器1用来计时。
中断服务函数就是这些。
void Service_T0() interrupt 1
{
count_f++;
}
void Service_T1() interrupt 3
{
TH1=(65535-50000+1)/256;
TL1=(65535-50000+1)%256;
count_t++;
if(count_t==20)
{
dat_f=count_f;
count_f=0;
count_t=0;
}
}
大体思路就是上述这些,下面是这些完整代码
首先SMG.h
#ifndef __SMG_H
#define __SMG_H
#include "reg52.h"
void DelaySMG(unsigned char t);
void DisPlaySMG_Bit(unsigned char pos,unsigned char dat);
void DisPlay_All(unsigned char dat);
#endif
SMG.c
#include "SMG.h"
#include "reg52.h"
void DelaySMG(unsigned char t)
{while(t--);
}
void DisPlaySMG_Bit(unsigned char pos,unsigned char dat)
{P0=0xff;P2=P2&0x1f|0xe0;P2=P2&0x1f;P0=0x01<<pos;P2=P2&0x1f|0xc0;P2=P2&0x1f;P0=dat;P2=P2&0x1f|0xe0;P2=P2&0x1f;
}
void DisPlay_All(unsigned char dat)
{P0=0xff;P2=P2&0x1f|0xc0;P2=P2&0x1f;P0=dat;P2=P2&0x1f|0xe0;P2=P2&0x1f;
}
最后是主函数:
#include "reg52.h"
#include "SMG.h"
unsigned char code SMG_duanma[18]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,0xbf,0x7f};
unsigned int count_f=0;
unsigned int dat_f=0;
unsigned char count_t=0;
void init_Timer()
{TH0=0xff;TL0=0xff;TH1=(65535-50000+1)/256;TL1=(65535-50000+1)%256;TMOD=0x16;ET0=1;ET1=1;EA=1;TR0=1;TR1=1;
}
void Service_T0() interrupt 1
{count_f++;
}
void Service_T1() interrupt 3
{TH1=(65535-50000+1)/256;TL1=(65535-50000+1)%256;count_t++;if(count_t==20){dat_f=count_f;count_f=0;count_t=0;}
}
void DisPlaySMG_F()
{DisPlaySMG_Bit(0,0x8e);DelaySMG(100);DisPlaySMG_Bit(1,0xff);DelaySMG(100);DisPlaySMG_Bit(2,0xff);DelaySMG(100);if(dat_f>9999){DisPlaySMG_Bit(3,SMG_duanma[dat_f/10000]);DelaySMG(100);}if(dat_f>999){DisPlaySMG_Bit(4,SMG_duanma[(dat_f/1000)%10]);DelaySMG(100);}if(dat_f>99){DisPlaySMG_Bit(5,SMG_duanma[(dat_f/100)%10]);DelaySMG(100);}if(dat_f>9){DisPlaySMG_Bit(6,SMG_duanma[(dat_f/10)%10]);DelaySMG(100);}DisPlaySMG_Bit(7,SMG_duanma[dat_f%10]);DelaySMG(100);DisPlay_All(0xff);
}
void init()
{P0=0xff;P2=P2&0x1f|0x80;P2=P2&0x1f;P0=0;P2=P2&0x1f|0xa0;P2=P2&0x1f;
}
void main()
{init_Timer();init();while(1){DisPlaySMG_F();}
}
记得要将J3上SIGNAL与P34连接上。