Reading state of input pins on a PIC18

Ozzah picture Ozzah · Apr 5, 2012 · Viewed 19.1k times · Source

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 │-
     └────────┘

Answer

Adam Casey picture Adam Casey · Apr 5, 2012

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