Subversion Repositories Code-Repo

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
147 Kevin 1
#include "defines.h"
119 Kevin 2
#include "adc.h"
3
 
123 Kevin 4
static ADC_DATA adc_data;
128 Kevin 5
static ADC_DATA *adc_data_p = &adc_data;
123 Kevin 6
 
7
void ADC_Init(unsigned char TAD, unsigned char FOSC) {
129 Kevin 8
    ADC_AN0_TRIS = 1;
9
    ADC_AN1_TRIS = 1;
10
    ADC_AN2_TRIS = 1;
123 Kevin 11
 
128 Kevin 12
    adc_data_p->last_channel = 0;
13
    adc_data_p->result = 0;
123 Kevin 14
 
15
    ADCON0bits.VCFG1 = 0; // VRef- = AVss
126 Kevin 16
    ADCON0bits.VCFG0 = 1; // VRef+ != AVdd
123 Kevin 17
    ADCON1bits.ADFM = 1; // Right justified result
18
    ADCON1bits.ADCAL = 1; // Calibrate A/D
19
    ADCON1bits.ACQT = TAD;
20
    ADCON1bits.ADCS = FOSC;
21
    ADCON0bits.ADON = 1; // Enable A/D module
22
 
23
    ADCON0bits.GO_DONE = 1; // Start calibration
24
    while (ADCON0bits.GO_DONE); // Wait for calibration to finish
25
    PIR1bits.ADIF = 0;  // Clear the IF flag
26
    ADCON1bits.ADCAL = 0; // Normal A/D operation
27
 
28
    PIE1bits.ADIE = 1; // Enable A/D interrupt
29
 
119 Kevin 30
}
31
 
123 Kevin 32
void ADC_Start(unsigned char channel) {
128 Kevin 33
    adc_data_p->last_channel = channel;
123 Kevin 34
    ADCON0bits.CHS = channel; // Set A/D channel
35
    ADCON0bits.GO_DONE = 1; // Start A/D conversion
119 Kevin 36
}
37
 
123 Kevin 38
void ADC_Stop() {
39
    ADCON0bits.ADON = 0; // Disable A/D module
119 Kevin 40
}
41
 
123 Kevin 42
void ADC_Interrupt_Handler() {
128 Kevin 43
    adc_data_p->result = ADRES;
123 Kevin 44
}
45
 
46
char ADC_Get_Result(unsigned int* ret) {
47
    if (ADCON0bits.GO_DONE) {
48
        return 0;
49
    } else {
128 Kevin 50
        *ret = adc_data_p->result;
123 Kevin 51
        return 1;
52
    }
119 Kevin 53
}