Consider the Arduino code below that reads an analog value from pin A0 and prints it. What will be printed if the input voltage on A0 is 2.5V and the Arduino uses a 5V reference?
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(1000);
}Think about how analogRead() converts voltage to a number between 0 and 1023 based on a 5V reference.
analogRead() returns a value from 0 to 1023 representing 0V to 5V. For 2.5V, the value is about half of 1023, which is approximately 512.
In Arduino, what value does analogRead() return if the input voltage on the analog pin is 0 volts?
Think about the lowest voltage and its corresponding ADC value.
0 volts corresponds to the lowest ADC value, which is 0.
This Arduino code reads an analog value and converts it to voltage. What will be printed if analogRead(A0) returns 820?
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = 820;
float voltage = sensorValue * (5.0 / 1023.0);
Serial.println(voltage, 2);
delay(1000);
}Calculate voltage by multiplying sensorValue by (5.0 / 1023.0).
Voltage = 820 * (5.0 / 1023.0) ≈ 4.0078, which rounds to 4.01 when printed with 2 decimal places.
Look at the code below. It always prints 0 even when the input voltage changes. What is the cause?
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue;
analogRead(A0);
Serial.println(sensorValue);
delay(1000);
}Check if the variable stores the analogRead() result.
sensorValue is declared but never assigned the value from analogRead(A0). So it prints the default 0.
Which of the following Arduino code snippets will cause a syntax error?
Check the syntax of function calls in C++.
Function calls require parentheses around arguments. Option A misses parentheses, causing a syntax error.
