Few things you can build with an Arduino are cooler than custom robotics. With just a few servos you can build devices that automate basic mechanical tasks, or, as we’ll show in this guide, you can create your own robot arm to play around with. We’ll be building on our previous guide to ultrasonic sensors, which you can find here.
Servos are small, self-contained motors consisting of three wires, an integrated gear unit, and a shaft. When a signal is sent to the servo, the shaft rotates, allowing your Arduino to move physical objects. Typical servos have three wires; a power wire (usually red), that connects to a 5V pin on your board, a ground wire (usually black or brown), and a signal wire (usually yellow, orange, or white). Signal wires connect to digital pins on your Arduino and allow your code to communicate with the servo.
There are two main kinds of servos. Standard servos have a set rotation limit, usually between 0 and 180 degrees, which can be assigned by the write() function. When a value is passed to the servo through this function, the shaft rotates until it reaches the specified angle.
The second kind of servo is a continuous rotation servo. These can rotate infinitely in either direction, but it can’t rotate to precise angles the way standard servos can. The write() function instead assigns a rotation speed to the servo. Both have their applications, and it’s worth considering what types of movement your robot needs.
Continuous rotation servos are useful when controlling objects that require unrestricted movement like wheels. Standard servos are more useful for tasks where a part needs to briefly move, with a restricted range of movement. The robot arm we’ll be working on in this project is a perfect example of the latter.
This project will build on some of the equipment and lessons learned in the previous ultrasonic sensor tutorial. However, you can use other input types like knobs to control servos. For this project, we’ll be using the following equipment:
Arduino Uno | ![]() |
HC-SR05 Ultrasonic Sensor
An HC-SR04 or other ultrasonic sensors can be used, but the pin configuration will need to be modified |
![]() |
Arduino IDE | ![]() |
A Robot Kit
While you can build your own robotics in any configuration you want, kits like the meArm come with pre-cut parts that do all the design and guess work for you.
|
![]() |
If you choose a different robot kit, make sure to check which servos you need, as some kits don’t include them!
You’ll also need a USB cable, and a speaker. Most simple speaker modules will work, but this project will use this simple mono speaker.
For this project, we’re going to focus on the code to control individual servos. You can check out our previous guide on how to use an ultrasonic sensor for more detail on how it works. Our basic servo sketch is a modified version of the built-in Knob sketch, using parts of the ultrasonic sketch as a sensor. The full sketch which controls one servo can be found here:
#include
Servo myservo; // Create servo control object
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode (6,OUTPUT); //Insert HC-SR-05 with VCC in pin 6
pinMode (5, INPUT); // Assign pin 5 to Echo
pinMode (4, OUTPUT);// Assign pin 4 to Trig
pinMode (2,OUTPUT); // Assign pin 2 to GND.
Serial.begin(9600); // This will allow you to read how far away your sensor is later
}
void loop() {
long duration, cm; // Initialize variables for duration and cm
digitalWrite(6, HIGH); // Power the sensor
digitalWrite(4, LOW); // Clear pulse before sending a 10 microsecond ping,
delayMicroseconds(2);
digitalWrite(4, HIGH);
delayMicroseconds(10);
digitalWrite(4, LOW);
duration = pulseIn(5, HIGH); // Detect pulse length from the Echo pin, measured in microseconds
cm = (duration/2)/29.155; // Divide duration in half (due to round trip), then convert distance to centimeters (1cm per 29.155 microseconds), assign to cm variable
int servorotate = 2*(constrain(cm, 2, 30))+30; // Assign servo position based on distance
Serial.print(cm); // Print distance in cm to serial monitor
Serial.print(“cm “);
Serial.print(servorotate);// Print rotate position
Serial.print(“position”);
Serial.println();
myservo.write(servorotate); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
}
Since we’ve covered much of this code before, we won’t rehash it all here. Instead, let’s focus on a couple of key points to explain how the servo functions work. First, a couple lines of code that belong at the top of the sketch, outside the setup() function.
#include
Servo myservo; // Create servo control object
The first line here instructs the sketch to include the servo library which provides access to all the servo related functions. The second line creates the servo object that you’ll send commands to later. This sketch only controls one servo, but if your project uses multiple servos, make sure there’s an object for each one.
myservo.attach(9); // Attaches servo to pin 9
This line attaches your servo to the pin that will control it. On the TG9z, as with most servos, the wire that controls the signal is yellow. So, whichever pin you connect the yellow wire to is the one you should attach in this line. For this sketch, we’re using pin 9.
At this point, much of the code in the sketch is devoted to controlling and getting a signal from the ultrasonic sensor. Again, you can check out our previous guide on how this code works for specifics. For now, the important thing to understand is that the code will cause the sensor to send out a pulse from one cylinder and receive it in the other. The time it takes for the signal to complete its round trip will be converted into a value in centimeters. This is helpful to gauge how far your hand or object is from the sensor when you run the sketch. This value will also be output to the serial monitor, so you can see which distance correlates to what servo position.
int servorotate = 2*(constrain(cm, 2, 30))+30; // Assign servo position based on distance
The constrain() function in this line ensures that the value in cm delivered to the board is contained in the specified range. In this case, between 2cm and 30cm. If the sensor detects a distance beyond that, it will clamp it to 30cm. This helps ensure that the servo doesn’t behave erratically if no object impedes the sensor until it, for example, detects the wall on the opposite side of the room.
After that, this line converts the number (currently between 2 and 30) into a usable position on the servo. This will depend heavily on how your robot is set up. In most cases, the servo’s range of motion will be greater than the range of the pieces of the robot itself. In the case of the robot arm I was using, I found that multiplying the number by two and adding 30 put it in the sweet spot, providing a functional range of 34 to 90.
myservo.write(servorotate); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
Finally, this line will tell the servo to rotate to the specified position. The sketch will pause for 15 milliseconds to let the servo get into place. With too short of a delay, the servo can behave erratically. Too long and the movement won’t be smooth. While the values might vary depending on your setup—factors as simple as the length of the pieces you’re attaching to can play a part, so be sure to experiment! At the very least, this code should get you started.
Now, to wire everything up. It’s a good idea to upload the code you have to the Arduino first before everything is connected. While you might have to experiment a bit after uploading the code, it’s best to do as much before you connect the servo as you can. Image: Arduino Uno
Once you’re ready, follow these steps:
● Plug the HC-SR05 sensor into digital pins 2 through 6, with GND plugged into pin 2, and VCC plugged into pin 6. This should result in the sensors facing outwards, away from the Arduino.
● Plug the power wire on your servo into a 5V pin, and the ground wire into GND.
● Plug the yellow signal wire on the servo into pin 9.
Once everything is connected and the code is uploaded, place an object or your hand in front of the ultrasonic sensor. As you move it closer or further away, the servo should move backwards and forwards. You can tweak the code to make it move farther. You can also try adding a second servo that’s tied to the same sensor or add more sensors and inputs to control other servos independently.