Reading state of input pins on a PIC18

我怕爱的太早我们不能终老 提交于 2020-01-02 09:44:47

问题


I have been able to get outputs working on my PIC and can make a bunch of LEDs dance on and off as I set various output latches high/low. However, I'm having a lot o difficulty reading in the state of a pin.

See the code below. I set up my config, and define the TRISC as input and TRISB as output. In an infinite loop, I check to see whether RC6 is high or low, and set the entire B latch high or low depending on the result.

#include <htc.h>

__CONFIG(1, FOSC_IRC   & FCMEN_OFF & IESO_OFF);
__CONFIG(2, PWRTEN_OFF & BOREN_OFF & WDTEN_OFF);
__CONFIG(3, MCLRE_OFF);
__CONFIG(4, STVREN_ON  & LVP_OFF   & DEBUG_OFF);
__CONFIG(5, 0xFFFF);
__CONFIG(6, 0xFFFF);
__CONFIG(7, 0xFFFF);

void main(void)
{
  TRISC = 0xFF; // input
  TRISB = 0x00; // output

  while (1)
  {
    if (PORTCbits.RC6 == 0)
      LATB = 0b00000000;
    else
      LATB = 0b11111111;
  }

  return;
}

The code compiles fine with no warnings or errors. If my code logic is simply setting latches high and low then that works fine, but I haven't been able to successfully read the state of a pin.

Any ideas?

I'm using a PIC18F14K50 and MPLAB v8.43 and the HiTech ANSI C Compiler.

My connections are +5V to the VDD (pin 1), VSS (pin 20) to ground. I have +5V to C6 (pin 8), and a 100K resistor and LED from B7 (pin 10) to ground. To toggle RC6, I connect/disconncet the wire to C6.

     ┌────────┐
+5v -│ 01  20 │- gnd
    -│ 02  19 │-
    -│ 03  18 │-
    -│ 04  17 │-
    -│ 05  16 │-
    -│ 06  15 │-
    -│ 07  14 │-
+5v -│ 08  13 │-
    -│ 09  12 │-
led -│ 10  11 │-
     └────────┘

回答1:


The ADC pins on the PICs unfortunately are configured as analog inputs on powerup. You need to disable the ADC functionality on that pin to use it as a digital input.

Clearing bit 0 of ANSELH will set RC6 to digital input. Then your code will work.

This is documented in the datasheet in section 9.4 : Port Analog Control

PIC18F/LF1XK50 Datasheet




回答2:


Setting...

TRISC = 1; // input

...should set only pin RC0 of PORTC as input pin, all other pins are defined as output. So PORTCbits.RC6 == 0 should not return correct input state of in RC6 pin.

TRISC = 255 should set all pins of PORTC as input.




回答3:


It is worth mentioning that some other PIC18 variants are set up differently:

On PIC18F4520 and PIC18F4680 you need to configure pins as digital it trough a ADCON1 register instead of ANSELH.

Setting a bit to 1 will make a pin digital.

Besides this you need to make them input pins by setting a bit to 1 in the corresponding TRIS register.



来源:https://stackoverflow.com/questions/10020506/reading-state-of-input-pins-on-a-pic18

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!