Hiển thị Điện áp với ADC module



#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "lcd.h"
#define _XTAL_FREQ 4000000
// CONFIG1
#pragma config FOSC = HS      // Oscillator Selection bits (HS oscillator: High-speed crystal/resonator on RA6/OSC2/CLKOUT and RA7/OSC1/CLKIN)
#pragma config WDTE = OFF      // Watchdog Timer Enable bit (WDT disabled and can be enabled by SWDTEN bit of the WDTCON register)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = ON       // RE3/MCLR pin function select bit (RE3/MCLR pin function is MCLR)
#pragma config CP = OFF         // Code Protection bit (Program memory code protection is disabled)
#pragma config CPD = OFF        // Data Code Protection bit (Data memory code protection is disabled)
#pragma config BOREN = OFF      // Brown Out Reset Selection bits (BOR disabled)
#pragma config IESO = OFF       // Internal External Switchover bit (Internal/External Switchover mode is disabled)
#pragma config FCMEN = OFF      // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is disabled)
#pragma config LVP = OFF        // Low Voltage Programming Enable bit (RB3 pin has digital I/O, HV on MCLR must be used for programming)

// CONFIG2
#pragma config BOR4V = BOR40V   // Brown-out Reset Selection bit (Brown-out Reset set to 4.0V)
#pragma config WRT = OFF        // Flash Program Memory Self Write Enable bits (Write protection off)
// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.
unsigned int read_adc(){
    __delay_us(6);
    GO_nDONE=1;
    while(GO_nDONE==1);
    return (((unsigned int)ADRESH)<<8) |ADRESL;
}
void adc_init(){
    TRISA3=1;
    ANS3=1;
    ADCS1=0;ADCS0=1;
    VCFG1=0;VCFG0=0;
    CHS3=0;CHS2=0;CHS1=1;CHS0=1;//kenh AN3
    ADFM=1;//CANH TRAI
    ADON=1;//KICH HOAT ADC
    ADIF=0;
    GIE=PEIE=ADIE=0;
}
unsigned int mid_filter_adc(){
    unsigned char i,level_filter=100;
    unsigned long sum=0;
    for(i=1;i<=level_filter;i++)
    {
        sum=sum+read_adc();
    }
    return (sum/level_filter);
}

void main(void) {
   
    unsigned long adc_val;
    float voltage=0;
    ANSEL=0x08;
    ANSELH=0x00;
    TRISA3=1;
    lcd_init();
    adc_init();
    lcd_gotoxy(10,1);
    printf("(mV)");
    lcd_gotoxy(1,0);
    printf("Dig. Voltmeter");
    while(1)
    {
        adc_val=mid_filter_adc();//loc nhieu trung binh
        voltage=(adc_val*5.0f/1023);
//        milivolt=voltage*1000;
        lcd_gotoxy(4,1);
        printf("%3.2f",voltage*1000);
       
    }
}

Previous
Next Post »