Servo to Arduino | Arduino Servo Control Code (Best Tutorial 2019)

Servo to Arduino

Arduino Servo control code: Servo to Arduino Tutorial 2019

This tutorial explains how to use the basics Arduino to control servo motors. Due to Servo motors robots can walk, or pick up things, or move sensors around that located in useful arms, legs.


In this tutorial, you will learn how to use best capability of Arduino to control servo motors and Arduino Servo Control Code in 2019

The basics of a servo motor

Arduino Servo Control Code

 Servo motors are somewhat similar to DC motors; While DC motors are generally designed to move in a continuous way—rotating 360 degrees at a given speed—servos are generally designed to move within a limited set of angles.


In other words, in the DC motor world, you generally want your motors to spin with continuous rotation speed that you control. 


Controlling servos is fairly simple. The device has three wires connected to it: one for the ground connection, one for the drive voltage, and the third is a control signal that expects a pulse-width modulated (PWM) signal.


The signal is a square wave that is turned on and off at a set rate, normally at around 500 Hz. The ratio of the length of the time the signal is on to the time the signal off determines the desired angle of the servo.


Arduino can control servos using two different approaches. The first is to connect your servos directly to Arduino. You'll use this solution in the first example of this blog. Unfortunately, if you have a lot of servo motors, they can sometimes draw more current than Arduino can provide, which is 40 mA.


To solve this problem, you'll need to use a shield that can connect to an external power source. Then, your Arduino and shield can provide both voltage and current so that you can control many servos. The second example in this blog will use this servo controller shield designed for Arduino to control 12 servos on a hexapod robot.


Connecting a servo motor directly to Arduino

Arduino Servo Control

The first step in connecting a servo motor to Arduino is to actually obtain a servo motor. The following figure shows a typical servo motor, the Hitec HS-311, available at most hobby or RC Control stores


In order to connect this servo motor to your Arduino, you'll need some of those male-to-male solderless jumper cables that you used in the previous blogs. You'll notice that there are three wires coming from the servo. Two of these supply the voltage and current to the servo. The third provides a control signal that tells the servo where and how to move.


You'll connect these three wires to the pins on Arduino. The black wire on the servo is ground; you'll connect that to the GND pin on Arduino. The red wire on the servo is the VCC connection; connect that to the 5 V pin on Arduino.


The orange pin is the control pin on the servo; connect that to one of the DIGITAL (PWM~) pins on Arduino, for example, pin 11, as shown in the following figure:


Just a word of caution, this works well with a single servo; you will not want to use the method for more than just one or two servos. Now that you have made these connections, you are ready to write the code to make your servo move.


Controlling the servos with a program


Now that the hardware is connected, you'll need to supply the control signal to make your servos move. To control your servo, bring up the Arduino IDE. Make sure that the proper Arduino and port are chosen. Then enter the lines of code as shown in the following screenshot:


This code uses the Servo library that is installed with the standard Arduino IDE. The three sections of code that you'll need to understand are as follows:


The global variables servo, servoPin, and angle are used by the program. The Servo data type adds a set of functions so that you can control your servo.


This includes the servo.attach(servoPin) and servo. write(angle) functions, which you will use in this program to send the servo to a specific angle. To find out all the different functions that are available, visit


The setup() function connects the servo functionality to the proper pin and then initializes the serial port.


The loop() function reads the serial port and then uses that data to send the servo to the proper angle by using servo.write(angle). When you have entered the code, upload the program. When it runs, navigate to Tools | Serial Monitor. 


Now you can imagine adding a whole set of servos, one controlled by a different digital output pin on Arduino. However, Arduino itself will soon run out of the ability to supply enough current to control more servos. So if you have projects that require more than just one or two servos, you'll probably want to go with a servo motor shield.


Connecting a servo motor shield to Arduino


The servo motor shield we'll use in this example is available at most online retailers who sell Arduino Uno, and is made by adafruit. The following figure shows the servo motor shield connected to the servo wires:


This particular shield can handle up to 16 servos. The important characteristic of this servo shield is the connection on the right-hand side of the shield. In the GND and VCC connections, you'll place your external voltage and current input, allowing Arduino to control many more servos.


Controlling the servo motor shield with a program

Now that your hardware is ready, you'll need to program Arduino to send the proper control signals. To control this shield, you'll need to download a library from Adafruit.


The library for the motor shield can be downloaded from https:// you have downloaded the library, you'll need to rename it to install it into the IDE.


Look for the file in the directory you downloaded the file from, and unzip this to the directory where your Arduino library is stored.


The Adafruit-PWM-Servo-Driver-Library-master directory should now be in the library directory. You'll need to change the name of this directory to AdafruitServoDriver.


The library and its examples are now available. You can open the servo example by navigating to File | Examples | AdafruitServoDriver | servo. What you really want is to build a legged quadruped robot to exercise all of these servos.


To complete this project, you'll first need to buy some parts so you can build your quadruped robot. There are several possibilities out there, but one set I personally like is a set of Lynxmotion parts available from the online retailer


To build your quadruped robot, you'll need two sets each of the two leg parts, and then one set each of a body part. The following table illustrates the parts as they are listed on the website:


Quantity Description

  • 1 Lynxmotion Symmetric Quadrapod Body Kit-Mini QBK-02
  • 2 Lynxmotion 3'' Aluminum Femur Pair
  • 2 Lynxmotion Robot Leg "A" Pair (No Servo) RL-01
  • 4 Lynxmotion Aluminum Multi-Purpose Servo Bracket Two Pack ASB-04


Once you have these parts, you'll also need 12 standard size servos. I personally like the Hitec servos; they are a very inexpensive servo that you can get at most hobby shops and online electronics retailers.


You may need quite a powerful servo, so buy at least the HS-422. When you get the parts, perform the following steps:


  • 1. Put two right legs together.
  • 2. Now, put two left legs together.
  • 3. The next step is to build the body kit.


4. And then connect each leg to the body kit. The important part of this step is to make sure you use a bearing on the underside connection of the leg.


5. The final step is to mount the batteries and Arduino to the body kit. I like to use an RC LiPo battery for my robotic projects; they are available from most RC stores or online.


You can certainly use standard alkaline AA batteries, but they are not rechargeable and don't last very long. Using rechargeable AA batteries solves the rechargeable problem, so it is certainly a better choice. I find the RC LiPo batteries last the longest and recharge quickest.


If you are going to use a LiPo battery, choose a 2S battery; this will provide 7.4 V, which will then be regulated by the Arduino and can drive both Arduino and servos. Your kit is now ready to move.


Let's start with a simple program that sets all of the servos to their middle position, and then takes in command to move just one of the servos to a specific angle. This will help you understand how your robot is configured,


The preceding code includes a significant number of Serial.println() functions; these are there to show you what is happening.

The key statement for servo control is pwm.setPWM(servo, 0, PWM value);.

This statement sends out a PWM signal that the servo motor uses to determine the desired angle.


The servo variable selects the servo to control, the 0 variable sets when the PWM pulse starts (you'll use 0 for this application), and the pwmValue variable sets the length of the pulse. You can now see how your robot can be programmed to be moved by performing the following steps:


1. One step you'll probably want to do is adjust the mechanical position of your servos. To do this, run the program so that all of the servos are set to their middle location.


2. Then, unscrew the screw at the center of each horn connected to the servo, and turn it so that it is now in the middle location on the robot for that particular servo.


When your robot is centered, you can now begin to program your robot to do things. First, let's add a command that waves one of the front legs. From the Arduino sketch, change your loop() function, and add the home() and wave() functions. 


The code is very simple; the setup() function establishes your access to the servo shield and the loop simply takes in a command from the serial port, and when it sees from the Serial Monitor tab, it moves the front leg up and down three times.


You can really take advantage of the SW that is available out there, as there is a set of SW capabilities that have been created by enterprising individuals that will allow your quadruped robot to do a number of different actions based on the input from the serial port.


One example is at and another at


Avoiding Obstacles Using Sensors

Now that your robot can move, it is important to make sure it won't run into walls or other barriers. In this blog, you'll learn the following topics:

  • How to add sensors to your projects
  • How to add a servo to your sensor


An overview of the sensors

Before you begin, you'll need to decide which sensors to use. You require basic sensors that will return information about the distance to an object, and there are two choices—sonar and infrared. Let's look at each.


Sonar sensors


The sonar sensor uses ultrasonic sound to calculate the distance to an object. The sensor consists of a transmitter and receiver. The transmitter creates a sound wave that travels out from the sensor. 


The device sends out a sound wave 10 times a second. If an object is in the path of these waves, the waves reflect off the object. This then returns sound waves to the sensor, as shown in the following diagram:


The sensor measures the returning sound waves. It uses the time difference between when the sound wave was sent out and when it returns to measure the distance to the object.


[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]


Infrared sensors

Another type of sensor is a sensor that uses infrared (IR) signals to detect distance. An IR sensor also uses both a transmitter and a receiver. The transmitter transmits a narrow beam of light and the sensor receives this beam of light. The difference in transit ends up as an angle measurement at the sensor, as shown in the following diagram:


The different angles give you an indication of the distance to the object. Unfortunately, the relationship between the output of the sensor and the distance is not linear, so you'll need to do some calibration to predict the actual distance and its relationship to the output of the sensor. This will be discussed later in this blog.


Connecting a sonar sensor to Arduino


Here is an image of a sonar sensor, HC-SR04, which works well with Arduino:

These sonar sensors are available at most places that sell Arduino products, including In order to connect this sonar sensor to your Arduino, you'll need some of those female-to-male jumper cables that you used in the previous blogs. You'll notice that there are four pins to connect the sonar sensor.


Two of these supply the voltage and current to the sensor. One pin, the Trig pin, triggers the sensor to send out a sound wave. The Echo pin then senses the return from the echo.


To access the sensor with Arduino, make the following connections using the male-to-female jumper wires:

Arduino pin Sensor pin
5V Vcc
12 Trig
11 Echo

Accessing the sonar sensor from the Arduino IDE

Now that the HW is connected, you'll want to download a library that supports this sensor. One of the better libraries for this sensor is available at https://code. Download the NewPing library and then open the Arduino IDE.


You can include the library in the IDE by navigating to Sketch | Import Library | Add Library | Downloads and selecting the NewPing ZIP file. Once you have the library installed, you can access the example program by navigating to File | Examples | NewPing | NewPingExample


Now, upload the code to Arduino and open a serial terminal by navigating to Tools | Serial Monitor in the IDE. Initially, you will see characters that make no sense; you need to change the serial port baud rate to 115200 baud by selecting this field in the lower-right corner of Serial Monitor.


Now, you should begin to see results that make sense. If you place your hand in front of the sensor and then move it, you should see the distance results change, You can now measure the distance to an object using your sonar sensor.


Connecting an IR sensor to Arduino


One popular choice is the Sharp series of IR sensors. Here is an image of one of the models, Sharp 2Y0A02, which is a unit that provides sensing to a distance of 150 cm:

To connect this unit, you'll need to connect the three pins that are available on the bottom of the sensor. Here is the connection list:

Arduino pin Sensor pin

  • 5V Vcc
  • A3 Vo

Unfortunately, there are no labels on the unit, but there is a data sheet that you can download from 


One of the challenges of making this connection is that the female-to-male connection jumpers are too big to connect directly to the sensor.


You'll want to order the three-wire cable with connectors with the sensor, and then you can make the connections between this cable and your Arduino device using the male-to-male jumper wires. Once the pins are connected, you are ready to access the sensor via the Arduino IDE.


Accessing the IR sensor from the Arduino IDE

Now, bring up the Arduino IDE. Here is a simple sketch that provides access to the sensor and returns the distance to the object via the serial link:


The sketch is quite simple. The three global variables at the top set the input pin to A3 and provide a storage location for the input value and distance. The setup() function simply sets the serial port baud rate to 9600 and prints out a single line to the serial port.


In the loop() function, you first get the value from the A3 input port. The next step is to convert it to a distance based on the voltage. To do this, you need to use the voltage to distance chart for the device; in this case, it is similar to the following diagram:


There are two parts to the curve. The first is the distance up to about 15 centimeters and then the distance from 15 centimeters to 150 centimeters. This simple example ignores distances closer than 15 centimeters, and models the distance from 15 centimeters and out as a decaying exponential with the following form:


Thanks to, the values that work quite well for a cm conversion in distance are 30431 for the constant and -1.169 as the exponential for this curve. If you open the Serial Monitor tab and place an object in front of the sensor, you'll see the readings for the distance to the object.


By the way, when you place the object closer than 15 cm, you should begin to see distances that seem much larger than should be indicated. This is due to the voltage to distance curve at these much shorter distances. If you truly need very short distances, you'll need a much more complex calculation.


Creating a scanning sensor platform

While knowing the distance in front of your robotic project is normally important, you might want to know other distances around the robot as well. One solution is to hook up multiple sensors, which is quite simple.


However, there is another solution that may be a bit more cost effective. Instead of multiple sensors, you can place a single sensor on a servo and then use the concepts that you learned in Blog, Controlling Servos with Arduino, to move the servo and allow the sensor to scan a set of different distances.


To create a scanning sensor of this type, take a sensor of your choice (in this case, I'll use the IR sensor) and mount it on a servo. I like to use a servo L bracket for this, which is mounted on the servo Pas follows. 


You'll need to connect both the IR sensor swell as the servo to Arduino. Now, you will need some Arduino code that will move the servo and also take the sensor readings. 


The preceding code simply moves the servo to an angle and then prints out the distance value reported by the IR sensor. The specific statements that may be of interest are as follows:

  • servo.attach(servoPin);: This statement attaches the servo control to the pin defined
  • servo.write(angle);: This statement sends the servo to this angle
  • inValue = analogRead(inputPin);: This statement reads the analog input value from this pin
  • distance = 30431 * pow(inValue, -1.169);: This statement translates the reading to distance in centimeters


Even More Useful Sensors

Your projects may want to do more than just avoiding barriers. In this blog, we'll go through the following topics:

  • How to add a digital compass so that your projects can sense direction.
  • How to add an accelerometer/gyro to your project so that you can sense the tilt and movement of your projects.
  • How to add an altimeter/pressure sensor to your project so that you can sense your altitude. These can also be useful in weather prediction.


Connecting a digital compass to Arduino

One of the important pieces of information that might be useful for your robot is its direction of travel. This could be given by a GPS unit, Using a GPS Device with Arduino.


However, a GPS unit can be expensive, and it often doesn't work well inside buildings, because the GPS satellite signals don't penetrate buildings well. So, let's learn how to hook up a digital compass to Arduino.


There are several chips that provide digital compass capability; one of the most common ones is the HMC5883L 3-Axis Digital Compass chip. This chip is packaged into a module by several companies, but almost all of them result in a similar interface. Here is a picture of one by a company called SainSmart, and it is available at a number of online retailers:


This type of digital compass uses magnetic sensors to discover the earth's magnetic field. The output of these sensors is then made accessible to the outside world through a set of registers that allow the user to set things such as the sample rate and continuous or single sampling. The x, y, and z directions are output using registers as well.


The connections to this chip are straightforward; the device communicates with Arduino using the I2C bus, a standard serial communications bus.


The I2C interface is a synchronous serial interface and provides more performance than an asynchronous Rx/Tx serial interface. The SCL data line provides a clock, while the data flow on the SDA line. The bus also provides addressing so that more than one device can be connected to the master device at the same time.

The following are the connections that you'll need to make between Arduino and the device:

Arduino pin Sensor pin
5V 5V

Notice that you will not connect the 3.3V or DRDY (data ready) lines. Our Arduino supplies power through the 5V line instead of the 3.3V line, and the DRDY line is not needed by this library. Now, you are ready to talk with the device using the IDE.


Accessing the compass from the Arduino IDE

The first step in accessing the compass capability from the IDE is to install a library. Finding a library that supports the module is a bit difficult, but one that works well is available at Digital%20Compass%20Module.


The following are the steps to install the library and run the example:

1. Select the Arduino Library for the HMC5883L link on the previously mentioned page, and it will take you to a set of library selections.


2. You need to select the HMC5883L / HMC5883L Library For Arduino.rar link at the bottom of this page, and it will download a .rar file that holds the library.


3. Unzip this file into the libraries directory of your Arduino installation.


4. Now, bring up the Arduino IDE and select the Examples option under the File menu, and you should be able to select the HMC5883L library example, as shown in the following screenshot:


5. Once you have selected this example, upload it to your Arduino and open the Serial Monitor. You may have to resize the monitor to get a good look at the results, but you should see something similar to the following screenshot:


The Raw data is the x, y, and z data that is coming directly from the compass and is related directly to the earth's magnetic field. The Scaled values are those that are scaled to reflect true north.


The Heading value is expressed in degrees and radians. Now, you can add direction to your project! As you move the device around, you should see the Heading value change.


These readings should give you an indication of the heading of your project. This is very useful to help you give direction to your robotic projects. However, you may want to use even more information, such as speed and tilt. Fortunately, there are sensors for this as well.


Connecting an accelerometer/gyro to Arduino


The ability to measure speed and tilt is important in many robotic applications. You'll need to add an accelerometer/gyro sensor for this. This device measures the tilt using very small gyros, devices that spin and resist changes in orientation. When these changes occur, the resistance to change can be measured. The device also measures movement using an accelerometer.


An accelerometer measures movement in one direction using very small (MEMS) machines that respond to the motion by outputting a small signal.


Providing this information can help you know how your device is moving. Fortunately, there are chips that can provide this functionality. One of them is the MPU-6050 chip, which provides a complete set of information on movement, including the acceleration and tilt. There are several different manufacturers who place this chip on a small board accessible from Arduino.


One of these is the SparkFun version, the SparkFun SEN-11028, available at

The interface to the board is quite simple, with only one issue. One of the ways to connect this particular chip is to solder header pins to the board to connect the jumper wires to Arduino.


You can purchase these at as well; just search for the Arduino stackable header, 8-pin version. Once the header is soldered, the device will look as follows:


Now, you can use a male-to-male jumper cable to connect between Arduino and the board. The following table shows the connections:

  • Arduino pin Sensor pin
  • 3.3V VDD
  • A5 SCL
  • A4 SDA
  • 3.3V VIO

You'll notice that you need to make two connections to the 3.3V supply, so you may want to create a male-to-male jumper cable with two connections on one end. This can be done using three male-to-male cables.


For this, we need to cut off one end and strip back the insulation, then solder the three cables together, and then wrap the solder connection in electrical tape.


Accessing the accelerometer from the Arduino IDE

Now that the two devices are connected, you'll need to bring up the Arduino IDE and add a library so that you can access the functionality from the SW. Follow these steps:


1. Go to and look on the right-hand side of the page for the download link. This will download the entire library.

From the SparkFun page on the device at www., you'll find a GitHub repository that supports not only this device but a number of devices that use the I2C interface.


2. Now, you should unzip the file to a handy location; I unzipped mine in the Downloads directory. What you want is just the files associated with Arduino, so go to the directory that supports those files:


3. Even though you won't need all of these libraries right now, you can just copy all of these to your Libraries directory of your Arduino for future use. You'll notice, by the way, that there is a duplicate of the HMC5883L library you installed earlier, so you can decide to merge these directories.


4. Once you have these directories installed, bring up the Arduino IDE. Before you bring up the example program for the device, open the Serial Monitor and set the baud rate to 38400. Now, bring up the example program that reads the raw values of the accelerometer and gyro by navigating to Examples | MPU6050 | Examples | MPU6050_raw,


This will open a sketch that provides the code to read the raw data from your sensor. When you upload the code and open the Serial Monitor, you should see something similar to the following screenshot:


The first three numbers are the x, y, and z raw accelerometer readings, and the last three are the x, y, and z angle readings from the gyroscope.


If you mount the device flat in your project, the x, y, and z readings would be associated with the yaw, pitch, and roll of the device respectively. As you move the device around, you should see these readings change.


This data can then be used to sense when your device is moving, in what direction, and how it is positioned. The device has a lot of capabilities, including the ability to calibrate itself so that a particular position is the "zero" position. For more information about these capabilities, feel free to look at both example programs provided by the library. 


Connecting an altimeter/pressure sensor to Arduino


The final sensor that you'll learn about in this blog is the altimeter/pressure sensor. An altimeter measures the barometric pressure, and as this pressure decreases with rising elevation, it can indicate elevation.


This is particularly useful when you want to build a robot that can fly. First, you'll need to select a device. One device that can provide this information is the SainSmart BMP085 Module Digital Barometric Pressure Sensor, available at many online retailers. It looks as follows:


It looks very similar to the digital compass, and just like the earlier two devices, it connects via the I2C interface. You can even use the same libraries you just downloaded for the accelerometer/gyro for I2C support. The connections between Arduino and the device will be the same as the digital compass, as demonstrated in the following table:


Arduino pin Sensor pin

  • 5V 5V
  • A5 SCL
  • A4 SDA

The connections, just like those of the digital compass, are clearly marked on the back of the device, and you can use female-to-male jumpers to make the connections.


Accessing the altimeter/pressure sensor from the Arduino IDE

The following are the steps associated with connecting this device to Arduino:

1. The first step in accessing the device is to download the appropriate library. Here, you have a choice. You can use the library described in the Connecting an accelerometer/gyro to Arduino section, or you can download a library just for this device.


The library supplied for the accelerometer/gyro is a more general library designed to communicate with many different I2C devices. The library for this device supports only this device. 


If you want to download the library for this device, go to and select the Download Link selection at the bottom of the link.


This will download a .rar file that will include an example sketch. I personally prefer to use the I2C library version; it is more up to date, so I will follow that example here.


2. Open the example by navigating to File | Examples | BMP085 | Examples


3. You should now set the Serial Monitor baud rate to 38400 if you haven't already done so, as this is the baud rate set by the example program. Now, you can upload the sketch of Arduino, and when you open the Serial Monitor, you should see something similar to the following screenshot:


You can see not only the altitude but the temperature and pressure as well. Now, this attitude is not an absolute value, but a relative one. It will change with a change in weather, as the barometric pressure is dependent on weather pattern changes.


This particular reading is, therefore, really only useful when you want to measure the relative changes in altitude, for example, when you want to know how far your flying project has either gone up or done from a reference position.


Communicating with Others

Until now, all our projects have been designed to be standalone and independent, but there will be occasions where we will have to integrate our project with other external devices, and this means that we will have to make our Arduino talk with these other elements. Usually, this communication is made via a very practical and extended standard called serial communication.


In this blog, we will see how to connect and program Arduino so that it is capable of serially talking to our computer as the simplest and most common type of serial communication, but what you will learn here is directly applicable to any other connection you have to establish to another device that can talk serially.

So, let's give up talking and let's make our projects talk.


Serial communications concepts


All through this blog, when we talk about serial communication, we will be referring to RS-232 standard protocol communication based on the Universal Asynchronous Receiver/Transmitter (UART) that the Arduino microcontroller incorporates.


It is the most common communication type for most Arduino projects in comparison to other serial protocol communications that can also be established with Arduino and that we will briefly introduce in the next section. 


The first thing we should know is why all these communication systems are called serial as opposed to parallel communications.


In the case of serial communication, every bit of the data being transmitted is sent one piece at a time, through just a single line of the communication channel. In a parallel communication, data bits are sent in groups all at once, which makes it necessary to have a bigger number of communication lines in the channel.


This is perhaps the main reason to use serial communications in Arduino, due to the limited number of pins available to establish the communication channel, allowing using just two pins in the case of RS-232 communications.


 If you take a closer look at your Arduino board, you should notice a pair of pins marked as TX and RX in the digital pins row, pins 0 and 1 to be precise, as you can also see in the following image:


Ambient light meter circuit schematic

In the sketch, we had to read the photocell value and map it to a four-state output range with the following lines of code:…

void loop(){

// Read the sensor and convert the value to

// one of the four states we will use value = analogRead(photocell); state = map(value,0, 200, 1, 4);

// acts depending on the obtained states switch(state){

case 1:...

At that time, I didn't tell you how I got that input range of 0–200, but now I will cover this.


By using just the input part of this circuit, the photocell, and the 10K Ohm protecting resistor, we are going to use the following sketch to be introduced to serial communication with Arduino and read the values generated by the photocell so that we can get an idea of the possible range of values to expect from it:

Serial sensor reading
// Photocell pin as a define doesn't consume memory #define photocell 0
// Global variables we will use
// A variable to store the read value
int value = 0;
// A variable to convert the read value to our output range int state = 0;
// Configuration of the board: just one output
void setup() {
pinMode(photocell, INPUT); //optional
// Init serial communication Serial.begin(9600);
// Sketch execution loop void loop(){
// Read the sensor and convert the value to
// one of the four states we will have value = analogRead(photocell);
state = map(value,300, 550, 1, 4);
// Send the read value and converted state through
// the serial communication in a fancy way Serial.print(value);
Serial.print(" : "); Serial.println(state);


The code is quite simple, and as you should have noticed it only reads the sensor value and maps it to a new range.


However, it also includes all necessary instructions to establish and maintain a serial communication with the computer to send the read and converted values to it so that you can know them and adapt your input range in response.


To begin, in the setup() function, we simply establish a serial communication at 9,600 bauds by using the following line of code:



At this moment, it really doesn't matter to you, but to establish a serial communication we are going to use the Serial object, and thus we have to use the object.method syntax, Serial.begin() in our case.


 For our purposes in this blog, all we have to know is that with this instruction we begin the serial protocol to make the Arduino board communicate with any serial device, the computer in our example.


Once the serial communication is established, we have to just send whatever value we want through it to the other part. To make this in the previous code, we have used three different lines of code:

  • Serial.print(value);
  • Serial.print(" : ");


Serial.println(state); The only difference between the Serial.print() and Serial.println() methods is that the former simply sends the value enclosed in the parentheses, while the latter sends the value and a carriage return, which comes in very handy when trying to format the serial output.


In our case, I've even included a delimiter between the read value and the converted one, so that the final result will be something like 508 : 3.


To see it in action, all you have to do is upload the code to the Arduino board and open, as we saw in Blog 2, The Arduino Development Environment, the Serial Monitor from the last icon on the Arduino programming environment toolbar, the one at the top right separated from the rest and whose icon represents a loupe looking at bits.


The Serial Monitor icon at the rightmost part of the Arduino toolbar

Once the window opens, the first thing you have to look at is that the select baud rate option at the bottom right of the window is the same as that you have set in the code the Arduino runs.


This ensures that both the Arduino and your computer are talking at just the same speed. In our case, we set the Arduino to begin the communication at 9,600 bauds.


Once the correct baud rate is set, you will begin to see a constant flow of data appearing on the window. In our case, the data will represent the read value from the sensor and the corresponding mapped value separated by a colon.


If data is not constantly appearing, ensure that you have checked the Autoscroll checkbox that allows the window to always scroll down to the new incoming data automatically.


In the next section, we will see how to use the upper textbox to send data from the computer to Arduino. Once you are able to read the data flow the Arduino is sending to your computer, you can cover your photocell to see how this data changes immediately to reflect the ambient light variation.


If you take the photocell to its two extreme situations, totally covered and highly illuminated, you can take note of the minimum and maximum values the sensor gives and these values, as you will have supposed, correspond to the minimum and maximum values of our input range for the mapping into the new output range.


In this example, I got values from 300 to 550, but they depend on my particular photocell, the place where I placed the photocell, and even the time of day, so take note of your readings and adapt your code in response.


In most of the projects, once the calibration has been made you simply comment out the lines corresponding to the serial communication to disable them and not make Arduino work on it if you're not going to need them anymore. Don't permanently delete them in case you need to later take a new look at the sensor readings.


Sending data to Arduino

What we have seen till now is just one half of a serial communication; we have simply sent data from the Arduino to our computer. In this new example, we will revisit the motor speed control project of Blog.


Analog Inputs to Feel between All and Nothing, and replace the potentiometer by our computer in the sense to use it as a way to vary the motor speed, and take advantage of this new control method to incorporate two new possibilities:


Totally stop the motor

Make it run at full throttle Since we are not going to use the input side of the previously mentioned project, we only need to connect a motor to Arduino as we already saw in Blog.


Controlling Outputs Softly with Analog Outputs, and I'll include that schematic here again for better understanding. The connection of a motor to Arduino to be controlled via a serial communication


The complete code of the sketch we are going to use for this data-sending example is as follows:

// Global Definitions
// The pin used for the transistor base #define transistorBase 6
// The increment for the motor speed #define motorIncrement 10
// Global variables we will use
// A variable to store the received value int dataReceived;
// and another to set the motor speed int speed = 0;
// Configuration of the board: three outputs and one input void setup() {
pinMode(transistorBase, OUTPUT);
// Init serial communication Serial.begin(9600);
// Sketch execution loop void loop(){
// check if data has been sent from the computer: if (Serial.available()) {
// read the next char
dataReceived =;
// Act depending on it switch (dataReceived){
// Increment speed case '+':
if (speed<250) { speed +=motorIncrement; } break; // Decrement speed case '-': if (speed>5) {
speed -= motorIncrement;
// Stop motor case '0':
speed = 0; break;
// Full throttle case '*':
speed = 255; break;
// Send back the actual speed Serial.println(speed);
// Set the speed motor analogWrite(transistorBase, speed);}


To begin, we have set two definitions, transistor base for the pin that we'll use to connect the transistor base and motorIncrement to specify the increment or decrement we'll use when changing the motor speed.


Once done, we declared two variables, dataReceived to hold the data received through the serial communication and speed to account for the current motor speed. In the setup() function, we simply set the transistor base pin as an output and began a serial communication at 9,600 bauds.


The main loop is where all the action is taking place and where the interesting part regarding serial data sending occurs. We just look if any new data has come through the serial communication with a call to the Serial.available() method, which returns true in case new data has been sent.


If we have new data, we get it 1 byte at a time by storing it in the dataReceived variable with a call to the method, and based on the value of this variable, we set a switch control structure to act depending on the received character.


The code considers four different situations:

  • The increment of the motor speed when it receives a + character
  • The decrement of the motor speed when it receives a - character
  • Full halt of the motor if a 0 is received
  • Set the motor at full throttle in case a * is received


In every case, we simply change the value of the speed variable accordingly.

Just after the switch case, we send the current updated speed back to the computer via serial communication and finally set the motor speed.


The method will return 1 byte at a time while there is incoming data; this means that if you send from the Serial Monitor window a list of chars like ++++, it will increase the speed by four times. It is like a computer-controlled motor with Arduino acting as a physical bridge.


Since the two projects we have seen in this blog aren't really new, I would like to finish this blog with a totally new example which, by the way, will introduce you to two new electronic components and a very powerful programming concept.


A computer connected dial thermometer

For this final example, I would like to build a device that displays the current temperature by using a dial and we will use two new components for it:

  • A thermistor or temperature-dependent resistor as a sensor
  • A servomotor as an output device to move the dial needle


Dealing with the thermistor is nothing new as it is just another kind of variable resistor and we will connect it to Arduino by once again creating a voltage divider. There is nothing new here.


Servomotors are a special kind of motors that don't freely spin, but are able to position at a specific angle and stay there instead thanks to a feedback mechanism and additional circuitry included in the motor case, and are depicted in the following image:


A thermistor and a small servomotor

The use of servomotors is very common in a multitude of projects but their management may be a bit tricky due to the fact that they need a specially forged train of pulses to operate.


The Arduino language comes here to our rescue once again by incorporating a library to deal with servomotors, which makes connecting and programming one of these devices a breeze.


A library is simply a set of functions already elaborated and tested to accomplish a task. In this example, we will use the servo Arduino library to deal with the one we are going to connect.


The thermometer circuit

As you see, we connect the thermistor just like the photocell or the potentiometer in our previous examples. The servomotor has three wires: V+, GND, and signal. We will connect the V+ wire (usually red) to 5V and the GND (black) wire to GND from the Arduino power pin header, and finally the signal one (usually yellow or white) to pin 7.


The code for the thermometer

Here, you have the complete code for the dial thermometer project. It shouldn't be hard to understand:

#include <Servo.h>
// Global Definitions
// The pin used for the transistor base #define servoPin 7
// The increment for the motor speed #define thermistor 0
// Global variables we will use
// A variable to store the read temperature int temperature;
// and another to store the servo angle int angle = 0;
// A servo object
Servo aServo;
// Configuration of the board: three outputs and one input void setup() {
// Set the thermistor pin as an output pinMode(thermistor,INPUT); // optional
// Init serial communication
// Sketch execution loop void loop(){
// We read the value of the thermistor temperature = analogRead(thermistor);
// Map it to a valid angle
angle = map(temperature, 750, 850, 0, 179);
// Send both back to the serial monitor Serial.print(temperature); Serial.print(" : "); Serial.println(angle);
// Position the servomotor accordingly aServo.write(angle);
// Wait some time to avoid the servo to vibrate delay(100);
The only new thing in this code is the programming of the servomotor.
We begin by including the library with the following:
#include <Servo.h>


This allows us to declare a new instance of a servo object in the Servo variable with this:

Servo aServo;


In the setup() function, we call the servo.attach(7) method of our new object to specify through which pin the servomotor will be commanded. 


Finally, in the main loop, we simply map the received value from the thermistor into a valid angle in the range 0–179 and use the obtained value to position the servomotor with a call to aServo.write(angle).


By sending the read value of the thermistor back to the computer via serial communication, you can estimate the range of temperatures you want to control and allow the servo to represent.


The proposed values 750–850 are the ones I found valid for my thermistor and the temperature ranges in my room, but I'm sure you will have to adapt to your specific configuration. Here, you have an image of my particular assembly with a small gradient I printed to be used as the dial background:

And You also visit Glossary of Electrical Terms


A thermistor and a small servomotor

A very simple project but also a very visual one that I'm sure will make a perfect introduction to the use of servos and the servo library.


If you want to know more about servos and the Arduino servo library, you could visit the servomotor entry at the Wikipedia site at wiki/Servomotor and the Arduino Reference page for the servo library at