1

I am running the below-given program but the problem is that for loop runs only once and turns on the LED and then Turns OFF. It should run for 5 times. Below is the code:

void led(void)
{
    RB0=~RB0;
    __delay_ms(delay);
    RB0=~RB0; 
}

void main(void) 
{
    ANSEL = 0;                        //Disable Analog PORTA
    TRISA0 = 1;                       //Make RA0 as Input
    TRISB = 0x00;
    PORTA = 0;
    PORTB = 0x01;
     // RB0=0;
     while(1)
     {
         //Switch Pressed
         if(swch==0)                      //Check for Switch Pressed
         {
             __delay_ms(delay_debounce);   //Switch Debounce Delay
             if(swch==0)                      //Check again Switch Pressed                     
             { 
             //Blink LED at PORT RB0    
                 for (int i = 0; i < 2; i++)
                 {
                     led();   
                 }
             }
         }
         else if(swch==1)
         {
             //Do Nothing    
         }
     }
     return;
 }

2 Answers 2

0

It actuality the LED turns on and off 5 2 times (see code), it just happens so fast that it looks like it's happening once. This is because there is no delay between where you turn it off and on again. Add this little snippet to your code:

//other code...

for(int i=0;i<2;i++)   // The 2 here means the LED will only flash twice!
{
    led();   
    __delay(500);
}

// other code...
Sign up to request clarification or add additional context in comments.

Comments

0

If you expand out what you are doing in the loop, it becomes

RB0=~RB0;
__delay_ms(delay);
RB0=~RB0; 
// No delay here before it switches back
RB0=~RB0;
__delay_ms(delay);
RB0=~RB0; 
RB0=~RB0;
__delay_ms(delay);
RB0=~RB0;

Notice that there is no delay between the LED changing states when it leaves the routine. Add another delay after changing the state.

void led(void)
{
    RB0=~RB0;
    __delay_ms(delay);
    RB0=~RB0; 
    __delay_ms(delay);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.