Using analogRead

Hi!

I've recently got an Arduino nano board with the mega 328 mcu. I've been doing basic tutorials, by executing a analog reading with the board I got two questions:

Code:

int ADC_pin = A0;

void setup() {
Serial.begin(9600);
}

void loop() {
int ADC_read = analogRead(ADC_pin);
float Voltage_read = ADC_read*(5.0/1023.0);
Serial.println(Voltage_read);
}

Question 1

At the local variable, it directly gets the value from the periferal:

int ADC_read = analogRead(ADC_pin);

Since any ADC setup has never been done at the setup() function, I'm thinking that maybe using pin A0 as ADC input is a default configuration of the device.

Or maybe the analogRead function makes that configuration when it's called, which I think is not the case because it seems to be a function that fits on loops (?)

Question 2

By using

float Voltage_read = ADC_read*5/1023;

It seems quite enough for printing the voltage value in the float format, it's not enough, it prints intergers at the arduino monitor.

With float Voltage_read = ADC_read5/1023; it prints intergers
With float Voltage_read = ADC_read
(5/1023); it always print 0.00

What it's working for me is:

float Voltage_read = ADC_read*(5.0/1023.0);

Why?

Thanks for reading :slight_smile:

The analogRead() function does any needed initialization of the analogue pin.

This style float Voltage_read = ADC_read*(5/1023); does integer division and that means 5 / 1023 gives 0.

This style (with decimals) float Voltage_read = ADC_read*(5.0/1023.0); tells the compiler to do a floating point division.

...R

Since any ADC setup has never been done at the setup() function, I'm thinking that maybe using pin A0 as ADC input is a default configuration of the device.

Setting up the ADC is done by the init() function that you have no control over.

By using

float Voltage_read = ADC_read*5/1023;

It seems quite enough for printing the voltage value in the float format, it's not enough, it prints intergers at the arduino monitor.

Since ADC_read, 5, and 1023, are all integers, the calculation is done using integer arithmetic, as expected. That the result is to be stored in a float is irrelevant.

Robin2:
The analogRead() function does any needed initialization of the analogue pin.

Can I change the sample rate or bit resolution?

Robin2:
This style (with decimals) float Voltage_read = ADC_read*(5.0/1023.0); tells the compiler to do a floating point division.

Thanks a lot! now I understand :slight_smile:

Tebi:
Can I change the sample rate or bit resolution?

The sample rate depends on how often you call analogRead().

You can reduce the resolution for higher sampling rates but you need to read the Atmel datasheet to see how that is done.

How many samples per second do you need?

...R