Search code examples
cmplabxc8mplab-x

If condition does not work in Microchip MPLAB IDE XC8 compiler


/*
 * File:   proje_6.c
 * Author: ayanoglu
 *
 * Created on 08 Nisan 2023 Cumartesi, 12:14
 */


#include <xc.h>

void delayFunction(unsigned int);

#define Button PORTBbits.RB0   //RB0 button

#define Led PORTBbits.RB1       //RB1 led

char Counter = 0;



void main(void) {
  
    TRISBbits.TRISB0 = 1;
    TRISBbits.TRISB1 = 0;


    
    if (Button==1){
        Counter++;
        
        
        if ((Counter !=0) && (Counter %10 == 0)){
            Led = 1;
            delayFunction(200);
            Led = 0;

        }
        
    }
    while(1);
    
    
    
    
    
}

void delayFunction(unsigned int itime){
    unsigned int i;
    unsigned char j;
    for (i=0;i<itime;i++){
        for(j=0;j<165;j++);
    }
}

I use P18F45K22

I want the led to turn on and turn off after a while when the number reaches tens(10,20,30..) but I can't get into the if statement.

pin RB0 as a button and pin RB1 as a led

counter should increase as I press the button


Solution

  • You would need something like:

    #include <xc.h>
    #include <libpic30.h>  //For __delay32(...)
    
    #define Button PORTBbits.RB0   //RB0 button
    
    #define Led PORTBbits.RB1       //RB1 led
    
    void main(void) {
        INT8 Counter = 0; //char can be used on PIC's but nicer with an int  
    
        TRISBbits.TRISB0 = 1; //Input
        TRISBbits.TRISB1 = 0; //Output
    
        while(1) { //Loop forever....
    
         if (Button==1){ //Assuming here that the button toggles, no bounce, etc.
    
          Counter++;
                 
            if ((Counter !=0) && (Counter %10 == 0)){
                Led = 1;
                __delay32(80000); //Delay 20 milliseconds to stabilise power supply 
                //*See note below... 
                Led = 0;
    
            }
        }    
    }
    

    *The __delay32() is a Microchip delay function. The parameter of 80000 was calculated for my system, yours might be different.