Blinking LEDs in reverse order

cmicrochipmicrocontrollerpic

The code below flashes some LEDs in order: pin 1, pin 2, pin 3, pin 4.

After this sequence has completed I would like to reverse direction and show pin 4, pin 3, pin 2, pin 1.

I wrote the code below but it's not working in reverse order.

What might be wrong?

#include <htc.h>

__CONFIG(1,OSCSDIS & HSPLL);
__CONFIG(2,BORDIS & PWRTDIS &WDTDIS);
__CONFIG(3,CCP2RC1);
__CONFIG(4,LVPDIS & STVREN);
__CONFIG(5,UNPROTECT);
__CONFIG(6,WRTEN);
__CONFIG(7,TRU);

#define _XTAL_FREQ   40000000


void delay_sec(unsigned char seconds)    // This function provides delay in terms of seconds
{
    unsigned char i,j;

    for(i=0;i<seconds;i++)
        for(j=0;j<100;j++)
            __delay_ms(10);
}
void led_display(char a)
{
    switch(a)
    {
        case 0: PORTB=0x01;PORTD=0x08;  break;
        case 1: PORTB=0x02;PORTD=0x04;  break;
        case 2: PORTB=0x04;PORTD=0x02;  break;
        case 3: PORTB=0x08;PORTD=0x01;  break;
    }
}

void main()
{
    TRISB=0x00;
    TRISD=0x00;
    char a,b;

    while(1)
    {
        led_display(a);

        a++;
        delay_sec(1);
        if(a==4)
        {
            a--;
        }
    }
}

Best Answer

You increment a every time and then you decrement it if a == 4. So a equals three in the beginning of you while-loop, then you increment it to four and decrement it, because it equals four. Now it is three again when you jump back to the start of loop.

Try something like:

bool directionForward == true;

while(1) {
    led_display(a);
    delay_sec(1);
    if(directionForward) {
        a++;
        if(a==4) directionForward = false;
    } else {
        a--;
        if(a==0) directionForward = true;
    }
}

And one other point: Try to avoid using this delay-function. Use a timer interrupt instead.