【问题标题】:Need to read analog input to a pic16f688 using mplab and xc8 compiler需要使用 mplab 和 xc8 编译器读取 pic16f688 的模拟输入
【发布时间】:2016-07-09 19:39:19
【问题描述】:

我正在使用 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 编译器。

【问题讨论】:

  • 您的振荡器配置是什么?看门狗定时器是打开还是关闭?
  • #define _XTAL_FREQ 8000000 所以根据这条线将振荡器设置为8MHz。提交后,我将在预处理器中进行编辑。看门狗定时器已关闭。
  • 您是否使用外部振荡器?

标签: pic mplab xc8


【解决方案1】:

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

默认 ADC 时钟为 Fosc/2,8Mhz 为高电平,因此将 ADCON1 设置为 Fosc/16,查看数据表。

为什么要删除这一行?

CMCON0 = 0x07; // Disbale comparators

这是必不可少的!

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多