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