user6569498
user6569498

Reputation: 23

Need to read analog input to a pic16f688 using mplab and xc8 compiler

I am using a PIC16f688 to try to read analog input and to turn a light on or off based on the voltage read. Using this PIC, I have successfully gotten the light to blink using on and off. Here is the code I used for that.

void main() {
    ANSEL = 0b00000000; //All I/O pins are configured as digital
    CMCON0 = 0x07; // Disbale comparators
    TRISC = 0b00000000; // PORTC All Outputs
    TRISA = 0b00001000; // PORTA All Outputs, Except RA3

    do {
        RC0 = 1;
        __delay_ms(500); 
        RC0 = 0;
        __delay_ms(500);
    } while (1); // Infinite Loop
}

After reading different things I ended up with this code to try to read the analog input.

#pragma config FOSC = HS      // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF     // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF    // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = OFF    // Brown-out Reset Enable bit (BOR disabled)
#pragma config CPD = OFF      // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
#pragma config CP = OFF       // Flash Program Memory Code Protection bit (Code protection off)


#include <xc.h>
#include <pic16f688.h>
#define _XTAL_FREQ 8000000
void main() {
    int voltage;
    ANSEL = 0b01000000; //All I/O pins are configured as digital except an6/RC2
    TRISC = 0b00000100; // PORTC All Outputs except RC2
    TRISA = 0b00001000; // PORTA All Outputs, Except RA3

    do {
        ADCON0 = 0xbb; //set to read
        GO_nDONE = 1;
        while(GO_nDONE == 1);
        voltage = (ADRESH << 8) + ADRESL; //get voltage reading
        if(voltage > 500){ //if voltage is greater than 500 out of 1023 turn light on
            RC0 = 1;
        }
        else{
            RC0 = 0;
        }
        __delay_ms(500);
    } while (1); // Infinite Loop
}

When I run this, the light is on no matter what the input is, including when the input is wired to ground.

I am using XC8 compiler in MPLab.

Upvotes: 2

Views: 940

Answers (2)

GJ.
GJ.

Reputation: 10937

I hope that you are using external oscillator otherwise you have set wrong internal oscillator!

Default ADC clock is Fosc/2 and is to high for 8Mhz, so set the ADCON1 to Fosc/16 check datasheet.

Why did you remove this line?

CMCON0 = 0x07; // Disbale comparators

It is essential!

Upvotes: 0

Arun Kumar
Arun Kumar

Reputation: 245

Try disabling the comparators using CMCON0 = 0x07; then RC0 should function normally.

Upvotes: 0

Related Questions