Arduino Experiment: Control Servo via UART Commands

Difficulty Level: Intermediate

In this tutorial, you will learn how to control the position of a servo motor by sending commands through UART (serial communication). This can be useful when building remote-controlled devices or systems where you need to change the servo position via a serial interface.

Required Components

Wiring Instructions

Code Explanation

This code allows you to control the position of a servo motor via serial commands. The Arduino listens for commands sent over the UART connection, which are simple text commands. For example, sending "90" moves the servo to 90 degrees.

Key Functions

Arduino Code

The following code listens for servo angle commands via UART and moves the servo accordingly:


// Include the Servo library
#include 

Servo myServo;  // Create a servo object

int servoPin = 9;  // Pin where the servo is connected

void setup() {
  // Attach the servo to pin 9
  myServo.attach(servoPin);

  // Start serial communication at 9600 baud
  Serial.begin(9600);
  
  Serial.println("Servo Control via UART Initialized. Send angle (0-180).");
}

void loop() {
  // Check if data is available to read
  if (Serial.available()) {
    // Read the incoming string until newline ('\n') and convert to integer
    String command = Serial.readStringUntil('\n');
    int angle = command.toInt();  // Convert string to integer (angle)

    // Ensure the angle is within the valid range (0-180)
    if (angle >= 0 && angle <= 180) {
      // Move the servo to the specified angle
      myServo.write(angle);
      Serial.print("Moving servo to ");
      Serial.print(angle);
      Serial.println(" degrees");
    } else {
      // Invalid angle command
      Serial.println("Invalid command! Please enter a value between 0 and 180.");
    }
  }
}
            

Upload and Test

  1. Connect your Arduino to your computer using the USB cable.
  2. Open the Arduino IDE and copy the code above into the editor.
  3. Select the correct board and port in the IDE.
  4. Click the upload button to send the code to the Arduino.
  5. Open the serial monitor and set the baud rate to 9600.
  6. Type an angle value (between 0 and 180) into the serial monitor and press Enter. The servo should move to the corresponding position.

Optional: Use Another Device for Serial Communication

If you want to control the servo using another device (like a second Arduino or a Bluetooth module), make sure the TX and RX pins are connected properly. You can modify the baud rate or communication logic as needed.

Conclusion

In this experiment, you learned how to control a servo motor via UART commands using Arduino. Serial communication is a powerful way to send commands to a microcontroller remotely, whether you're using a second Arduino, a computer, or another serial-capable device. You can expand this idea to control multiple servos or even other devices like motors or LEDs.