Consider this Arduino sketch snippet that reads a sensor value and checks for errors. What will be printed to the serial monitor?
int sensorValue = analogRead(A0); if (sensorValue < 0) { Serial.println("Error: Sensor read failed"); } else { Serial.print("Sensor value: "); Serial.println(sensorValue); }
analogRead returns values from 0 to 1023. Negative values do not occur.
analogRead returns a value between 0 and 1023. It never returns negative values, so the error condition is never true. The code prints the sensor value, which is 0 if nothing is connected.
In embedded projects, sensors may fail or give invalid data. Which approach below is the best way to detect a sensor failure?
Think about what real sensor values look like and how to spot invalid readings.
Checking if the sensor value is outside the expected range is the best way to detect failure. Sensors rarely produce exactly zero or negative values unless faulty.
Examine the code below. The error message always appears even when the sensor is disconnected. Why?
int sensorValue = analogRead(A0); if (sensorValue == -1) { Serial.println("Sensor error detected"); } else { Serial.println(sensorValue); }
Look closely at the if condition syntax.
The condition uses '=' which assigns -1 to sensorValue instead of comparing. This always evaluates to true, but sensorValue is set to -1, which is invalid for analogRead. The error message should print but the logic is flawed.
Identify the option that corrects the syntax error in this code:
if sensorValue < 0 {
Serial.println("Error");
}Arduino uses C++ syntax for conditions.
Arduino requires parentheses around the condition and braces for the block. Option C correctly uses parentheses and braces.
Given this code snippet, how many times will the error message print if the sensor is disconnected and analogRead returns 0 every time?
void loop() {
int val = analogRead(A0);
if (val < 10) {
Serial.println("Sensor error");
}
delay(1000);
}Consider the loop behavior and delay.
The loop runs repeatedly. Since analogRead returns 0 (less than 10), the error message prints every time the loop runs, which is every second due to delay(1000).