help! why?

my codes:

unsigned int i=0;
void Timer(void) interrupt 1
    {
    i++;
    }

void Main (void)
    {
    while (1) printf ("i=%d\n", i);

    }

I had thought that I will get below on serial window

"
i=0;
i=1;
i=2;
i=3;
...
"


but I got

"
i=0
i=-9472
i=-28416
i=29184
i=10240
i=-8960
i=-27904
i=29696
i=10752
i=-8192
i=-27392
i=30464
i=11264
i=-7680
......
"


these values are disorderly and unsystematic, why? You had better try it on your own keilc.

Parents
  • hi,

    firstly, about disorderly and unsystematic. You know, printf() is not simple function which produce result by one assembly command. Processing format string and sending result via COM-port - it all take alot of time. Ofcoz timer does not wait till printf() will be done; so for time within printf() sends a byte, timer may be increased many times. As result you will get randomize values of i variable.

    well, now about negative values. In fact %d prints both negative and positive values depend on bit 15 of i variable. Printf() does not know about your unsigned declaration. If you wish to print all positive values so you should use %ud or %u (it depends on compiler you use).

    Good days!

Reply
  • hi,

    firstly, about disorderly and unsystematic. You know, printf() is not simple function which produce result by one assembly command. Processing format string and sending result via COM-port - it all take alot of time. Ofcoz timer does not wait till printf() will be done; so for time within printf() sends a byte, timer may be increased many times. As result you will get randomize values of i variable.

    well, now about negative values. In fact %d prints both negative and positive values depend on bit 15 of i variable. Printf() does not know about your unsigned declaration. If you wish to print all positive values so you should use %ud or %u (it depends on compiler you use).

    Good days!

Children
More questions in this forum