Search code examples
cembedded8051

embedded C programming issue for 8051 MCU


I am studying 8051 MCU programming and I am now doing a mini project of LED flashing. What I want to do is that when I press the button, the LED will flash slower. Conversely, when I release the button, the LED will flash faster. I used embedded C and here is my code:

#include <reg51.h>

sbit LED = P0^0;
sbit SW = P1^0;


void T0delay(int num);

void main()
{
    while (1)
    {
        LED = ~LED;
        if (SW == 0)
        {
            T0delay(4);
        }
        else
        {
            T0delay(2);
        }
    }
}

void T0delay(int num)
{
        **unsigned char i;
        unsigned char a;**
        for (a=0;a<num;a++)
        {
            for (i=0;i<num;i++)
            {
                TMOD = 0x01;
                TL0 = 0xFE;
                TH0 = 0xA5;
                TR0 = 1;
                while (TF0 == 0);
                TR0 = 0;
                TF0 = 0;
            }
        }               
}

But I found that when I declared the variable a and i as 0 outside the for loop, the LED will flash faster.

#include <reg51.h>

sbit LED = P0^0;
sbit SW = P1^0;


void T0delay(int num);

void main()
{
    while (1)
    {
        LED = ~LED;
        if (SW == 0)
        {
            T0delay(4);
        }
        else
        {
            T0delay(2);
        }
    }
}

void T0delay(int num)
{
        **unsigned char i = 0;
        unsigned char a = 0;**
        for (a;a<num;a++)
        {
            for (i;i<num;i++)
            {
                TMOD = 0x01;
                TL0 = 0xFE;
                TH0 = 0xA5;
                TR0 = 1;
                while (TF0 == 0);
                TR0 = 0;
                TF0 = 0;
            }
        }               
}

Can anyone explain why it performs like this? is there anything wrong in my declaration way causing this result? What is the good practice for a professional engineers to declare the variable? Sorry for my poor English. Please let me know in case there is any unclear in my question. Thank you!


Solution

  • By initialising i once only, it is not reset for the next iteration of the a loop.

    for (i; i < num; i++)
    

    On the second and subsequent loop, i will start at num. This is why you need

    for (i = 0; i < num; i++)
    

    So that i loops from 0 on every occasion.

    But the initial loop value of a is set only once, so it doesn't matter whether that is when a is defined, or in the first loop condition.