How it works...

For our sample applications, we are going to use an emulator for the 8051 microcontroller. Several of them are available; however, we will be using MCU8051IDE since it's readily available in the Ubuntu repository.

We install it as a regular Ubuntu package, as follows:

# apt install -y mcu8051ide

This is a GUI IDE and requires an X Window system to run. If you use Linux or Windows as your working environment, consider installing and running it directly from https://sourceforge.net/projects/mcu8051ide/files/.

The simple program we created defines a global variable called Counter, as shown here:

volatile int Counter = 0;

This is defined as volatile, indicating that it can be changed externally and that a compiler shouldn't try to optimize the code to eliminate it.

Next, we define a simple function called timer0_ISR:

void timer0_ISR (void) __interrupt(1)

It doesn't accept any parameters and doesn't return any values. The only thing it does is increment the Counter variable. It is declared with an important attribute called __interrupt(1) to let the compiler know that it is an interrupt handler and that it serves the interrupt number 1. The compiler generates code that updates the corresponding entry of the interrupt vector array automatically.

After defining the ISR itself, we configure the parameters of the timer:

TMOD = 0x03; 
TH0 = 0x0;
TL0 = 0x0;

Then, we turn on Timer 0, as shown here:

TR0 = 1;

The following command enables interrupts from Timer 0:

ET0 = 1; 

The following code enables all interrupts:

EA = 1;

At this point, our ISR is being periodically activated by the timer's interrupt. We run an endless loop that does nothing since all the work is done within ISR:

while (1); // do nothing 

When we run the preceding code in the simulator, we will see that the actual value of the counter variable changes over time, indicating that our ISR is being activated by the timer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.115.195