stc15系列单片机 timer组件



/**
 *  文件名:timer.h
 */

#ifndef _TIMER_H
#define _TIMER_H

#define SYS_MCLK 11059200	//系统主时钟
#define FOSC	 11059200	//晶振频率



#define USING_T0
#define USING_STC15_T2



#ifdef USING_T0
	extern uint8_t tmr0LowByte, tmr0HighByte;
	void tmr0_init(uint8_t ms);
#endif



#ifdef USING_T1
	extern uint8_t tmr1LowByte, tmr1HighByte;
	void tmr1_init(uint8_t ms);
#endif



#ifdef USING_T2
	void tmr2_init(uint8_t ms);
#endif



#ifdef USING_STC15_T2
	void stc15_tmr2_init(uint8_t ms);
#endif



#endif



/**
 *  文件名:timer.c
 */

#include 
#include "stdint.h"
#include "timer.h"


/**
 * 定时器0
 */
#ifdef USING_T0
uint8_t tmr0LowByte, tmr0HighByte;

void tmr0_init(uint8_t ms) {	//!!8bits
	uint32_t tmp;	//小心溢出

	tmp = ms * SYS_MCLK / 12 / 1000;
	tmp = 65536 - tmp;
	tmr0LowByte = (uint8_t)tmp;
	tmr0HighByte = (uint8_t)(tmp >> 8);

	AUXR &= 0x7F;		//定时器时钟12T模式
	TMOD &= 0xF0;
	TMOD |= 0x01;
	TL0 = tmr0LowByte;
	TH0 = tmr0HighByte;
	EA = 1;
	ET0 = 1;
	TR0 = 1;
}
#endif



#ifdef USING_T1
uint8_t tmr1LowByte, tmr1HighByte;

void tmr1_init(uint8_t ms) {	//!!8bits
	uint32_t tmp;

	tmp = ms * SYS_MCLK / 12 / 1000;
	tmp = 65536 - tmp;
	tmr1LowByte = (uint8_t)tmp;
	tmr1HighByte = (uint8_t)(tmp >> 8);

	AUXR &= 0xBF;
	TMOD &= 0x0F;
	TMOD |= 0x10;
	TL1 = tmr1LowByte;
	TH1 = tmr1HighByte;
	EA = 1;
	ET1 = 1;
	TR1 = 1;
}
#endif



#ifdef USING_T2
/**
 * 89系列单片机定时器2初始化
 * 定时器模式:16位自动重载
 * 定时器时钟:12T(FOSC/12)
 */
void tmr2_init(uint8_t ms) {
	uint32_t tmp;	//小心溢出

	tmp = ms * SYS_MCLK / 12 / 1000;
	tmp = 65536 - tmp;
	
	T2MOD = 0x00;	//初始化模式寄存器
	T2CON = 0x00;	//初始化控制寄存器
	TL2 = (uint8_t)tmp;			//设置定时器初值
	TH2 = (uint8_t)(tmp >> 8);
	RCAP2L = TL2;				//设置定时器重载值
	RCAP2H = TH2;
	EA = 1;		//!!!
	ET2 = 1;	//!!!
	TR2 = 1;
}
#endif



#ifdef USING_STC15_T2
/**
 * stc15系列单片机定时器2初始化
 * 定时器模式:16位自动重载
 * 定时器时钟:12T(FOSC/12)
 */
void stc15_tmr2_init(uint8_t ms) {
	uint32_t tmp;	//小心溢出

	tmp = ms * SYS_MCLK / 12 / 1000;
	tmp = 65536 - tmp;
	
	AUXR &= 0xFB;		//定时器时钟12T模式
	T2L = (uint8_t)tmp;			//设置定时器初值
	T2H = (uint8_t)(tmp >> 8);
	EA = 1;		//!!!
	IE2 |= 0x04;				//!!!开定时器2中断
	AUXR |= 0x10;				//定时器2开始计时
}
#endif


你可能感兴趣的:(51单片机)