Learning to Program the Arduino

Listing 7. Servo Control Sketch

 * servo1: servo1.pde

 * Servo control from the Serial port
 * Slower, faster, Center and Stop a Servo with an LED Blinky
 * Created: 1 June, 2011, Amit Saha (http://echorand.me)
 * Adapted from http://principialabs.com/arduino-serial-servo-control/

/** Adjust these values for your servo and setup, if necessary **/
int servoPin     =  2;    // control pin for servo motor
int minPulse     =  500;  // minimum servo position
int maxPulse     =  3000; // maximum servo position
int turnRate     =  10;  // servo turn rate increment (larger value, 
                            faster rate)
int refreshTime  =  20;   // time (ms) between pulses (50Hz)

int OFF=0; // This variable will be used to get/set the status of the servo

/** The Arduino will calculate these values for you **/
int centerServo;         // center servo position
int pulseWidth;          // servo pulse width
int moveServo;           // raw user input
long lastPulse   = 0;    // recorded time (ms) of the last pulse

/* LED setup*/
int ledPin=13;

void setup() {
  pinMode(ledPin, OUTPUT); // LED Blink
  pinMode(servoPin, OUTPUT);  // Set servo pin as an output pin
  centerServo = maxPulse - ((maxPulse - minPulse)/2);
  pulseWidth = 0;
  Serial.println("      Arduino Serial Servo Control");
  Serial.println("Keys:'(s)lower' or '(f)aster', spacebar to center 
and o to stop");

  moveServo = 60;

void loop() {
  // wait for serial input
  if (Serial.available() > 0) {
    // read the incoming byte:
    moveServo = Serial.read();

    // ASCII 's' is 115, ASCII 'f' is 102, 'o' is 111, 'spacebar' is 32
    if (moveServo == 115) { pulseWidth = pulseWidth - turnRate; OFF=0;}
    if (moveServo == 102) { pulseWidth = pulseWidth + turnRate;OFF=0; }
    if (moveServo == 32) { pulseWidth = centerServo; OFF=0;} //center
    if (moveServo == 111) { OFF= 1;} //STOP

    // limit the servo pulse at min and max
    if (pulseWidth > maxPulse) { pulseWidth = maxPulse; }
    if (pulseWidth < minPulse) { pulseWidth = minPulse; }


  // pulse the servo every 20 ms (refreshTime) with current pulseWidth
  // this will hold the servo's position if unchanged, or move it if
  // changed
  if (OFF == 0)
    /* Turn ON the LED*/

    if (millis() - lastPulse >= refreshTime) {
      digitalWrite(servoPin, HIGH);   // start the pulse
      delayMicroseconds(pulseWidth);  // pulse width
      digitalWrite(servoPin, LOW);    // stop the pulse
      lastPulse = millis();           // save the time of the last pulse
     /* Turn OFF the LED*/

    //Stop the servo
    digitalWrite(servoPin, LOW);

Once the sketch is uploaded, open a serial communication channel using screen (feel free to substitute it with your favorite terminal communication program). Type screen /dev/tttyACM0 9600, and you should see the "servo prompt" at your service:

Arduino Serial Servo Control
Keys:'(s)lower' or '(f)aster', spacebar to center and o to stop

Pressing the keys to the servo should produce the desired behavior. If you see the code listing for the servo mechanism, you will see that the key to controlling the speed is basically the duration of the delay (variable pulseWidth) between sending a HIGH and LOW signal to the servo. Here, we are simulating an analog behavior using the important technique called Pulse Width Modulation, which you can read about elsewhere.

If you have gotten this servo example up and running, you also might want to check out the other example sketches for working with servos in the Arduino IDE under File→Examples→Servo.

A Peek under the Hood

I'm drawing toward the close of this article, and I hope you have had a lot of fun. However, if you are like me, you already have started wondering what's going on behind the scenes—the journey of the processing sketch to the bytes getting executed on the Arduino board.

The real work behind the scenes is done by the GNU C/C++ compilers, linkers and libraries for the AVR microcontroller. If you hold the Shift key when you compile your sketch, you will see that the commands - avr-g++, avr-g++, avr-ar and avr-objcopy are invoked. First, your Arduino sketch is converted to a suitable C++ file (with the .cpp extension), which then is compiled, linked and finally converted to the hex file that is uploaded to the Arduino board. You can see all these intermediate files in the /tmp/build*.tmp directory. Knowledge of this build process can enable you to bypass the IDE for your Arduino development by writing an appropriate Makefile. See the "Command-Line Arduino development" article listed in Resources for an example.


I've described a few simple but cool things that can be done with an Arduino, but this article barely scratches the surface. A number of excellent books are available that list a great number of Arduino projects you can build for fun and profit. These are, of course, in addition to all the excellent on-line resources available. During exploring Arduino purely from the various blog posts on the Web and a trial-and-error-based approach to learning, I discovered many great projects in the Arduino ecosystem. Be sure to see the Resources for this article for some of the most interesting Arduino books, articles and projects.

Also note that wires are good, but only when you want to limit yourself to the confines of your tabletop or even your room. If you want your Arduino to be out there, decoupled from your host machine, you need to explore ways of wireless communication. Say hello to XBee modules, which allow communication with the ZigBee communication standard.

And before I end, you might face issues with erratic serial communication. Especially during extended periods of experimenting with serial communication, I found that the serial ports would remain locked or just be plainly not accessible from the host computer. My advice is to be patient. Unplug and plug back in a few times, and try killing the lock file manually. Now, you should be good to go.


Thanks to the awesome Arduino community members for their documentation and numerous other bloggers on the Web. The Arduino circuit diagrams were drawn with Fritzing (http://fritzing.org).


Author's Code for This Article: https://bitbucket.org/amitksaha/articles_code/src/6bed469945fd/arduino_article

Plumbing for the Arduino: http://www.concurrency.cc/book

PureData (Audio Processing and Visualization): http://puredata.info

Firefly Experiments (bridging the gap between Grasshopper, the Arduino microcontroller, the Internet and beyond): http://www.fireflyexperiments.com

Arduino: http://arduino.cc

Processing Language: http://processing.org

Arduino Hardware (I/O Boards): http://www.arduino.cc/en/Main/Hardware

Arduino Uno: http://arduino.cc/en/Main/ArduinoBoardUno

Sparkfun's Starter Kit for the Arduino: http://www.sparkfun.com/products/10174

Installing Arduino on Linux (for different distributions): http://www.arduino.cc/playground/Learning/Linux

Command-Line Arduino Development: http://shallowsky.com/software/arduino/arduino-cmdline.html

Getting Started with Arduino by Massimo Banzi, O'Reilly Media/Make: http://shop.oreilly.com/product/9780596155520.do

Programming Interactivity: A Designer's Guide to Processing, Arduino, and openFrameworks by Joshua Noble, O'Reilly: http://shop.oreilly.com/product/9780596154158.do

Arduino Cookbook by Michael Margolis, O'Reilly: http://shop.oreilly.com/product/0636920022244.do

Arduino Language Reference: http://www.arduino.cc/en/Reference/HomePage

Tom Igoe's Physical Computing Page: http://www.tigoe.net/pcomp

Experimenter's Guide for Arduino: http://ardx.org/src/guide/2/ARDX-EG-ADAF-WEB.pdf

Arduino Tutorials (tronixstuff): http://tronixstuff.wordpress.com

Principia Labs, Arduino Serial Servo Control: http://principialabs.com/arduino-serial-servo-control

Make's Arduino Web Site: http://blog.makezine.com/arduino

Arduino Tutorial on Lady Ada: http://www.ladyada.net/learn/arduino



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Really interesting

marksen's picture

Arduino is a really intersting project because its way to use are limitless. It can be adapted to many things and it's quite easy to program.

I love the Arduino! Thanks

Pit's picture

I love the Arduino! Thanks for the interesting article.

Processing, C/C++ and Arduino

SomeTom's picture

...a language that looks very similar to C and is based on Processing.

Well, I'd rather say it's a language that looks like Processing (Arduino is using the Processing IDE) but is based on C/C++. There's AVR's version of gcc under the hood, while Processing is running on top of Java.
Although the simplified C/C++ inside the IDE is looking mostly like Processing, Arduino really is not Processing at all. If you used to play around with Processing before you tried to code some Arduino you might make some weird experiences, as it really seems to be the same - until you try to try to initialize arrays or do some string operations.
After hours of really weird behaviour, I looked a little deeper into the docs and was quite surprised to find out that I had unknowingly been running Java-like code through a C-compiler for half a day :)
The funniest thing about it was that it actually worked most of the time...

Thank you for the comment.

Amit Saha's picture

Thank you for the comment. Perhaps, "based on Processing" is not very true.

However to me, the language looks "very" C. And yes as you pointed out, its really gcc-avr down below as also pointed out in the later parts of the article. My experience with Processing is not beyond a basic level, so I came to Arduino "from" C, rather than processing.


Great article. Just a brief

Fabpicca's picture

Great article.
Just a brief observation.
Arduino doesn't stand for "good friend" in Italian (I'm Italian). As far as I know Arduino is the name of the cafè Arduino inventors where used to meet.

But Wikipedia says so?

AmitSaha's picture

Hello: Thanks for your comment. I am sorry if I got it wrong, But Wikipedia has this: "Arduino" is an Italian masculine first name, meaning "strong friend". The English version of the name is "Hardwin".(From: http://en.wikipedia.org/wiki/Arduino#History)


You're mistaken.

Anonymous's picture

Amit is a Hebrew name which has the meaning "Friend" but it's not correct to say that Amit is the Hebrew word for friend. Just because the name's origin is Italian doesn't mean it's a current Italian word for something.

Name of Cafe, Name of King

MoChaMan69's picture

The name Arduino comes from the cafe the founder(s) frequented where they thought of the project . Cafe Arduino takes it's name from medievel king that briefly ruled the area . I can't find my source right now but it's something like King of Ardo , therefore he was an Arduino , hence Cafe Arduino , hence the Arduino Project . Much of this comes from the IEEE article a few months ago .

Unfortunately, the lack of research in the first sentence makes me doubt the entire 5 page article . I'll glance at it later anyway in case there's something useful . - MC

I'm from Italy, therefore I

From_Italy's picture

I'm from Italy, therefore I can give a definitive answer. Arduino is the name of a bar in Ivrea (Piedmont, Italy) frequented by the (Italian) creators of the open source framework. The bar was named after Arduin of Ivrea, first King of Italy from 1002 to 1017. By the way, Arduino is not a common name nowadays in Italy


Roland's picture

The IO pins can't drive much: 5v and 40ma each, not to exceed 120ma total. You need a tiny relay to do anything more than power an LED, and even there you need to limit the current to prevent burnout. I have had luck with tiny reed relays connected directly to the IO pins. See www.elexp.com p/n 22RD5, with 5v/500ohm coils. These draw only 10ma. Buy more than you need and test them all. Two of the 12 I ordered had open coils. And put a diode across any relay coils. The Arduino already has pull-up/pull-down diodes on all the pins, which is why the AD pins read around 2.5v if not connected. Remember, when you stop applying any power to a coil, the magnetic field collapses which produces a brief voltage spike. Also, any of the above reed relays can also be used as magnetic sensors to detect an open window, for instance. Just glue a small magnet nearby.

Figures 2 and 3

OP's picture

The LEDs shown in figures 2 and 3 are shorted as illustrated. The edge rows on most (if not all) breadboards are buses.

Ground wires and tty

SomeTom's picture

Right. Also the ground wire of the rightmost LED does not connect anywhere. It should be in the same column as the LED it is supposed to ground.
If you are using a recent version of Arduino (and a newer original board) you are more likely to find /dev/ttyUSB0 that /dev/ttyACM0. (Just a typo, but /dev/tttyACM0 won't do any good at all).

Free Dummies Books
Continuous Engineering


  • What continuous engineering is
  • How to continuously improve complex product designs
  • How to anticipate and respond to markets and clients
  • How to get the most out of your engineering resources

Get your free book now

Sponsored by IBM

Free Dummies Books
Service Virtualization

Learn to:

  • Define service virtualization
  • Select the most beneficial services to virtualize
  • Improve your traditional approach to testing
  • Deliver higher-quality software faster

Get your free book now

Sponsored by IBM