ADC initialization

Sir,
I have used arduino's built in function analogRead(). But in one project from Arduino ProjectHub(https://create.arduino.cc/projecthub/plouc68000/ardutester-v1-13-the-arduino-uno-transistor-tester-dbafb4), the author initialized ADC as conventional AVR initialization.

#define ADC_CLOCK_DIV         (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0)
#define CPU_FREQ              F_CPU
#define OSC_STARTUP           16384
ADCSRA = (1 << ADEN) | ADC_CLOCK_DIV;

Is there any benefit for this over builtin analogRead()
Please help me........ :confused:

1. int x = analogRead(A0); instructions involves the following subtasks:
(1) Analog Channel-0 is selected with the hep of ADMUX Register
(2) VREF voltage (default 5V) is selected with the help of ADMUX Register.
(3) 125 kHz ADC Clock is selcted with the help of ADCSRA Register.
(4) ADC is enabled with the help of ADCSRA Register.
(5) ADC is started with the help of ADCSRA Register.
(6) Keeps checking if the conversion is done with the help of ADCSRA Register.
(7) After conversion, the ADC value is brought into variable x.

2. The 2 register level codes that you have mentioned selects ADC Clock at 125 kHz and enables the ADC.

This may explain it better than I can.

The Arduino ecosystem is intended to make programming microcontrollers accessible to non-experts (whatever that means). As such the programming model abstracts some of the low level details of controlling the microcontroller peripherals. It is also intended to provide a common programming model across a range of microcontroller devices.

A consequence of this is that the ADC peripheral on any specific microcontroller has configurations and features which are not accessible via the simple "analogRead()" abstraction. If one wants to use such a configuration it is necessary to use a application interface that supports it. In this case the developer has used direct register manipulation which is straightforward but not portable across microcontroller types. There also exist AVR libraries that are portable across multiple devices but with finer control than "analogRead()".

For the ADC in particular there are common instances where using analogRead() is sub-optimum including at least the following:

  • Faster sampling rate - change ADC clock speed
  • Strictly uniform sampling - use ADC continuous sampling mode
  • Non-blocking - start ADC conversion cycle, go off and do other work, then retrieve ADC reading when it is complete

MrMark:
Non-blocking - start ADC conversion cycle, go off and do other work, then retrieve ADC reading when it is complete[...]

I think that 'int x = analogRead(A0);' is a blocking code -- it keeps checking the 'EOC' status.

SteveMann:
This may explain it better than I can.

Sometimes a summary much better which can be made by repetitive study of the text.