简体   繁体   中英

Design for a C Program Using Timer2 Interrupts

I'm programming my C code onto a PIC board. My question is how to get my program to count how long a button (RB0) is pressed down. It then displays the time it took and display it on an LCD Display. It counts in ms. Below is my code so far.

    // 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);
   }
}

you need figure out how your button is connected to your microcontroller and declare that port in you main function. Make sure you are able to read the state of the port (ie button up or button down).

Then it your IntServe interrupt check if the button is down, if it is increment COUNTER .

The COUNTER is an integer, so it will only be able to count upto 65,535 ms (about 65 seconds), you may want to implement a second count variable for overflow, so that you can count button presses longer than 65 seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM