Consider this Arduino code snippet that reads an IR sensor value and prints if an obstacle is detected.
const int irSensorPin = A0;
int sensorValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(irSensorPin);
if (sensorValue > 500) {
Serial.println("Obstacle detected");
} else {
Serial.println("No obstacle");
}
delay(1000);
}Assuming the sensor reads 600, what will be printed?
const int irSensorPin = A0; int sensorValue = 600; void setup() { Serial.begin(9600); } void loop() { // sensorValue = analogRead(irSensorPin); // Simulated as 600 if (sensorValue > 500) { Serial.println("Obstacle detected"); } else { Serial.println("No obstacle"); } delay(1000); }
Check the condition comparing sensorValue to 500.
The code prints "Obstacle detected" because the sensor value 600 is greater than 500.
Which of the following components is essential to detect obstacles using an IR sensor on Arduino?
Think about what emits and detects infrared light.
An IR sensor uses an infrared LED to emit light and a photodiode to detect reflected IR light from obstacles.
Look at this Arduino code snippet:
const int irPin = A0;
int val = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
val = analogRead(irPin);
if (val = 700) {
Serial.println("Obstacle detected");
} else {
Serial.println("No obstacle");
}
delay(500);
}Why does it always print "Obstacle detected" regardless of sensor value?
const int irPin = A0; int val = 0; void setup() { Serial.begin(9600); } void loop() { val = analogRead(irPin); if (val = 700) { Serial.println("Obstacle detected"); } else { Serial.println("No obstacle"); } delay(500); }
Check the if statement condition carefully.
The if condition uses = which assigns 700 to val and always evaluates true, so it always prints "Obstacle detected".
Find the option that fixes the syntax error in this Arduino code:
void loop() {
int sensorVal = analogRead(A0)
if sensorVal > 400 {
Serial.println("Obstacle");
}
}Check missing punctuation and if statement syntax.
In Arduino C++, statements need semicolons and if conditions require parentheses.
Given this Arduino code snippet:
const int irPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
for (int i = 0; i < 5; i++) {
int val = analogRead(irPin);
if (val > 600) {
Serial.println("Obstacle detected");
}
}
delay(1000);
}If the sensor reads 650 every time, how many times will "Obstacle detected" print each loop() call?
Look at the for loop and condition inside it.
The for loop runs 5 times, and each time the sensor value is 650 > 600, so it prints 5 times.
