我正在将 C 代码编程到 PIC 板上。我的问题是如何让我的程序计算按下按钮(RB0)的时间。然后它会显示所花费的时间并将其显示在液晶显示屏上。以毫秒为单位计算。下面是到目前为止我的代码。
// Global Variables
unsigned int COUNTER;
// Subroutine Declarations
#include <pic18.h>
#include "lcd_portd.c"
//LCD routine, modified from previous examples
void LCD_Out(unsigned int STUFF, unsigned char A)
{
unsigned char C[5], i;
for (i=0; i<5; i++)
{
C[i] = STUFF % 10;
STUFF = STUFF / 10;
}
for (i=5; i>0; i--)
{
if (i == A) LCD_Write('.');
LCD_Write(C[i-1] + '0');
}
}
void interrupt IntServe(void)
{
if (TMR2IF)
{
RB0 = !RB0;
TMR2IF = 0;
COUNTER = COUNTER + 1;
}
}
// Main Routine
void main(void)
{
//Instantiate all Ports to ready for Timers and pin sets
LCD_Init();
TRISA = 0;
TRISB = 0;
TRISC = 0;
TRISD = 0;
TRISE = 0;
ADCON1 = 0x0F;
//Timer Interrupt for 1 ms, A = 9, C = 4, B = 250
//Which means PR2 = 249, and # is x1001101 = 0x4D
T2CON = 0x4D;
PR2 = 249;
TMR2IE = 1;
PEIE = 1;
TMR2ON = 1;
TMR2IP = 1;
GIE = 1;
// While Loop displays length of Wait through Counter
while(1)
{
LCD_Move(0,0);
LCD_Out(COUNTER,3);
}
}
最佳答案
您需要弄清楚按钮如何连接到微 Controller ,并在主函数中声明该端口。确保您能够读取端口的状态(即按钮向上或按钮向下)。
然后,您的 IntServe 中断检查按钮是否按下,是否递增 COUNTER
。
COUNTER
是一个整数,因此它最多只能计数 65,535 毫秒(约 65 秒),您可能需要实现第二个计数变量以防止溢出,以便可以计数按钮按下时间超过 65 秒。
关于c - 使用 Timer2 中断的 C 程序设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35903973/