/*
* File: ADC_Ver1
* Author: chris
* This is Basic ADC Code for the PIC12F1840 Series. Should be portable to others
* Created on August 19, 2013, 6:11 PM
*/
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <htc.h>
#define _XTAL_FREQ 8000000
#define RA5 (PORTAbits.RA5) //Charge LED
#define RA4 (PORTAbits.RA4) // PFET
#define __delay_us(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000000.0)))
#define __delay_ms(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000.0)))
#pragma config FOSC = INTOSC, CLKOUTEN = OFF, PLLEN = OFF, WDTE = OFF, LVP = OFF, MCLRE = ON
void SetupClock (void) //set up clock
{
OSCCON = 0b01110010;
}
void IntADC (void) //setup ADC
{
//** Initalise Ports FOR ADC **//
//PORTA = 0x00;
TRISA = 0b00001111; //RA4,RA5 outputs, RA0, RA1 Inputs
//** Set Up ADC Parameters **//
ANSELA = 0b00000111; //RA4 Output, RA5 Output, all others input
ADCON1 = 0b10010000; // Sets ADRESL to contain the first 7 bits of conversion, ADRESH will have the final 3 bits.
ADCON0bits.ADON = 1;
} // void InitADC(void)
int ReadADC(unsigned char ch)
{
int ret = 0;
ADRESH = 0;
ADRESL = 0;
ADCON0 = 0b10000001 + (ch<<3); // set channel to read
__delay_ms (25);
ADCON0bits.GO = 1; // start conversion
while(ADCON0bits.GO_nDONE); // wait for conversion
ret = (ADRESH & 0x3) << 8; // get
ret += ADRESL; // result
return ret;
}
void main (){
SetupClock();
IntADC();
unsigned int Vcharge;
unsigned int Vcurrent;
unsigned int Vbattery;
Vcharge = 0;
Vcurrent = 0;
Vbattery = 0;
while (1){
Vcharge = ReadADC(0);
__delay_ms(100);
Vcurrent = ReadADC(1);
if (Vcharge >512)
{
RA4 = 1;
}
else
RA4 = 0;
if (Vcurrent > 512 )
{
RA5 = 1;
}
else
RA5 = 0;
}
}