/****************************************************************
* Description : ket noi bien tro voi chan RA3 de chuyen doi ADC :
* RA3 < 2.5v thi RB0 = 1
* RA3 > 2.5v thi RB0 = 0
* hien thi dien ap len LCD
* Tool : HI-TECH PIC
* Chip : 16F887
****************************************************************/
#include <htc.h>
#include "lcd.h"
__CONFIG(XT & WDTDIS & PWRTEN & MCLREN & UNPROTECT & SWBOREN
& IESODIS & FCMDIS & LVPDIS & DEBUGDIS);
__CONFIG(BORV21);
#define _XTAL_FREQ 4000000
/****************************************************************/
void port_init()
{
ANSEL = 0x08; //user ADC channel AN3
ANSELH = 0; //AN8 - 13 la digital
TRISA3 = 1; //RA3 la input
TRISB0 = 0; //RB0 là output
RB0 = 1;
}
/****************************************************************/
void ADC_init()
{
// ADC convertion clock = Fosc/8
ADCS1 = 0;
ADCS0 = 1;
// voltage referent : internal Vref
VCFG1 = 0;
VCFG0 = 0;
// select input channel : AN3
CHS3 = 0;
CHS2 = 0;
CHS1 = 1;
CHS0 = 1;
// result format : right
ADFM = 1;
// turn on ADC module
ADON = 1;
// delay to wait for ADC module init
__delay_ms (1);
}
/***************************************************************/
// interrupt initialization
void ini_init()
{
GIE = 1; // NGAT TOAN CUC
PEIE = 1; // NGAT NGOAI VI
ADIE = 1; // NGAT ADC
ADIF = 0; // XOA CO NGAT ADC
}
//----------------------------------------------------------------
// chuyen so de hien thi
void ADC_lcd(long i)
{
char a, b, c, d;
// tach hang ngan, tram, chuc, don vi
a = i / 1000;
b = (i - 1000*a)/ 100;
c = (i - 1000*a - 100*b)/ 10;
d = i - 1000*a - 100*b - 10*c;
//HIEN THI LEN LCD
lcd_puts("Vin = ");
lcd_gotoxy(7,0);
lcd_putc(a + 0x30);
lcd_puts(".");
lcd_putc(b + 0x30);
lcd_putc(c + 0x30);
lcd_putc(d + 0x30);
lcd_puts(" V");
unsigned char j=0;
for(;j<10;j++) __delay_ms(100);
}
/****************************************************************/
// interrup service rountine (thu tuc ngat)
void interrupt sir()
{
long ADC_result;
if (PEIE && ADIE && ADIF)
{
ADIF= 0;
//READ ADC RESULT
ADC_result = (ADRESH<<8)| ADRESL; //=ADRESH*256+ADRESL;
ADC_result=ADC_result*5*1000/1024;
ADC_lcd(ADC_result);
if (ADC_result > 2500)
{RB0 = 0;}
else {RB0 =1;}
}
}
/****************************************************************/
void main()
{
port_init();
ADC_init();
ini_init();
lcd_init();
while(1)
{
__delay_us(50);
lcd_clear(); //delay between 2 AD conversions
GODONE =1; //set GODONE bit to start conversions
}
}
/****************************************************************
* END OF ADC led main.c
****************************************************************/