需要使用 mplab 和 xc8 编译器将模拟输入读取到 pic16f688

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

我正在使用 PIC16f688 尝试读取模拟输入并根据读取的电压打开或关闭灯。使用这张图片,我已经成功地让灯通过开关来闪烁。这是我为此使用的代码。

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
}

在阅读了不同的东西之后,我最终得到了这段代码来尝试读取模拟输入。

#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
}

当我运行这个时,无论输入是什么,灯都会亮,包括当输入接地时。

我在 MPLab 中使用 XC8 编译器。

尝试使用 CMCON0 = 0x07 禁用比较器;那么 RC0 应该可以正常运行。

希望您使用的是外部振荡器,否则您设置错误的内部振荡器!

默认的 ADC 时钟是 Fosc/2 并且对于 8Mhz 来说是高电平,因此将 ADCON1 设置为 Fosc/16 检查数据表。

为什么要删除这一行?

CMCON0 = 0x07; // Disbale comparators

必不可少!