PIC24FJ128GA610, ADC, need help

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Hi guys

I am trying to use the ADC in a PIC24, there are a few new register (AD1CHS and AD1CSS) that I have no idea what they do. And as you may guess, my code doesn't work. What have I done wrong??

Here is my code
Code:
// ADC
#define ADC1_TRIS   TRISBbits.TRISB14
#define ADC2_TRIS   TRISBbits.TRISB15
#define ADC1_ANS    ANSBbits.ANSB14
#define ADC2_ANS    ANSBbits.ANSB15

void InitADC(void){
    ADC1_TRIS = 1; // input, AN14 Tris
    ADC2_TRIS = 1; // input, AN15 Tris
  
    ADC1_ANS = 1; // analog input, 
    ADC2_ANS = 1; // analog input
  
    AD1CON1bits.FORM = 0; // unsigned, right justified
  
    AD1CON2bits.PVCFG = 0; // Vref+ = Vdd
    AD1CON2bits.NVCFG = 0; // Vref- = Vss
  
    // what is this, I simply can't find explanation about this sample A and sample B thing
    // so I simply set them to the sam analog that I need to do ADC read
    AD1CHSbits.CH0NA = 0;
    AD1CHSbits.CH0SA = 14; // 0b01110, AN14
  
    AD1CHSbits.CH0NB = 0;
    AD1CHSbits.CH0SB = 14; // 0b01110, AN14
  
    AD1CON3bits.ADRC = 1; // internal RC clock
  
    AD1CON3bits.SAMC = 0x0F; // auto-sample time
    AD1CON3bits.ADCS = 0x05; // A/D conversion clock
  
    AD1CON1bits.SSRC = 0b0111; // auto-convert mode
    //AD1CON1bits.SSRC = 0b0000; //SAMP is cleared by software
  
    // A/D input scan select register, don't know what it mean, assuming I need to enable 
    // the channel I want to do ADC on??
    AD1CSSLbits.CSS14 = 1; // enable AN14???
    //AD1CSSLbits.CSS15 = 1;
  
    AD1CON1bits.ADON = 1; // enable ADC
}

while(1){
  AD1CON1bits.SAMP = 1; // start sampling

  delay_ms(1000); // lots of delay for ADC to do conversion
                              //also give me lots of time to read the print out
 
    // my test code
    if (AD1CON1bits.DONE) {
        printf("ADC done\n");
        printf("ADC: %u\n", ADC1BUF0);
    }
    if (IFS0bits.AD1IF) {
        printf("ADC flag\n");
        printf("ADC: %u\n", ADC1BUF0);
        IFS0bits.AD1IF = 0;
    }
}
 

Thread Starter

bug13

Joined Feb 13, 2012
2,002
What does it do, or not do, that is not as desired?
In my code, I can never see AD1CONbits.DONE and IFS0bits.AD1IF set, so there was nothing printed out.

It's not my printf() function, as it print stuff fine on other part of the code. If I change my code around a little, the ADC reading is always 496, reading doesn't change if I change the voltage.

Code:
while(1){
  AD1CON1bits.SAMP = 1; // start sampling
  delay_ms(1000); // lots of delay for ADC to do conversion
                              //also give me lots of time to read the print out
    // my test code
    printf("ADC: %u\n", ADC1BUF0);
    if (AD1CON1bits.DONE) {
        printf("ADC done\n");
      
    }
    if (IFS0bits.AD1IF) {
        printf("ADC flag\n");
        IFS0bits.AD1IF = 0;
    }
}
 
Top