【发布时间】:2018-04-29 19:19:21
【问题描述】:
我正在尝试在带有 XC8 编译器的 MPLAB X IDE 中使用 PIC18F4321 的 Timer1 在 16 位模式下编写一个产生 1000 ms 延迟的子程序。利用此延迟来切换 LED。我的问题是我无法得到想要的延迟(1000 毫秒)。我尝试调试程序我观察到使用宏计算的“计数”值不正确。它给出的值是 0x4000 而不是 0x0F42。 不知道宏有什么问题:
#define count (((timeDelay) * 1000) / (timerPeriod) * 256)
// C-program using polled I/O:
#include <P18F4321.h>
#define timeDelay (1000) // 1000 ms
#define Fosc (4) // 4 MHz
#define timerPeriod (1 / ((Fosc) / 4)) // us
#define count (((timeDelay) * 1000) / (timerPeriod) * 256)
#define countInit ((0xFFFF - (count)) + 1)
#define countInitHigh ((countInit & 0xFF00) >> 8)
#define countInitLow (countInit & 0x00FF)
void T0Delay(); // A subroutine that generates a delay of 1000 ms
void main()
{
OSCCON = 0x60; // 4MHz Internal Oscillator
TRISC = 0x00; // Port C output
T0CON = 0x07; // 16-bit, 1:256 prescaler, internal clock
for(;;) // loop forever
{
PORTCbits.RC0 = 0; // turn LED OFF
T0Delay(); // Wait 10 seconds
PORTCbits.RC0 = 1; // turn LED ON
T0Delay(); // Wait 10 seconds
}
}
void T0Delay(void)
{
TMR0H = countInitHigh;
TMR0L = countInitLow;
INTCONbits.TMR0IF = 0; // clear timer overflow flag
T0CONbits.TMR0ON = 1; // start Timer0
while(!INTCONbits.TMR0IF); //polling, wait until timer finishes counting
T0CONbits.TMR0ON = 0; // Stop Timer0
}
【问题讨论】:
-
timerPeriod真的应该扩展为(1 / (((4)) / 4)),即 1 吗? -
@zwol 是的,它是正确的
-
如果您在 16 位 int 系统上,
timeDelay * 1000会导致未定义的行为 -
@M.M 是的,我使用的是 16 位系统。但是我该如何解决这个问题???
-
一种方法是使用 32 位算法(将
1000更改为UINT32_C(1000)或1000UL)
标签: c embedded microcontroller mplab pic18