October 21, 2024
Chicago 12, Melborne City, USA
C#

Nested if statement in C not executing inner if


Struggling (newbie) with a nested if in C, probably doing something stupid.

Basically a switch down tester which determines whether just down for a second or longer.

void SwitchTest(void) 
{
    __delay_ms(3000);
    // LEDCOM = LED_ON;            // Connect Bar Common
    LED1 = LED_OFF; 
    LED2 = LED_OFF; 
    LED3 = LED_OFF; 
    LED4 = LED_OFF; 
    LED5 = LED_OFF; 
        
    if (PORTAbits.RA1 == 1)       // Is the Status Button pressed (high = no)
    { 
        GoSleep();                  // No, Sleep    
    }
    else if (PORTAbits.RA1 == 0)  
    {
        __delay_ms(1000);             // Yes, retest in 1 sec
        if (PORTAbits.RA1 == 1)       // Is the Status Button still pressed (low = yes)
        {
            LED1 = LED_ON;               // No, turn on LED1    
            __delay_ms(3000); 
            DisplayStep();                // No, display previous step    
        }
        else
        {    
            return;                       // Yes, resume main loop 
        }
    }  
}

The GoSleep() and return; parts work but the code for LED1 ON and DisplayStep() never occurs (yet it does seem to recognise that the switch was down for less than 1 second.

This code (asm) works

btfsc  PORTA,0         ; Is the switch pressed (0)
     goto   GoRest          ; No, sleep
     call   Wait0.5s        ; Yes, retest in 1sec
    ; call  Wait0.5s
     btfsc  PORTA,0         ; Is the switch still pressed (0)
     goto   DisplayStep     ; No, Display previous led_step
     return                 ; Yes, resume MainLoop



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video