my codes:
unsigned int i=0; void Timer(void) interrupt 1 { i++; } void Main (void) { while (1) printf ("i=%d\n", i); }
when using an int in an ISR and main you will ocasionally get false readings This is true because an int is a 16-bit value which takes 2 bytes. On the 8051, everything is handled as a byte. So, 2 reads are required to get the value of an int. What Erik is saying is that IF an interrupt happens between the 2 instructions that read the int you may actually get the MSB before the interrupt and the LSB after the interrupt. IF the interrupt causes the int to overflow (0x02FF ->0x0300) the value you get will either be 0x0200 or 0x03FF depending on the order in which the bytes are read. The following demonstrates how to disable interrupts, read the value, and re-enable interrupts:
while (1) { int i_copy; EA = 0; i_copy = i; EA = 1; printf ("i=%d\n", i_copy); }
To be completely correct, you should also declare i as "volatile", as it might be updated by something (the ISR) without the knowledge of the code generator / optimizer. The volatile declaration will force the compiler to actually read i, rather than using a previous and possibly stale value.