Beginner PIC I/O (16F887, MPLAB, Hi-Tech C)

Thread Starter

Recon

Joined Oct 16, 2009
30
I am trying to write a basic program to turn on an LED when an input is high. I managed to make an LED flash thanks to people on this forum :), but I'm having trouble with my next simple program.

LED Flashing Program (works)
Rich (BB code):
#include "htc.h"
#define _XTAL_FREQ 4000000

__CONFIG(FOSC_INTRC_NOCLKOUT & WDTE_OFF & PWRTE_ON & MCLRE_ON & CP_OFF & CPD_OFF & BOREN_OFF & IESO_OFF & FCMEN_OFF & LVP_OFF & DEBUG_OFF & BOR4V_BOR40V & WRT_OFF);

int main(void) {

	TRISA = 0b11111110; //RA0 is output, others are inputs

 	for(;;) {
        	RA0 = 1;    
        	__delay_ms(100);
		__delay_ms(100);
      		RA0 = 0; 
		__delay_ms(100);
		__delay_ms(100);
	}
}
LED I/O Program (doesn't work)
Rich (BB code):
#include "htc.h"
#define _XTAL_FREQ 4000000

__CONFIG(FOSC_INTRC_NOCLKOUT & WDTE_OFF & PWRTE_ON & MCLRE_ON & CP_OFF & CPD_OFF & BOREN_OFF & IESO_OFF & FCMEN_OFF & LVP_OFF & DEBUG_OFF & BOR4V_BOR40V & WRT_OFF);

int main(void) {

	TRISA = 0b11111110; //RA0 is output, others are inputs

 	for(;;) {
		if(RA1 == 1){
		RA0 = 1; 
		}
		else {
		RA0 = 0; 
		}
	}
}
I am making RA1 "high" by connecting it to +v through a 10k resistor. Is this correct?
 

t06afre

Joined May 11, 2009
5,934
On every PIC with analog functions on pins. These pins will default to analog functions after power up. And here comes the downside of this. Then using PORTA
The ANSEL register must be initialized to configure an analog channel as a digital input. Pins configured as analog inputs will read ‘0’.​
Then working with PICs it is very important to have the datasheet at hand all the time. You do not have to read from start to finish. But then you use any functions. As in your case PORTA. You must confer with the datasheet. To be sure everything is set up correct. If you move to PORTD or PORTE your setup should work as is. If you use PORTA. You must insert the line​
Rich (BB code):
ANSEL=0;​
Before the endless loop​
 

Thread Starter

Recon

Joined Oct 16, 2009
30
Thanks, t06afre, that worked. :D

I use the datasheet as much as I can, but admittedly a lot of it is still over my head. :rolleyes:
 
Top