First:
#include <AT89X51.H> unsigned int TD3=0;// void t0(void) interrupt 1 using 3 { TL0=(65536-50000)%256; TH0=(65536-50000)/256; //6MHz TD3++; } void main() {//1 TMOD=0x11; // TL0=(65536-50000)%256; TH0=(65536-50000)/256; // ET0=1; EA=1; TR0=1; while(1) { while(TD3<=18000); // TD3=0; } }//1
Secondly:
#include <AT89X51.H> unsigned int TD3=0;// void t0(void) interrupt 1 using 3 { TH0=(65536-50000)/256; // TL0=(65536-50000)%256; TD3++; } void main() {//1 TMOD=0x11; // TH0=(65536-50000)/256; // TL0=(65536-50000)%256; ET0=1; EA=1; TR0=1; while(1) { while(TD3<=18000); // TD3=0; } }//1
TD3 counter limited all 18000.By the first way, TD3 counted to 18000 then step int TD3=0; .But , by the second way , TD3 counted only to 17920 then step into TD3=0; .Why did this happen? Thanks.
You are using an 8-bit processor. The processor is incapable of performing an atomic test of a 16-bit number, just as your 16-bit assign of the timer registers has to be splitted into two 8-bit assigns. The test is performed either low byte before high byte or the reverse - and if the variable gets incremented in-between, you get into troubles.
Why not let your interrupt perform the compare/reset, and set a flag?
You also have to think about this problem when you reload the timer in your interrupt handler - what happens when you assign just the low or the high part of the timer value?