Menu
CoddyTech

Servo Angle From Serial

Part of the Outputs section of Coddy's Arduino journey. Lesson 23 of 24.

The arm can also take orders from the Serial monitor. Type an angle and press Enter; Serial.parseInt() reads the number:

if (Serial.available() > 0) {
  int angle = Serial.parseInt();
  Serial.read();  // the newline after the number
  // use angle
}

The newline after the number stays waiting. On the next run of loop(), parseInt() would find no digits, wait a second and return 0. Ignoring that 0 worked for a blink speed, but 0 is a real angle. So read the newline away with one Serial.read() right after the number.

Someone may also type a number that is not an angle. arm.write() reads any number from 544 up as a pulse length in microseconds, so 1000 would put the arm near 45 degrees. constrain() keeps the angle between 0 and 180 first:

angle = constrain(angle, 0, 180);  // give it the variable, not parseInt()
challenge icon

Challenge

Medium

Move the servo to the angle typed in the Serial monitor:

  • when a number arrives, read it with Serial.parseInt(), then read away the newline (0 is an angle too)
  • keep it between 0 and 180 with constrain()
  • move the arm and print the angle as Angle: 45

Press Run, send 45 from the Serial monitor, then Check.

Try it yourself

#include <Servo.h>

Servo arm;

void setup() {
  arm.attach(9);
  arm.write(90);
  Serial.begin(9600);
}

void loop() {
  // when a number arrives: read it, read away the newline,
  // keep it between 0 and 180, move the arm and print it
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Outputs

Practice on your own: Arduino playground