Consider this Arduino code controlling a servo motor. What will the servo do when this code runs?
#include <Servo.h> Servo myServo; void setup() { myServo.attach(9); myServo.write(0); } void loop() { for (int pos = 0; pos <= 180; pos += 30) { myServo.write(pos); delay(500); } }
Look at the for loop and the delay inside loop().
The for loop increases the servo position from 0 to 180 in steps of 30 degrees. Each position is held for 500 milliseconds before moving to the next. After reaching 180, the loop restarts, so the servo repeats this motion.
Look at this code snippet controlling a servo. What error will it cause when compiled?
#include <Servo.h> Servo myServo; void setup() { myServo.attach(9); myServo.write(90); } void loop() { myServo.write(200); delay(1000); }
Check the valid range for servo angles in the Servo library.
The Servo library accepts angles from 0 to 180 degrees. Writing 200 degrees does not cause a compile or runtime error, but the servo will likely ignore or clamp the value. The code compiles and runs with a warning or no error.
This code is supposed to sweep the servo from 0 to 180 degrees and back. Why does the servo stay still?
#include <Servo.h> Servo myServo; void setup() { myServo.attach(9); } void loop() { for (int pos = 0; pos <= 180; pos++) { myServo.write(pos); } for (int pos = 180; pos >= 0; pos--) { myServo.write(pos); } }
Think about how fast the servo can move and how the code sends commands.
The loops send position commands very quickly without delay. The servo cannot physically move that fast, so it appears stuck. Adding a delay inside the loops allows the servo to move step by step.
Find the option that corrects the syntax error in this Arduino sketch.
#include <Servo.h> Servo myServo; void setup() { myServo.attach(9) myServo.write(90); } void loop() { // empty loop }
Look carefully at the end of the line with myServo.attach(9).
The line myServo.attach(9) is missing a semicolon at the end. Adding it fixes the syntax error. Other options either do not fix the syntax or introduce new errors.
This code sweeps a servo motor from 0 to 180 degrees in steps of 45 degrees, then back to 0. How many distinct positions does the servo move to in one full sweep cycle?
#include <Servo.h> Servo myServo; void setup() { myServo.attach(9); } void loop() { for (int pos = 0; pos <= 180; pos += 45) { myServo.write(pos); delay(500); } for (int pos = 135; pos >= 0; pos -= 45) { myServo.write(pos); delay(500); } }
Count the positions in the first loop and the second loop, then combine without duplicates.
The first loop moves to positions: 0, 45, 90, 135, 180 (5 positions). The second loop moves: 135, 90, 45, 0 (4 positions). The total distinct positions are 5: 0, 45, 90, 135, 180.
