天天看點

定時器c語言程式52,52單片機定時器2使用(C語言程式).doc

52單片機定時器2使用(C語言程式)

水寒 8051 1,128 views 0 Comments 發表評論

本文是關于52單片機定時器計數器2做為普通的16位自動重裝定時器使用,類似于定時器計數器0和定時器計數器1工作在方式1下。以下程式在Keil 2和Keil 3下調時通過,下載下傳在本校的實驗闆上達到預期效果。AT89C52及其以上、AT89S52及其以上、STC89C52及其以上測試正常運作。

源代碼:

view source

print?

001

015

016

#include

017

#include

018

#define uchar unsigned char

019

#define uint unsigned int

020

#define LED_DATA P0

021

sbit DULA=P2^6;

022

sbit WELA=P2^7;

023

sbit LED=P1^7;

024

uchar timer2_ctr,num;

025

uchar code table[]={0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71, 0x40, 0};

026

027

//24MHz晶振延時x毫秒函數

028

void delay_ms(uint xms)

029

{

030

uint x,y;

031

for(x=xms; x>0; x--)

032

for(y=248; y>0; y--);

033

}

034

035

//初始化主函數

036

void init_main()

037

{

038

DULA=0; //關閉數位管顯示

039

WELA=0;

040

041

RCAP2H=(0xFFFF-50000)/256;

042

RCAP2L=(0xFFFF-50000)%256; //24MHz晶振下定時25ms,自動重裝

043

TH2=RCAP2H;

044

TL2=RCAP2L; //定時器2賦初值

045

T2CON=0; //配置定時器2控制寄存器,這裡其實不用配置,T2CON上電預設就是0,這裡指派隻是為了示範這個寄存器的配置

046

T2MOD=0; //配置定時器2工作模式寄存器,這裡其實不用配置,T2MOD上電預設就是0,這裡指派隻是為了示範這個寄存器的配置

047

IE=0xA0; //1010 0000開總中斷,開外定時器2中斷,可按位操作:EA=1; ET2=1;

048

TR2=1; //啟動定時器2

049

}

050

051

//數位管顯示3位數:0-255

052

void display(uchar num)

053

{

054

uchar gw,sw,bw;

055

bw=num/100;

056

sw=num%100/10;

057

gw=num%10;

058

059

LED_DATA=0XFE; //1111 1110

060

WELA=1;

061

_nop_();_nop_();

062

WELA=0;

063

LED_DATA=table[bw];

064

DULA=1;

065

_nop_();_nop_();

066

DULA=0;

067

delay_ms(3);

068

069

LED_DATA=0XFD; //1111 1101

070

WELA=1;

071

_nop_();_nop_();

072

WELA=0;

073

LED_DATA=table[sw];

074

DULA=1;

075

_nop_();_nop_();

076

DULA=0;

077

delay_ms(3);

078

079

LED_DATA=0XFB; //1111 1011

080

WELA=1;

081

_nop_();_nop_();

082

WELA=0;

083

LED_DATA=table[gw];

084

DULA=1;

085

_nop_();_nop_();

086

DULA=0;

087

delay_ms(3);

088

}

089

090

void main()

091

{

092

init_main();

093

while(1)

094

{

095

display(num);

096

}

097

}

098

099

void timer2() interrupt 5

100

{

101

//!!!注意!!! 定時器2必須由軟體對溢出标志位清零,硬體不能清零,這裡與定時器0和定時器1不同!!!

102

103

TF2=0;

104

timer2_ctr++;

105

106

//定時25ms40=1000ms即1秒鐘,這裡模拟一個60秒秒表

107

if(timer2_ctr>=40)

108

{

109

timer2_ctr=0;

110

LED=~LED;

111

num++;

112

if(num>=60)

113

{

114

num=0;

115

}

116

}

117

}

展開閱讀全文