Reading input pin of PIC18F

599 Views Asked by At

I am connecting a switch to PIC and I want to read that switch. I am using PIC18F4580. If the input pin is Low, then it will turn on an LED connected to another pin, configured as output. However, the LED keeps on the whole time, and the switch button has no effect. This is my code:

void main() 
{
    IRCF2_bit = 1;    //Internal 8MHz Oscisllator Configuration
    IRCF1_bit = 1;
    IRCF0_bit = 0;
    INTSRC_bit = 1;
    PLLEN_bit = 0;
    TRISD0_bit = 1;    //Switch connected to D0 and pin configured as input
    TRISD1_bit = 0;     //LED connected to D1 and pin configured as output 
    PORTD.F1=0;        //Turn off LED

    while(1) 
    {

        if (PORTD.F0==0) 
        {     
            //If Switch is pressed
            delay_ms(100);          //switch debounce

            if (PORTD.F0==0) 
            {
                PORTD.F1=1;           //Turn on LED
            }
            else 
            {
                PORTD.F1=0;                 //Turn off LED
            }
        }
  }

}

I am clueless on what to do. I have used Pull up resistors for the switch button, and all the hardware should be correct. Any help is much appreciated.

2

There are 2 best solutions below

0
On

use LAT (LATD) instead of PORT (PORTD) to make changes to output

see: Difference between PORT and LATCH on PIC 18F

0
On

The program will never reach the statement

        PORTD.F1=0;                 //Turn off LED

Try something like:

   while(1) 
   {
       if (PORTD.F0==0) 
       {     
           //If Switch is pressed
           delay_ms(100);          //switch debounce
           PORTD.F1=1;           //Turn on LED
        }
        else
        {
            PORTD.F1=0;                 //Turn off LED
        }
    }