8051 external interrupt

martin picture martin · Apr 30, 2010 · Viewed 7.3k times · Source

how to enable external interrupt of 8051?

Answer

jschmier picture jschmier · Apr 30, 2010

Each of the 8051s interrupts has its own bit in the interrupt enable (IE) special function register (SFR) and is enabled by setting the corresponding bit. The code examples below are in 8051 assembly as well as C to provide a general idea of what is taking place.

To enable external interrupt 0 (EX0) you need to set bit 0 of IE.

SETB EX0 or ORL IE,#01 or MOV IE,#01

To enable external interrupt 1 (EX1) you need to set bit 3 of IE.

SETB EX1 or ORL IE,#08 or MOV IE,#08

Interrupts then need to be globally enabled by setting bit 7 of IE, which is the global interupt enable/disable bit (EA). If necessary, you can set the priority of the external interrupts to high via the interrupt priority (IP) SFR.

SETB EA or ORL IE,#80

Example in C:

#define IE (*(volatile unsigned char *)0xA8)
#define BIT(x) (1 << (x))
...
IE &= ~BIT(7); /* clear bit 7 of IE (EA) to disable interrupts */
...
IE |= BIT(0);  /* set bit 0 of IE (EX0) to enable external interrupt 0 */
...
IE |= BIT(1);  /* set bit 3 of IE (EX1) to enable external interrupt 1 */
...
IE ^= BIT(7)   /* toggle bit 7 of IE (EA) to re-enable interrupts */

or

IE = 0x89;  /* enable both external interrupts and globally enable interrupts */

The various 8051 C compiler vendors often define their own methods of setting up interrupt functions. You may need to consult the documentation for your specific compiler.

To define an interrupt function using the Keil C51 Compiler (pdf link to application note), an interrupt number and register bank is specified where the interrupt number corresponds to a specific interrupt vector address.

void my_external_interrupt_0_routine(void) interrupt 0 using 2
{
/* do something */
}

To define an interrupt function using the 8051 IAR C/C++ Compiler (icc8051) (pdf link to reference guide), the __interrupt keyword and the #pragma vector directive can be used.

#pragma vector=0x03
__interrupt void my_external_interrupt_0_routine(void)
{
/* do something */
}

If you are new to the 8051, there is a wealth of information available at www.8052.com. I would also recommend The 8051/8052 Microcontroller: Architecture, Assembly Language, and Hardware Interfacing written by Craig Steiner, the webmaster and author of 8052.com.