Subversion Repositories Code-Repo

Rev

Rev 128 | Rev 147 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#include "maindefs.h"
#include "adc.h"

static ADC_DATA adc_data;
static ADC_DATA *adc_data_p = &adc_data;

void ADC_Init(unsigned char TAD, unsigned char FOSC) {
    ADC_AN0_TRIS = 1;
    ADC_AN1_TRIS = 1;
    ADC_AN2_TRIS = 1;

    adc_data_p->last_channel = 0;
    adc_data_p->result = 0;

    ADCON0bits.VCFG1 = 0; // VRef- = AVss
    ADCON0bits.VCFG0 = 1; // VRef+ != AVdd
    ADCON1bits.ADFM = 1; // Right justified result
    ADCON1bits.ADCAL = 1; // Calibrate A/D
    ADCON1bits.ACQT = TAD;
    ADCON1bits.ADCS = FOSC;
    ADCON0bits.ADON = 1; // Enable A/D module

    ADCON0bits.GO_DONE = 1; // Start calibration
    while (ADCON0bits.GO_DONE); // Wait for calibration to finish
    PIR1bits.ADIF = 0;  // Clear the IF flag
    ADCON1bits.ADCAL = 0; // Normal A/D operation

    PIE1bits.ADIE = 1; // Enable A/D interrupt

}

void ADC_Start(unsigned char channel) {
    adc_data_p->last_channel = channel;
    ADCON0bits.CHS = channel; // Set A/D channel
    ADCON0bits.GO_DONE = 1; // Start A/D conversion
}

void ADC_Stop() {
    ADCON0bits.ADON = 0; // Disable A/D module
}

void ADC_Interrupt_Handler() {
    adc_data_p->result = ADRES;
}

char ADC_Get_Result(unsigned int* ret) {
    if (ADCON0bits.GO_DONE) {
        return 0;
    } else {
        *ret = adc_data_p->result;
        return 1;
    }
}