How it works...

In this recipe, we utilize the capability of 8051 timers so that they act as counters. We define an interrupt service routine in exactly the same way as we do for ordinary timers. Since we use Timer 1 as a counter, we use interrupt line number 3, as follows:

void timer1_ISR (void) __interrupt(3) 

The body of the interrupt routine is simple. We only increment the counter variable.

Now, let's ensure the ISR is activated by the external source rather than the clock oscillator. To do so, we configure Timer 1 by setting the C/T bit of the TMOD special function register to one:

TMOD = 0x60;

The same line configures Timer 1 to run in Mode 2  8-bit mode with auto-reload. Since our goal is to make the interrupt routine invoked on every external pin activation, we set the auto-reload and initial values to the maximum value of 254:

TH1 = 254; 
TL1 = 254;

Next, we enable Timer 1:

 TR1 = 1;

Then, all the interrupts from Timer 1 are activated, as shown here:

 ET1 = 1;
EA = 1;

After that, we can enter the endless loop that does nothing since all the work is done in the Interrupt Service Routine:

 while (1); // do nothing 

At this point, we can run the code in the emulator. However, we need to configure the external source of events. For this purpose, we utilize one of the virtual external hardware components supported by MCU8051IDE – the virtual keypad.

We configure one of its keys to activate pin P3.5 of 8051. This pin is used as a source for Timer 1 when it is used in counting mode.

Now, we run the code. Pressing the virtual key activates the counter. Once the timer value overflows, our ISR is triggered, incrementing the counter variable.

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

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