Before addressing your questions, I think it's worth pointing out what TR0
, TH0
, and TL0
are. They are not variables local to the function or sitting on the stack (assuming you have a call stack, which most 8051 applications do not -- look up memory overlays). These are Special Function Registers, usually abbreviated SFR. You can read more about SFRs, but for the purposes of your question you can treat them as global variables from a scope perspective.
You may modify the
TL0
andTH0
registers at any time, including within the Timer 0 peripheral's interrupt handler.It is not necessary to stop the the timer to modify its value, but be aware that it will continue counting while you're doing that. This could be a problem if you are writing just as the lower byte is rolling over where you might end up with a timer value different than you intended.
<previous code> // Timer increments to 0x12fe TH0 = 0xff; // Timer is now 0xffff // Timer increments to 0x0000 TL0 = 0x52; // Timer is now 0x0052 // Timer increments to 0x0053
You tried to set the timer to 0xff52 but you ended up with 0x0052. This is an extreme example, but the risk is there. You can be less risky by writing
TL0
first followed byTH0
, but turning off the timer is the simplest solution.Since you now know that
TL0
andTH0
are SFRs with global scope, you don't have to worry about the stack or any other function argument passing mechanism interfering with them.