프로그램/마이컴

8051 모든 인터럽트

더월드 2020. 3. 4.

 

#include<reg51.h>
#define LEDs P0
unsigned char receivedChar=0;
unsigned char count=0;
unsigned char ti_flag=0;

void ext_int_0() interrupt 0
{ 
    count++;
}

void ext_int_1() interrupt 2
{ 
    count--;
}

void timer0_isr() interrupt 1
{
    TH0  = 0X4B;         // ReLoad the timer value for 50ms
    TL0  = 0XFD;
    if(timerCount >= 20) // count for 1sec delay(50msx20 = 1000ms = 1sec)
    {
        timerCount = 0;
        LEDs =!LEDs;        // Toggle the LEDs every 1sec
    }
    else
    {
        timerCount++;
    }
}

void serial_isr() interrupt 4
{ 
    if(RI == 1)
    {
        receivedChar = SBUF; 
        if(receivedChar == 'c') 
        {
            count = 0;       // Clear the count if 'c' is pressed on serial terminal
        }
        RI = 0;              // Clear the Receive interrupt flag
    }
    else if(TI == 1)
    {
        TI = 0;              // Clear the Transmit interrupt flag
        ti_flag = 1;
    }
}

void serial_txChar(char ch)
{
    SBUF = ch;
    while(ti_flag == 1);
    ti_flag = 0;
}

void serial_txString(char *ptr)
{
    while(*ptr)
        serial_txChar(*ptr++);
}

void serial_txNumber(unsigned char num)
{
    serial_txString("\n\rCount = ");
    serial_txChar(num/100+0x30);
    num = num%100;
    serial_txChar(num/10+0x30);
    serial_txChar(num%10+0x30);
}

void main()
{
    unsigned char old_count=0;
    SCON = 0x50;  // Asynchronous mode, 8-bit data and 1-stop bit
    TMOD = 0x21;  // Timer1 in Mode2 and Timer0 in Mode1
    TH1 =  0xFD;  // Load timer value for 9600 baudrate
    TR1 = 1;      // Turn ON the timer for Baud rate generation
    ES  = 1;      // Enable Serial Interrupt
    P3 |= 0x0c;   // Configure the INT0 & INT1 pins as Inputs
    EX0 = 1;      // Enable INT0
    EX1 = 1;      // Enable INT1
    TH0 = 0x4B;   // Load timer value for 50ms
    TL0 = 0xFD;
    ET0 = 1;      // Enable Timer0 Interrupt
    TR0 = 1;      // Enable Timer1 Interrupt
    EA  = 1;      // Enable Global Interrupt bit

    serial_txString("\n\rProgram to demonstrate all interrupts.");
    serial_txString("\n\rTimer0 Interrupt: Observe the LED blinking on P0");
    serial_txString("\n\rINT0 Interrupt: Press INT0 to increment the count");
    serial_txString("\n\rINT1 Interrupt: Press INT1 to decrement the count");
    serial_txString("\n\rSerial Interrupt: Press 'c' to clear the count \n\r");

    while(1)
    {
        serial_txNumber(old_count); // Transmit the interrupt count value
        while(old_count == count);  // wait till the counter changes(INT0/INT1/Serial interrupts will change the counter)
        old_count = count;           
    }
}

'프로그램 > 마이컴' 카테고리의 다른 글

PIC18F4520 EEPROM  (0) 2020.03.04
PIC18F4520 Timer.  (0) 2020.03.04
외부 인터럽트  (0) 2020.03.04
8051/4051 Timers  (0) 2020.03.04
8051/4051 UART Interrupt  (0) 2020.03.03

댓글

💲 추천 글