51單片機(jī)定時(shí)器0工作在模式2
//51hei單片機(jī)網(wǎng)原創(chuàng)作品,版權(quán)所有.
#include "reg_c51.h"
#define reload_value 0x06//計(jì)數(shù)值為250,若時(shí)鐘頻率為12MHz,相當(dāng)于250μs
unsigned char hex[16]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,
0x88,0x83,0xC6,0xA1,0x86,0x8E}; //數(shù)碼管十六進(jìn)制譯碼表
unsigned char n,nn; //定義中斷次數(shù)變量
void main(void) //主函數(shù)
{
TMOD = 0xF0; //定時(shí)/計(jì)數(shù)器0工作在模式2,8位重裝模式
TMOD |= 0x0A; //GATE0=1; C/T0#=0; M1=1; M0=0;
TL0 = reload_value; //設(shè)置初值
TH0 = reload_value; //設(shè)置初值
ET0=1; //允許定時(shí)/計(jì)數(shù)器0中斷
EA=1; //允許總中斷
TR0=1; //啟動(dòng)定時(shí)/計(jì)數(shù)器0
while(1) //無限循環(huán)
{
P1=hex[n/10]; //顯示中斷次數(shù)變量n的高位
P0=hex[n%10]; //顯示中斷次數(shù)變量n的低位
}}
void it_timer0(void) interrupt 1 //定時(shí)/計(jì)數(shù)器0中斷函數(shù)
{
nn=nn++; //每次中斷nn加1,每?jī)纱沃袛嚅g隔250μs
if (nn==40) //nn=40,就是中斷40次,相當(dāng)于40*250μs =10ms
{
nn=0;
n++; //每10ms,n加1,
if(n==100) //n=100,相當(dāng)于時(shí)間10ms*100=1s
{n=0;
P2_0 = ~P2_0;//每間隔1s,將P2_0引腳電平取反,使相連的LED燈閃爍
}}}
評(píng)論