This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

counter/timer2 in c51

I am interested in using timer2 to
count .1 second and every .1 second, i would like port0 pin1 1 to toggle.
I would appreciate it if anyone can help me how to initilize the counter2 and interrupt every .1sec.
thanks

  • Hi Selma,

    actually, you should read the description of timer2 in the datasheet of your processor. The adjustment of the parameters depend on the clock frequency that is used for the processor.

    What you want to do can be done with a 16 bit overflow of the timer2. The clock source should be fosc/12 (this way you get a timer "tick" every micro second assuming a clock of 12MHz, if your clock is faster, you will get a tick more often).

    16 bit overflow means that you initialize the counter with a value of e.g. 0xfff0. It will count up on every tick and when the counter overflows (from 0xffff to 0x0000), a timer 2 interrupt will be issued.

    If you want to get an interrupt every 0.1 second you need to "extend" the interrupt. That means, the maximum interrupt period is 0x10000 * 1us (@12MHz). This is 0.065536 sec. So you should initilize the timer in a way that every 0.05 sec an interrupt is issued. That interrupt can count down a software variable, which is initialized with 2. When you count it down every interrup and detect when 0 is reached, you can toggle you bit or do whatevery you want.

    The value for initializing the timer will be 0x10000 - ticks per interrupt periode. For 0.05 sec @12MHz, that should be 0x10000 - 50000 = 0x3CB0.

    I guess, you will be able to find a suitable code for timer0. You can refer to that for setting up a working interrupt service routine.

    If not, I can send you some code snippets for timer 0.