본문 바로가기

정리중인 카테고리/전공 기술

PIC 타이머0 인터럽트 서비스 루틴 + 키 입력 응용

#include <xc.h>

#include <stdint.h>

#pragma config WDTE = OFF, PWRTE = OFF, CP = OFF, BOREN = OFF

#define _XTAL_FREQ 4000000

#define sB_LED  sGPIO.GP1
#define sF_LED  sGPIO.GP2
#define BUTTON  PORTBbits.RB3

volatile union {
    uint8_t port;
    struct {
        unsigned GP0 : 1;
        unsigned GP1 : 1;
        unsigned GP2 : 1;
        unsigned GP3 : 1;
        unsigned GP4 : 1;
        unsigned GP5 : 1;
    };
} sGPIO;

void main() {
    TRISB = 0x08;
    PORTB = 0;

    sGPIO.port = 0;

    OPTION_REGbits.T0CS = 0;
    OPTION_REGbits.PSA = 1;

    INTCONbits.T0IE = 1;
    ei();

    while(1) {
        if(BUTTON == 0) sB_LED = 1;
        else sB_LED = 0;
        PORTB = sGPIO.port;
    }
}

void interrupt isr(void) {
    static uint16_t cnt_t0 = 0;

    TMR0 += 256-250+3;

    INTCONbits.T0IF = 0;

    ++cnt_t0;
    if(cnt_t0 == 500000/250) {
        cnt_t0 = 0;
        sF_LED = ~sF_LED;
    }
}