Reputation: 157
This C programme is supposed to simulate a digital clock. There gonna be 3 7segment in the Proteus programme to show the hour, minute and second (like a digital clock)
#include<reg51.h>
void main()
{
int t, i, j, k, a, b, c, d, e;
e = 0;
P3 = 0x00;
P2 = 0x00;
P0 = 0x00;
while (1)
{
P0 = 0x00;
for (c = 0; c<3; c++)
{
for (d = 0; d<10; d++)
{
for (a = 0; a<6; a++)
{
for (b = 0; b<10; b++)
{
for (t = 0; t<6; t++)
{
for (i = 0; i<10; i++)
{
for (k = 0; k<1000; k++)
for (j = 0; j<142; j++);
P3++;
}
P3 = P3 + 0x06;
}
P3 = 0x00;
P2++;
}
P2 = P2 + 0x06;
}
P2 = 0x00;
P0++;
if (P0 == 0x24){
P0 = 0x00;
e = 1;
}
if (e == 1)
break;
}
if (e == 1){
e = 0;
break;
}
P0 = P0 + 0x06;
}
}
}
Would it be OK if someone explains the code? I don't understand the nested for
loops at the beginning of the code? Moreover, what are these increasing?
P2 = P2 + 0x06;
What is 0x06? finally, what is e
supposed to do in this code?
Upvotes: 1
Views: 532
Reputation: 41962
The following snippet has no side-effect
for (k = 0; k<1000; k++)
for (j = 0; j<142; j++);
as a result it's probably used as a desperate man's delay and the innermost 3 loops can be converted to this
for (i = 0; i<10; i++)
{
delay(142000);
P3++;
}
P3 = P3 + 0x06;
In practice the whole delay loops will be removed completely after optimization, so the real delay function from the library should be called instead
From what I can guess P3 is the BCD output for the units digit in 3 numbers. It's increased by 1 each 142000 cycles. Once it's been increased 10 times, i.e. an overflow has happen, 0x06 would be added to the sum to adjust the BCD addition (move the carry to the next digit) as I explained here.
If you write the P3 after each cycle in hex it'll be easier to get 0x00 0x01 0x02 0x03 ... 0x08 0x09 0x10 0x11 ... 0x19 0x20
: after 10 cycles we'll get 0x0A + 0x06 = 0x10
.
However if we continue to the next line
P3 = 0x00;
P2++;
we can see that P3 is reset after 10 cycles, so it means only the low 4 bits of the least significant digit is stored in P3, the next digit will be stored in the low nibble of P2. Why? because the minute's tens digit ranges only from 0 to 5 (counted by t
). The way P2 and P0 are increased and carried is also the same as P3.
Finally P0 is reset to 0 when it reaches 24, so P0 contains the whole hour
if (P0 == 0x24){
P0 = 0x00;
e = 1;
}
Now you can easily guess what e
is used for
Upvotes: 2