Pergunta

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 │-
     └────────┘
Foi útil?

Solução

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

Outras dicas

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.

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top