1

我正在将一个开关连接到 PIC,并且我想读取该开关。我正在使用 PIC18F4580。如果输入引脚为低电平,则它将打开连接到另一个引脚的 LED,配置为输出。但是,LED 一直亮着,开关按钮没有任何作用。这是我的代码:

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
            }
        }
  }

}

我不知道该怎么做。我已经为开关按钮使用了上拉电阻,所有硬件都应该是正确的。任何帮助深表感谢。

4

2 回答 2

1

程序永远不会到达语句

        PORTD.F1=0;                 //Turn off LED

尝试类似:

   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
        }
    }
于 2018-03-22T14:28:10.230 回答
1

使用 LAT (LATD) 而不是 PORT (PORTD) 来更改输出

请参阅: PIC 18F 上的 PORT 和 LATCH 之间的区别

于 2018-03-22T14:02:16.527 回答