A warning in advance: I'm no expert in 8051 programming.
Now to the problem at hand:
1) the variable
sec within the
main do loop is undefined. There seems to be no need for the assignment
sec = TL0; since
sec is not used within
main.
2) The
do - while construct plus the following statements
TR=0; and
TF0=0; seem to be unnecessary as in mode 2 the timer bits TL0 will reload on overflow from TH0 automatically.
3) Within the subroutine
ToTime() the variable in the function header is
val, but within the subroutine the name
value is used. That is not proper.
4) You write:
inside the do while loop as soon as the counter starts the tl0 register is incremented
Well yes and no:
- Yes, it is incremented with each clock edge. That is the purpose of counting events (in this case event = clock edge).
- No, it will not be incremented as soon as the loop starts. The loop only enables the timer (
TR0=1;). Counting is independent from the loop, triggered by the clock.
A good explanation of the 8051's timers is given here:
http://www.8052.com/tuttimer.phtml
It's in assembler, but the explanation and the names of the registers and special functins bits seem to be the same as in your code example.
Harald