void loop() {
-
const unsigned int MAX_ANGLE = 3;
-
char degrees[MAX_ANGLE + 1];
20
-
if (Serial.available()) {
-
int i = 0;
-
while (Serial.available() && i < MAX_ANGLE + 1) {
-
const char c = Serial.read();
25
if (c != -1 && c != '\n')
-
degrees[i++] = c;
-
delay(SERIAL_DELAY);
-
}
-
degrees[i] = 0;
30
int value = atoi(degrees);
-
if (value == 0)
-
value = 1;
-
Serial.print(value);
-
Serial.println(" degrees.");
35
servo.write(value);
-
delay(MOTOR_DELAY);
-
}
-
}
-
We include the Servo library, and in line 8, we define a new
Servo
object. In
the
setup
function, we initialize the serial port, and we
attach
the
Servo
object
to the pin we have defined in
MOTOR_PIN
. After that, we wait for 15 milliseconds
so the servo motor has enough time to process our command. Then we call
write
to move the servo back to 1 degree. We could also move it back to 0
degrees, but some of the servos I’ve worked with make some annoying noise
in this position.
The main purpose of the
loop
function is to read new degree values from the
serial port. These values are in a range from 0 to 180, and we read them as
ASCII values. So, we need a string that can contain up to four characters.
(Remember, strings are null-terminated in C.) That’s why we declare the
degrees
string with a length of four in line 20.
Then we wait for new data to arrive at the serial port and read it character
by character until no more data is available or until we have read enough.
We terminate the string with a zero byte and print the value we’ve read to the
serial port. Finally, we convert the string into an integer value using
atoi
and
pass it to the
write
method of the
Servo
object in line 36. Then we wait again
for the servo to do its job.
Compile and upload the sketch, then open the serial monitor. After the servo
has initialized, send some degree values, such as 45, 180, or 10. See how the
report erratum • discuss
First Steps with a Servo Motor • 229
www.it-ebooks.info