ADC - First read is always wrong

Hi, 

I have been playing around with the nRF9160 DK trying to get it reading a range of sensors, so far with success, however I have found an issue which has stumped me. I am using ADC0 to read a voltage. Although this is intended for a pressure transducer, for debugging I have just put the 5V out through a resistive divider (10K / 10K) and the ADC successfully reads 2.5V. 

However, when the program is first run, the very first ADC reading is around 50. The next one, and all instances after, it reads correctly (around 3500 - using 3V VDD as reference and gain of 1/4, 12-bit resolution). 

I assumed this may be due to acquisition time, but I tried a few different values and nothing helped. 

I wont post the full code, but here is the config and read code

#define ADC_RESOLUTION 12
#define ADC_GAIN ADC_GAIN_1_4
#define ADC_REFERENCE ADC_REF_VDD_1_4
#define ADC_ACQUISITION_TIME ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 10)
#define ADC_1ST_CHANNEL_ID 0  
#define ADC_1ST_CHANNEL_INPUT NRF_SAADC_INPUT_AIN0

#define BUFFER_SIZE 1
static uint16_t m_sample_buffer[BUFFER_SIZE];

static struct adc_channel_cfg channel_cfg = {
	.gain 				= ADC_GAIN,
	.reference 			= ADC_REFERENCE,
	.acquisition_time 	= ADC_ACQUISITION_TIME,
	.differential 		= 0,
	.channel_id			= ADC_1ST_CHANNEL_INPUT ,
	.input_positive 	= SAADC_CH_PSELP_PSELP_AnalogInput0,
};

static int adc_sample(void)
{
	int ret;

		struct adc_sequence sequence = {
		.channels    = BIT(channel_cfg.channel_id),
		.buffer      = &m_sample_buffer,
		.buffer_size = sizeof(m_sample_buffer),
		.resolution  = ADC_RESOLUTION,
	};

	if (!adc_dev) {
		return -1;
	}

	ret = adc_read(adc_dev, &sequence);
	if (ret) {
        printk("adc_read() failed with code %d\n", ret);
	}

	for (int i = 0; i < BUFFER_SIZE; i++) {
                printk("ADC raw value: %d\n", m_sample_buffer[i]);
				uint32_t mV = (m_sample_buffer[i] *1000)*3/4096;	//n*1000*Reference (3V) / 12bit adc
				printk("ADC mV after Divider: %u\n", mV);
				mV = mV *2;
				printk("Voltage Sensed: %u\n", mV);
	}

	return ret;
}



//WITHIN MAIN

adc_dev = device_get_binding("ADC_0");
	if (!adc_dev) {
        printk("device_get_binding ADC_0 failed\n");
    } 
    NRF_SAADC_NS->TASKS_CALIBRATEOFFSET=1;
    err = adc_channel_setup(adc_dev, &channel_cfg);
    if (err) {
	    printk("Error in adc setup: %d\n", err);
	}
	
//END

The adc_sample() function is called when button 1 is pressed, but I'm sure that shouldnt make a difference. 

Thanks, 

Damien

Parents
  • I am a 20 plus year experienced hardware embedded design engineer.  When I have seen the symptoms like you described it is often caused because the ADC input has some capacitance (which is normal)... the first time you read the ADC the amount of time the capacitance is allowed to charge is too short and thus a low reading is achieved.. after two or three readings the capacitor is charged enough to have an accurate reading.  A great way to test this is to put a capacitor in parallel with the bottom (one connected to DC common often referred to as ground) resistor of your resistor divider.  This way the external capacitor you have just connected will be fully charged at the 2.5VDC level BEFORE the ADC samples.  Now the external capacitor charge can be delivered very quickly to charge the ADC capacitance and thus a correct reading can be acquired on the first attempt.  I normally use a 0.1 to 1 uF capacitor for this purpose but the value is not very critical (I would avoid anything in the pF range as the idea is to have lots of charge in the external capacitor versus the relatively small ADC capacitance (normally about 10 to 20 pF).

    What if your company has already made 10 million circuit board assemblies and they don't want to go back and add the extra capacitor to the design... what can you do?... two solutions that do NOT require an external capacitor are common.

    1) Do exactly what you stumbled upon... read twice and throw the first reading out! then use the second reading  OR

    2) If the ADC has a mux in front of it you can read a similar voltage on another channel first and then switch to your ADC channel as the internal capacitance charge will remain.  This only works IF you have a mux and a similar voltage on another channel (internal power rail is a common choice).

    Hope this helps.

     Dan

  • Hi Dan, 

    Thanks for the suggestion. I did wonder about capacitance on the input, but the voltage at the middle of the resistor divider is constant - meaning when I reset the device/program, it doesn't drop to 0V and need recharging, its powered but a constant source. I put a 1uF cap in parallel, and used an oscilloscope to measure it voltage during a read and it doesn't fluctuate at all, so I struggle to see how that can be the cause. 

    I realise I can do a double read and throw the first one, but I just wondered why this was in case there was something inherently wrong with my code/logic, which could become a larger issue later. 

    Thanks, 

    Damien

  • Hi,

    We have had the similar problem like this one. I tried what  suggested and it gave some errors on missing arguments. So I did it like this:

    ...
    	LOG_INF("nrf_saadc_task_trigger NRF_SAADC_TASK_STOP");
    	nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_STOP);
    	LOG_INF("nrf_saadc_event_check NRF_SAADC_EVENT_STOPPED");
    	while(!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STOPPED));
    	LOG_INF("nrf_saadc_task_trigger NRF_SAADC_TASK_CALIBRATEOFFSET");
    	nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_CALIBRATEOFFSET);
    	LOG_INF("nrf_saadc_event_check NRF_SAADC_EVENT_CALIBRATEDONE");
    	while(!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE));
    	LOG_INF("nrf_saadc_task_trigger NRF_SAADC_TASK_STOP");
    	nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_STOP);
    	LOG_INF("nrf_saadc_event_check NRF_SAADC_EVENT_STOPPED");
    	while(!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STOPPED));
    	LOG_INF("done");
    ...

    And it's getting stuck on NRF_SAADC_EVENT_CALIBRATEDONE.

    [00:00:01.773,071] [1B][0m<inf> adc_control: nrf_saadc_task_trigger NRF_SAADC_TASK_STOP[1B][0m
    [00:00:01.781,768] [1B][0m<inf> adc_control: nrf_saadc_event_check NRF_SAADC_EVENT_STOPPED[1B][0m
    [00:00:01.790,740] [1B][0m<inf> adc_control: nrf_saadc_task_trigger NRF_SAADC_TASK_CALIBRATEOFFSET[1B][0m
    [00:00:01.800,506] [1B][0m<inf> adc_control: nrf_saadc_event_check NRF_SAADC_EVENT_CALIBRATEDONE[1B][0m

    Earlier I had it like below and it was working but I'm not sure if I did it at the right way.

    ...
    	nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_CALIBRATEOFFSET);
    	nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE);
    	nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_STOP);
    	nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STOPPED);
    	nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START);
    ...

    I hope we could solve this issue.

    Regards,
    Tero

  • Hi Karl and Tero. 

    As Tero said, it does get stuck on the NRF_SAADC_EVENT_CALIBRATEDONE line. I tried what Tero had previously and that didn't work for me either. 

    Thanks, 

    Damien

  • Hello again Damien and Tero,

    Thank you for your patience with this.

    anicare-tero said:
    We have had the similar problem like this one. I tried what Karl Ylvisaker suggested and it gave some errors on missing arguments. So I did it like this:

    Yes, I wrote the section with the nRF5 SDK in mind, my mistake.

    anicare-tero said:
    Earlier I had it like below and it was working but I'm not sure if I did it at the right way.

    I am not sure that this will work, since the program counter will move on immediately after having triggered the task to cleared the event - regardless of the event actually having happened.

    DamoL said:
    As Tero said, it does get stuck on the NRF_SAADC_EVENT_CALIBRATEDONE line. I tried what Tero had previously and that didn't work for me either. 

    I just created a minimal NCS ADC example to test this on my end as well, and I notice that the same thing - the CALIBRATEDONE event never seems to occur. I am not immediately sure why this is happening - perhaps the calibrate done event is cleared somewhere else with a higher priority, so that the section here never sees the event, or similar.

    I will have a look into what is happening behind the scenes here tomorrow.

    Best regards,
    Karl

  • Hello again Damien and Tero,

    As mentioned I previously had the nRF5 SDK in mind when discussing this issue earlier. Looking into the NCS SAADC's irq handler it is apparent that the CALIBRATEDONE event is indeed cleared before the main context ever sees it. While this explains how the application is getting stuck waiting for the event, it does not unambiguously explain why you saw a change in the behavior after triggering the stop tasks before and after the calibrate done triggering.

    Could you try to add a delay in between your call to trigger calibration and the first sampling, to see if this then gives the SAADC sufficient time to finish calibration and the STOP task, before it is started again?
    If it is the Errata 86 at play, the driver's implementation of the workaround should take care of it as long as it is given time to finish before the first call.

    Best regards,
    Karl

  • Hi Karl, 

    Apologies I have been away for a few days. I have tried your suggestion. But do not see a change in behaviour. My current workaround is just using printk() between adc_read() and looking at the buffer. 

    ret = adc_read(dev, &sequence);
    	if (ret) {
            printk("adc_read() failed with code %d\n", ret);
    	}
    	else{
    
    		for (int i = 0; i < BUFFER_SIZE; i++) {
    					printk("Reading ADC\n");    //THIS ADDS SUFFICIENT DELAY
    					uint32_t mV = (m_sample_buffer[i] *1000)*3/4096;	//n*1000*Reference (3V) / 12bit adc
    					printk("ADC raw value: %d\n", m_sample_buffer[i]);
    					printk("ADC mV after Divider: %u\n", mV);
    					mV = mV *2;
    					printk("Voltage Sensed: %u\n", mV);
    		}
    	}
    For some reason this gives enough time for the buffer to be filled. If I comment out that line it reads correctly about 30% of the time.
    Thanks, 
    Damien
Reply
  • Hi Karl, 

    Apologies I have been away for a few days. I have tried your suggestion. But do not see a change in behaviour. My current workaround is just using printk() between adc_read() and looking at the buffer. 

    ret = adc_read(dev, &sequence);
    	if (ret) {
            printk("adc_read() failed with code %d\n", ret);
    	}
    	else{
    
    		for (int i = 0; i < BUFFER_SIZE; i++) {
    					printk("Reading ADC\n");    //THIS ADDS SUFFICIENT DELAY
    					uint32_t mV = (m_sample_buffer[i] *1000)*3/4096;	//n*1000*Reference (3V) / 12bit adc
    					printk("ADC raw value: %d\n", m_sample_buffer[i]);
    					printk("ADC mV after Divider: %u\n", mV);
    					mV = mV *2;
    					printk("Voltage Sensed: %u\n", mV);
    		}
    	}
    For some reason this gives enough time for the buffer to be filled. If I comment out that line it reads correctly about 30% of the time.
    Thanks, 
    Damien
Children
  • Hello again, Damien

    DamoL said:
    Apologies I have been away for a few days.

    No need to apologize - we will continue this whenever you have the chance.

    DamoL said:
    I have tried your suggestion. But do not see a change in behaviour. My current workaround is just using printk() between adc_read() and looking at the buffer. 
    DamoL said:
    For some reason this gives enough time for the buffer to be filled. If I comment out that line it reads correctly about 30% of the time.

    Thank you for trying this, and updating us on the results. I find this very strange. I will need to look deeper into this, and once I have done so I will escalate it to the SAADC driver's developer team so that they may examine my findings and patch it. I will update you as soon as I have got anything to share.

    Thank you for bringing this to our attention!

    Best regards,
    Karl

  • Hello again Tero and Damien,

    Thank you for your extreme patience with this issue. I have been out of office for some time, but now I am back in office and will resume work with this investigation.

    A colleague has conducted some tests on this in my absence and come to the conclusion that the incorrect sample is as expected as per the 9160's SAADC documentation, which reads:

    The ADC has a temperature dependent offset. If the ADC is to operate over a large temperature range, we recommend running CALIBRATEOFFSET at regular intervals. The CALIBRATEDONE event will be fired when the calibration has been completed. Note that the DONE and RESULTDONE events will also be generated.

    Which implies that a junk DONE and RESULTDONE event will be returned following a successful calibration. I will have to test this some more, to see if this might have been what is causing the behavior you have seen on your end as well. I have also noted that the implementation of the Errata 86 workaround in the adc_nrfx_saadc.c driver does not exactly follow the workaround detailed in the mentioned Errata 86 (namely, it does not wait for the appropriate events to be generated), which I am unclear on whether has played into this issue.

    Best regards,
    Karl

  • Hello again, Tero and Damien

    It seems that the incorrect sample does indeed stem from the calibrateoffset procedure - at least in my minimal NCS ADC test application.

    Damien, could you confirm whether you meant that the unexpected sample happens periodically without the added kprint delay, or only during startup of the SAADC peripheral? If it is periodically, could you possibly send me the stripped down version of the project (only adc parts needed) that you tested with along with which NCS version you used when you saw this behavior?

    Tero, does the previous discussion not explain the similar issue you saw/are seeing?
    If your issue now diverges from this issue, please open a separate ticket where you detail your issue.

    In any case, I thought I should let you both know that I have made an internal ticket with the SAADC driver developers to have the adc_nrfx_saadc driver's implementation of the errata 86 workaround reviewed, and to have it re-implemented to instead exactly match the workaround described in the errata 86 documentation.

    I have also opened an internal request to have this elaborated on and clarified in the nRF9160's SAADC Product Specification section, akin to that of the nRF5340's SAADC section or better.

    Best regards,
    Karl

  • Hi Karl, 

    Thanks for the update. 

    Damien, could you confirm whether you meant that the unexpected sample happens periodically without the added kprint delay, or only during startup of the SAADC peripheral?

    When I have the printk() it only happened the first time I tried reading. Without the printk() it happened fairly often. I don't have a copy of the original code as I was just playing around with it and trying out the libraries, etc. But it was essentially exactly what was in the original question of this post, with added printk() before reading the buffer. 

    main.c would look a bit like this;

    #include <drivers/adc.h>
    #include <hal/nrf_saadc.h>
    
    #define ADC_RESOLUTION 12
    #define ADC_GAIN ADC_GAIN_1_4
    #define ADC_REFERENCE ADC_REF_VDD_1_4
    #define ADC_ACQUISITION_TIME ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 10)
    #define ADC_1ST_CHANNEL_ID 0  
    #define ADC_1ST_CHANNEL_INPUT NRF_SAADC_INPUT_AIN0
    
    #define BUFFER_SIZE 1
    /* ADC Struct */
    static struct device *adc_dev;
    
    static uint16_t m_sample_buffer[BUFFER_SIZE];
    
    static struct adc_channel_cfg channel_cfg = {
    	.gain 				= ADC_GAIN,
    	.reference 			= ADC_REFERENCE,
    	.acquisition_time 	= ADC_ACQUISITION_TIME,
    	.differential 		= 0,
    	.channel_id			= ADC_1ST_CHANNEL_INPUT ,
    };
    
    static int adc_sample(void)
    {
    	int ret;
    
    		struct adc_sequence sequence = {
    		.channels    = BIT(channel_cfg.channel_id),
    		.buffer      = &m_sample_buffer,
    		.buffer_size = sizeof(m_sample_buffer),
    		.resolution  = ADC_RESOLUTION,
    	};
    
    	if (!adc_dev) {
    		return -1;
    	}
    
    	ret = adc_read(adc_dev, &sequence);
    	if (ret) {
            printk("adc_read() failed with code %d\n", ret);
    	}
    
    	for (int i = 0; i < BUFFER_SIZE; i++) {
                    printk("ADC raw value: %d\n", m_sample_buffer[i]);
    				uint32_t mV = (m_sample_buffer[i] *1000)*3/4096;	//n*1000*Reference (3V) / 12bit adc
    				printk("ADC mV after Divider: %u\n", mV);
    				mV = mV *2;
    				printk("Voltage Sensed: %u\n", mV);
    	}
    
    	return ret;
    }
    
    int adc_value=0;
    
    static void button_handler(uint32_t button_states, uint32_t has_changed)
    {	
    	if (has_changed & button_states &
    		BIT(0)) {
    		    adc_value = adc_sample();
    		    printk("Value - %i", adc_value);
    	}
    }
    
    void main(void)
    {
    	int err=0;
        adc_dev = device_get_binding("ADC_0");
    	if (!adc_dev) {
            printk("device_get_binding ADC_0 failed\n");
        } 
        NRF_SAADC_NS->TASKS_CALIBRATEOFFSET=1;
        err = adc_channel_setup(adc_dev, &channel_cfg);
        if (err) {
    	    printk("Error in adc setup: %d\n", err);
    	}
    	
    #if defined(CONFIG_DK_LIBRARY)
    	dk_buttons_init(button_handler);
    #endif
    	
    }

    As for the versio, it would have been V1.6.1 . 

    Thanks, 

    Damien

Related