Subversion Repositories Code-Repo

Rev

Details | Last modification | View Log | RSS feed

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