Arduino Uno Quick Start Manual page 244

Hide thumbs Also See for Arduino Uno:
Table of Contents

Advertisement

void
loop() {
-
const unsigned int
-
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("
35
servo.write(value);
-
delay(MOTOR_DELAY);
-
}
-
}
-
We include the Servo library, and in line 8, we define a new
the
setup
function, we initialize the serial port, and we
to the pin we have defined in
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
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
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
pass it to the
write
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
MAX_ANGLE = 3;
degrees.");
MOTOR_PIN
. After that, we wait for 15 milliseconds
loop
function is to read new degree values from the
method of the
Servo
object in line 36. Then we wait again
www.it-ebooks.info
First Steps with a Servo Motor
Servo
object. In
attach
the
Servo
object
degrees
atoi
and
229
report erratum
discuss

Hide quick links:

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the Arduino Uno and is the answer not in the manual?

Subscribe to Our Youtube Channel

Table of Contents