我想弄清楚如何为我的 C8051F020 MCU 创建一个计时器。以下代码使用通过init_Timer2()
以下公式传递给的值:
65535-(0.1 / (12/2000000)=48868。
我将计时器设置为每次执行时计数,每计数 10 次,计数一秒。这是基于上面的公式。传递给 48868 时init_Timer2
会产生 0.1 秒的延迟。每秒需要十个。但是,当我测试计时器时,它有点快。在 10 秒时计时器报告 11 秒,在 20 秒时计时器报告 22 秒。我想尽可能接近完美的一秒。
这是我的代码:
#include <compiler_defs.h>
#include <C8051F020_defs.h>
void init_Clock(void);
void init_Watchdog(void);
void init_Ports(void);
void init_Timer2(unsigned int counts);
void start_Timer2(void);
void timer2_ISR(void);
unsigned int timer2_Count;
unsigned int seconds;
unsigned int minutes;
int main(void)
{
init_Clock();
init_Watchdog();
init_Ports();
start_Timer2();
P5 &= 0xFF;
while (1);
}
//=============================================================
//Functions
//=============================================================
void init_Clock(void)
{
OSCICN = 0x04; //2Mhz
//OSCICN = 0x07; //16Mhz
}
void init_Watchdog(void)
{
//Disable watchdog timer
WDTCN = 0xDE;
WDTCN = 0xAD;
}
void init_Ports(void)
{
XBR0 = 0x00;
XBR1 = 0x00;
XBR2 = 0x40;
P0 = 0x00;
P0MDOUT = 0x00;
P5 = 0x00; //Set P5 to 1111
P74OUT = 0x08; //Set P5 4 - 7 (LEDs) to push pull (Output)
}
void init_Timer2(unsigned int counts)
{
CKCON = 0x00; //Set all timers to system clock divided by 12
T2CON = 0x00; //Set timer 2 to timer mode
RCAP2 = counts;
T2 = 0xFFFF; //655535
IE |= 0x20; //Enable timer 2
T2CON |= 0x04; //Start timer 2
}
void start_Timer2(void)
{
EA = 0;
init_Timer2(48868);
EA = 1;
}
void timer2_ISR(void) interrupt 5
{
T2CON &= ~(0x80);
P5 ^= 0xF0;
timer2_Count++;
if(timer2_Count % 10 == 0)
{
seconds++;
}
if(seconds % 60 == 0 && seconds != 0)
{
minutes++;
}
}