2
\$\begingroup\$

I had a problem with some code where I had to convert analog to digital using my PIC24HJ128GP506A microcontroller. As you may know, the microcontroller uses Successive Approximation for conversion, but I often got incorrect results.

After I implemented a small delay code, it solved my problem. However, I would like to understand: Why did the delay resolve the issue?

Code without Delay:

float readADC(unsigned int pin)
{
    _CH0SA = pin; 
    unsigned long tmpvalue = 0;
    float result = 0;
    
    for(int i=0;i<50;i++){   
        AD1CON1bits.SAMP = 1;    
        while (!AD1CON1bits.DONE); // Wait samp  
        AD1CON1bits.SAMP = 0;
        tmpvalue = tmpvalue + ADC1BUF0;
    }  

    result = tmpvalue / 50;   
    return result ;        
}

With delay :

float readADC(unsigned int pin)
{  
    _CH0SA = pin; 
    unsigned long tmpvalue = 0;
    float result = 0; 
  
    for(int i=0;i<50;i++){ 
        AD1CON1bits.SAMP = 1;    
        while (!AD1CON1bits.DONE); // Wait samp
        AD1CON1bits.SAMP = 0;
        tmpvalue = tmpvalue + ADC1BUF0;
        for(long i = 4500;i>0;i--);      // My delay
    }

    result = tmpvalue / 50;
    return result ;        
}
void configADC(void){  
    // AD1CON1
    _ADON = 0;
    _AD12B = 1;
    _FORM = 0;
    _SSRC = 7;
    _ASAM = 1; 
    _ADON = 1;

    // AD1CON2
    _VCFG = 0;  
    _SMPI = 0;

    //AD1CON3
    _ADRC = 1;  
    _SAMC = 4;  
    //AD1CHS0
    _CH0NA = 0;
    //_CH0SA = 0; 
    //INTERRUPT
    _NSTDIS = 1; 
    _AD1IF  = 0;  
    _AD1IE  = 0; 
    _AD1IP  = 2;  
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ btw this:result = tmpvalue / 50;is an pure integer conversion. You need a cast to float \$\endgroup\$
    – Mike
    Commented Jun 29, 2023 at 6:10
  • 1
    \$\begingroup\$ Have you switched ADCON1to auto conversion? Show your ADC init. \$\endgroup\$
    – Mike
    Commented Jun 29, 2023 at 6:12

1 Answer 1

0
\$\begingroup\$

The issue is probably the set-up time for the ADC. From the data sheet: enter image description here

It is possible that you could have a significant number of "indeterminate" readings during the 20 microseconds required to stabilize the ADC module. I would try adding a delay before your first reading, and then try reducing the time between reads and see if that helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.