Reading from pins

As when writing to a pin, the pin must be configured correctly before it can be used. When reading from a pin it should be configured as an input. This is done by writing a 1 to the bit of the data direction register belonging to the port connected to the pin.

To read from pin 1 of a 16F84 lookup the label on pin 1 in the diagram. The label is RA2. This translates to PORTA bit 2. Set the corresponding bit in the PORTA data direction register TRISA to 1. This configures the pin as an input. Then read PORTA and mask out bit 2.

This can be done in XCSB as:

// set pin 1 as input
TRISA = TRISA | 0x02

// read pin 1 into temp
temp = PORTA & 0x02

// now temp will be 0 if RA2 was low and will be not 0 is RA2 was high.

// to convert temp to exactly 0 or 1 use:
temp = ((PORTA & 0x02) != 0)

The 0x02 value is a hex mask. A simpler way to access a bit within a byte is to use a constant expression of the form
(1 << n)
where n is the bit number (see bit masks for more information)

To read pin 17 use

TRISA = TRISA | (1 << 0)
temp = ((PORTA & (1 << 0)) != 0)
Although the expression
temp = ((PORTA & (1 << 0)) != 0)
may look complicated, the XCSB compiler will convert it to only 4 native PIC instructions.