Search code examples
cinterrupt8051

8051 two timers and Interrupts problem in c


I want to make two timer works at the same time but it seems not working at all

I wrote the code to blink led.
The led would blink when i used either one of the timer and interrupt when I used them both, two ports for led are not working.

Was there any rule that can't use two interrupts or timers at the same time?
or just my mcu broken?

btw I am using AT89S52
coding by keil uVision5
and program with WLpro

Here is my code

#include <reg52.h>

sbit LED = P0 ^ 5;
sbit LED2 = P0 ^ 6;
int i = 0;
int y = 0;
int x = 0;
int count = 0;

void blink2()
interrupt 3
{
  TH1=0x7d;
  TL1=0xec;
  y++;

  if(y==100) {
    if(i==1) {
      LED=0;
      x=0;
    }
    else {
      LED=1;
      x=1;
    }
    y=0;
  }
}

void blink1() 
interrupt 1
{
  TH0=0xd8;
  TL0=0xf0;
  count++;

  if(count==100) {
    if(i==1) {
      LED2=0;
      i=0;
    }
    else {
      LED2=1;
      i=1;
    }
    count=0;
  }
}

void main() {
  TMOD = 0x11;  // timer mode
  TH0 = 0xd8;
  TL0 = 0xf0;

  TH1 = 0x7d;
  TL1 = 0xec;

  TR0 = 1;
  TR1 = 1;

  IE = 0x8a;
}

Solution

  • In blink2() you test the global variable i, but you never change it.

    Note aside: blink1() manages LED2, while blink2() manages LED. Perhaps a more consistent naming would help, and the same applies to the variables i, x, y and count.

    There is no restriction to use more than one interrupt concurrently, but when of them executes, the others are temporarily blocked. It is not your problem here, your code is fine; but if you want an interrupt be able to be interrupted in turn, for low latency, you must re-enable interrupts in the (relatively) "slow" handler.

    Last suggestion: where you have "if (y==100)" and lately "y=0", if you move "y=0" just below "if (y==100)" readability improves.

    All the rest seems ok, but I would double-check the setup of the timers; I don't have at hand the datasheet, may be there is a flag to clear in the interrupt handler (I can't remember). Given that you say that a single timer works, I suppose you know what to do, two timers should run without any problem.