robot with arduino

60
T he beast needed a hefty battery for power, and with the battery alone weighing some 15 pounds, I needed a sturdy frame to keep everything together. Constructed of aluminum, the robot measured 18 inches square by almost three feet high, and required heavy duty and expensive gear motors — all this just to meander down the hallway and scare the &@%! out of my cat. Five years and over $1,500 later, I put “Maximillian” to rest, pulling its parts to use in other projects. Robot electronics were shrinking, and that meant robots themselves were getting smaller. Innovations like the BASIC Stamp made it much easier to experiment with low cost, self-contained microcontrollers — perhaps the ideal robotic brain. Microcontrollers are now so commonplace that you have your pick of hundreds of makes and models; from the super simple, to the confoundedly complex. Somewhere in the middle is the Arduino — a small and affordable microcontroller development board that’s fast becoming something of a superstar. Why the Popularity? Sure, the Arduino is a capable little critter able to handle the most common things microcontrollers can do. And let’s not forget that some of its fame has to do with price: the standard Arduino costs about $30, assembled and tested. Even less if you want to build it from a kit. Then there’s its free programming software. Using a standard USB cable, it lets you easily connect the Arduino to your computer — Windows, Mac, or Linux — and begin working in minutes. The programming editor is simple to use and comes with several dozen examples to get you started. What’s really made the Arduino a darling of geeks the world over is this: Both its hardware design and software are open source. That means others are able to take the best ideas and improve on them, all without paying licensing fees. This has created something of a cottage industry of fans and third-party support. Though the most popular version of the Arduino is made by a company in Italy (where the board was originally developed), many others offer compatible designs in one form or another. Add to this a growing body of add-ons that maximize the Arduino, and free resources for programming examples, code libraries, and step-by-step tutorials. Making Robots With The 56 SERVO 11.2010 Twenty years ago, I began work on my ultimate home robot. Its brain was an Intel 80286-based PC motherboard, running at a whopping 8 MHz. The robot used a floppy disc drive to load the operating system and programs, and custom prototype boards for external interfacing. Arduino Part 1 By Gordon McComb worldmags worldmags

Upload: lee

Post on 29-Nov-2014

1.640 views

Category:

Documents


14 download

TRANSCRIPT

Page 1: Robot With Arduino

The beast needed a hefty battery for power, and withthe battery alone weighing some 15 pounds, Ineeded a sturdy frame to keep everything together.Constructed of aluminum, the robot measured 18

inches square by almost three feet high, and required heavyduty and expensive gear motors — all this just to meanderdown the hallway and scare the &@%! out of my cat.

Five years and over $1,500 later, I put “Maximillian” torest, pulling its parts to use in other projects. Robotelectronics were shrinking, and that meant robotsthemselves were getting smaller. Innovations like the BASICStamp made it much easier to experiment with low cost,self-contained microcontrollers — perhaps the ideal roboticbrain. Microcontrollers are now so commonplace that youhave your pick of hundreds of makes and models; from thesuper simple, to the confoundedly complex. Somewhere inthe middle is the Arduino — a small and affordablemicrocontroller development board that’s fast becomingsomething of a superstar.

Why the Popularity?

Sure, the Arduino is a capable little critter able to

handle the most common things microcontrollers can do.And let’s not forget that some of its fame has to do withprice: the standard Arduino costs about $30, assembledand tested. Even less if you want to build it from a kit.

Then there’s its free programming software. Using astandard USB cable, it lets you easily connect the Arduinoto your computer — Windows, Mac, or Linux — and beginworking in minutes. The programming editor is simple touse and comes with several dozen examples to get youstarted.

What’s really made the Arduino a darling of geeks theworld over is this: Both its hardware design and softwareare open source. That means others are able to take thebest ideas and improve on them, all without payinglicensing fees. This has created something of a cottageindustry of fans and third-party support.

Though the most popular version of the Arduino ismade by a company in Italy (where the board was originallydeveloped), many others offer compatible designs in oneform or another. Add to this a growing body of add-onsthat maximize the Arduino, and free resources forprogramming examples, code libraries, and step-by-steptutorials.

Making RobotsWith The

56 SERVO 11.2010

Twenty years ago, I began work on my ultimate home robot. Its brain wasan Intel 80286-based PC motherboard, running at a whopping 8 MHz. Therobot used a floppy disc drive to load the operating system and programs,and custom prototype boards for external interfacing.

ArduinoPart 1

By Gordon McComb

worldmags

worldmags

Page 2: Robot With Arduino

Introducing Arduino Robotics

So, it makes sense to look at ways to leverage theArduino to build robots. That’s exactly what we’ll be doingin this article and several more to follow in the monthsahead. I’ll show you how to build, program, and use aneconomical and expandable autonomous desktop robot — the ArdBot — that’s powered by an Arduino. Cost of theproject is under $85 — even less if you already have somebasic components like a solderless breadboard and hookupwire.

The robot base is simple to build and can beconstructed out of a variety of materials; no special toolsare required. I’ll demonstrate a version made of expandedPVC plastic, but you can use heavy cardboard, foam board,picture frame mat board, or most any other material youlike. (For your convenience, you can get the robot chassisprecut with all the hardware; see the Sources box for moreinformation.)

I believe in robot designs that let you explore andexperiment, and the ArdBot leaves plenty of room forexpansion and independent discovery. You can use therobot for line or wall following, maze solving, or generalmeandering around in a room. (Cat scaring optional.) Youcan also take the concepts presented here and design yourown version of the ArdBot — bigger or smaller, wheels ortracks — your choice.

In this installment, you’ll learn all about the Arduino:what it’s made of, how to connect it to your computer, andhow to start developing robot projects for it. You’ll also beintroduced to the ArdBot chassis, including where to get itsmain parts. In coming installments to this series, you’llexplore programming the robot to do interesting things,and extending its features with sensors and other add-ins.

Arduino Under the Hood

First introduced in 2005, the Arduino has gone throughnumerous iterations, revisions, andimprovements. As I’m writing this, theArduino team just released their newestversion: the Arduino Uno (see Figure 1).Like its predecessors, the Uno is an all-in-one development board. It contains anAtmel AVR microcontroller — specificallythe ATmega328 — a USB-to-serialinterface, five volt voltage regulator, andvarious support electronics.

Previous iterations of the Arduinohave included the Duemilanove (whichmeans 2009 in Italian) and the Diecimilawhich means 10,000 (a reference to the

number of Arduino boards that had been manufactured bythat time; many more have been made since).

The Uno, Duemilanove, and Diecimila are what mightbe called main or core board designs. These all share acommon form factor which is a PCB that measures 2-1/8”by 2-3/4”. All contain a power jack for a 2.1 mm (centerpositive) barrel connector, as well as a USB Type B jack forhooking up to a host computer.

A series of 28 female pin headers allow connection ofexternal devices to the Arduino. The headers are separatedinto three groups as shown in Figure 2. The groups are:power, analog input, and digital input/output. Of the 28pins, 20 are devoted to input and output. There are sixanalog input pins which can also serve as general-purposedigital I/O. The 14 digital input/output pins include six thatcan be used to generate PWM (pulse width modulated)signals; these are useful for such things as controlling the

SERVO 11.2010 57

FIGURE 2. Points of interest on the Arduinoboard include the USB and power jacks,function and power LEDs, and rows of

connection headers.

FIGURE 1. The Arduino Duo is a compact microcontroller boardbased on the Atmel ATmega328 chip. It’s available from a

number of sources at about $30 average retail.

www.servomagazine.com/index.php?/magazine/article/november2010_McComb

worldmagsworldmags

worldmags

Page 3: Robot With Arduino

speed of motors. Through its I/O pins, the Arduinosupports the basic inter-communications standards: TTLserial, SPI, 1-Wire, and I2C. Two of its pins (digital I/O lines2 and 3) support hardware interrupts that via softwaretrigger on a LOW value, a rising or falling edge, or achange in value.

Like any microcontroller, the Arduino is basically a smallsingle-board computer designed to interface to external

hardware like switches, motors, lights, relays, sensors, andLEDs. At the heart of the Arduino is an Atmel AVRmicrocontroller. The exact version of AVR controllerdepends on the version of the Arduino. For example, theolder Diecimila and the first Duemilanove versions used anAVR ATmega168; the second generation Duemilanove(referred to as 2009b) as well as the Uno, use the AVRATmega328. The ‘328 is physically identical to the ‘168 butit contains more memory space. See Tables 1 and 2 fordetails on variations between the controller chips used.

The bulk of the components on the Arduino aresurface-mount, but on most Arduino boards the AVRmicrocontroller is provided in a dual inline pin (DIP)package. This permits easy replacement should that ever beneeded. A new AVR chip costs maybe $5 or $6; that’s a lotcheaper than replacing the entire Arduino board.

Keep in mind that the AVR provided in commerciallymanufactured Arduino boards comes with a bootloaderprogram pre-installed in its Flash memory. This bootloaderallows you to program the Arduino by using a USBconnection to your PC. When replacing the AVRmicrocontroller of an Arduino, you need to either purchasea chip with the bootloader software pre-installed, or if youhave the proper hardware setup — like an Atmel STK500programmer — you can do it yourself. Instructions fordownloading bootloader software into an AVR chip areprovided on the main Arduino information page.

Many Variations on a Theme

The core board designs of the Uno, Duemilanove, andDiecimila are perhaps the most common and popular of theArduinos, but there are numerous other variations. Here arejust some of the standardized Arduino boards you’llencounter. The Arduino BT and Fio are intended for wirelessapplications. The BT contains a Bluetooth module; the Fiohas a built-in Zigbee radio. (You can also readily addBluetooth and Zigbee to an Uno or other core board using“shields” detailed below.)

The Nano is a compact stick-shaped board made forbreadboard use. It has all the main features of the Uno andothers (including built-in USB jack), but measures only 0.73”x 1.7”. It uses only surface-mount parts.

The Mini is even smaller, and is ideal for very small botswith limited space. The Mini lacks its own USB jack, andrequires the use of a USB adapter or serial TTL connectionto the host PC for programming. The Mini has four analoginput pins instead of the six or eight of the other versions.

The Mega2560 is based on a larger AVR chip, and itoffers over three times the number of analog and digitalI/O lines (see Table 3). Memory and program space arebigger, too. The Arduino Mega2560 contains 256 KB ofFlash (by comparison, the Uno has 32 KB), as well as moreRAM and EEPROM space. Use this for the bigger jobs.

Several Arduino resellers (such as Solarbotics andAdafruit) offer their own custom offshoots of the Arduino— these typically go by different names such as Boarduino

58 SERVO 11.2010

Table 1. Arduino at a Glance.

Arduino Version Microcontroller Supports StandardExpansion Shields

Uno andDuemilanove

(2009b)ATmega328 Yes

Duemilanove(pre-2009b) and

DiecimilaATmega168 Yes

Mega 2560 ATmega2560 No

Nano, Mini,LilyPad, others

ATmega168 orATmega328 No

Table 2. MicrocontrollerSpecifications.

ATmega168 ATmega328 ATmega2560

Flash memory16 KB; 2 KB

used by bootloader

32 KB; 0.5 KBused by

bootloader

256 KB; 8 KBused by

bootloader

SRAM 1 KB 2 KB 8 KB

EEPROM 512 bytes 1 KB 4 KB

Clock speed 16 MHz 16 MHz 16 MHz

Table 3. Arduino Pin Resources.

Arduino Uno, Duemilanove, and Diecimila

Digital I/O Pins 14 (of which six provide PWM output)

Analog Input Pins 6

Nano

Digital I/O Pins 14 (of which six provide PWM output)

Analog Input Pins 8

Mega 2560

Digital I/O Pins 54 (of which 14 provide PWM output)

Analog Input Pins 16

worldmagsworldmags

worldmagso

Page 4: Robot With Arduino

or Freeduino to differentiate them from the original Arduinodesigns. The Adafruit Boarduino (available in kit form forunder $18) is like the Arduino Nano. It uses thru-holecomponents for ease of soldering.

Some variations of the Arduino depart from thestandard form-factor of the Uno, and are not designed foruse with expansion shields (discussed below). A goodexample is the LilyPad — a special Arduino layoutengineered for making (among other things) wearablemicrocontroller projects. Think Borg implants, only morefriendly looking. The flower-shaped LilyPad has a flat profileand can be sewn into fabric. It has connection points onthe ends of its 22 petals.

With so many variations of the Arduino floatingaround, it’s easy to get confused. For the ArdBot, we’ll beusing an Arduino Duo, but you can readily substitute justabout any of the other versions. If you already have anearlier Duemilanove or even Diecimila, you can use it withthe ArdBot. The only catch is that you’ll need to make sureyou have an up-to-date Arduino programming environmentinstalled on your computer. I’ve tested everything withversion 0019 of the Arduino programming IDE (discussedlater), so with that version or anything later you should begood to go.

Ready Expansion Via Shields

The Arduino is an example of the KISS principle. Itssimple design helps keep costs down, and makes theArduino a universal development board adaptable to justabout anything. While there are more expensive specialtyversions of the Arduino made for robotics applications, thebasic board lacks connectors to directly attach to motors,sensors, or other devices.

The Arduino itself has no breadboard area, but it’s easyenough to connect any of the inputs or outputs to a smallbreadboard via wires. For an application like robotics, you’llwant to expand the Arduino I/O headers to make it easierto plug in things like motors, switches, and ultrasonic orinfrared sensors.

One method is to use an add-on expansion boardknown as a shield. These stick directly on top of the coreboard designs (Uno, Duemilanove, and Diecimila). Pins onthe underside of the shield insert directly into the Arduino’sI/O headers. Two popular expansion shields are thesolderless breadboard and the proto shield; both provideprototyping areas for expanding your circuit designs.

Of course, you don’t absolutely need a shield to expandthe Arduino. You can place a breadboard — solderless orotherwise — beside the Arduino, and use ribbon cables orhookup wire to connect the two together. This is theapproach we’ll be using with the ArdBot described in thisseries of articles.

USB Connection and Power

To allow the easiest possible means of programming,

the Arduino Duo and related core boards support on-boardUSB. You merely need to connect a suitable USB cablebetween the Arduino and your computer. The cable evenprovides the power to the board. The necessary USB driversare provided with the Arduino software. In most cases,installation of the drivers is not fully automatic, but thesteps are straightforward and the Arduino support pagesprovide a walk-through example.

The Arduino accepts a standard USB Type B connector.Your PC probably uses the larger Type A connector, so youneed a Type A to Type B USB cable. Keep in mind thatsome PCs and laptops may use Mini-A or Mini-B connectors,so check first before purchasing a cable for use with theArduino.

Operating voltage of the Arduino circuitry is five voltswhich is supplied either by the USB cable when it’s pluggedinto a USB port on your computer, or by a built-in linearregulator when the board is powered externally. Theregulator is intended to be powered by 7-12 VDC; a nine

Main ComponentsThis is a selected list of North American sources for themain components for the ArdBot.

Arduino Duo or DuemilanoveSource Item or SKUAdafruit 50HVW Tech 28920 (Freeduino SB)RobotShop RB-Ard-03SparkFun DEV-09950

Solderless breadboard, 170 tie-pointsSource Item or SKUAdafruit 65HVW Tech 21380Parallax 700-00012RobotShop RB-Spa-139

Continuous rotation servo (Futaba spline)Source Item or SKUParallax 900-00008Pololu 1248RobotShop RB-Gws-23 Solarbotics 36000SparkFun ROB-09347

2-1/2” or 2-5/8” rubber wheels (Futaba spline)Source Item or SKUAdafruit 167HVW Tech,Solarbotics SWParallax 28109Pololu 226RobotShop RB-Sbo-86

SERVO 11.2010 59

worldmagsworldmags

worldmags

Page 5: Robot With Arduino

volt battery is ideal. Anything higher than 12 volts is notrecommended as it could cause the regulator to overheat.

For robotics, I think it’s best to power the Arduino fromits own battery. The ArdBot uses a split supply where theArduino is powered by a nine volt transistor battery; a

separate four-cell AA battery holder is used for servomotors and other components that don’t require voltageregulation.

Indicator LEDs are provided on the Arduino for testingand verification. A small green LED shows power; two otherLEDs show serial transmit and receive activity and shouldflash when the board is being programmed from yourcomputer. A fourth LED is connected in parallel with digitalI/O line 13 and serves as a simple way to test the Arduinoand make sure it is working properly. We’ll use this featurein a simple example later on in this article.

Programming the Arduino

Microcontrollers depend on a host computer fordeveloping and compiling programs. The software used onthe host computer is known as an integrated developmentenvironment, or IDE. For the Arduino, the developmentenvironment is based on the open source Processingplatform (www.processing.org) which is described by itscreators as a “programming language and environment forpeople who want to program images, animation, andinteractions.“

The Arduino programming language leverages an opensource project known as Wiring (wiring.org.co). TheArduino language is based on good old-fashioned C. If youare unfamiliar with this language, don’t worry; it’s not hardto learn, and the Arduino IDE provides some feedbackwhen you make mistakes in your programs.

60 SERVO 11.2010

FIGURE 3. The Arduino integrated development environment (IDE)provides a centralized place to write, compile, and downloadprograms to the Arduino board.

Adafruit Industrieswww.adafruit.comArduino resellers and custom shield projects. Convenientpremade nine volt battery clip and 2.1 mm barrel connector(see product #80), and nine volt battery holder with switch(product #67).

Arduino www.arduino.ccThe main Arduino site provides downloads, tutorials, references, design schematics, and other information usefulfor learning about and using the Arduino family of boards.

Atmelwww.atmel.com/products/AVRManufacturers of the AVR microcontrollers used in theArduino. See their site for datasheets (in PDF format).

Budget Roboticswww.budgetrobotics.comCustom machined decks, servo mounting hardware, andassembly hardware for the ArdBot.

Freeduinowww.freeduino.orgHome of the Freeduino collaborative project.

HVW Technologieswww.hvwtech.comReseller of Arduino products and manufacturer (with Solarbotics) of the Freeduino SB.

Parallaxwww.parallax.comNot resellers of Arduino, but they offer continuous rotationservos, wheels, and sensors.

Pololuwww.pololu.comWheels, continuous rotation servo motors.

RobotShopwww.robotshop.ca (Canada); www.robotshop.us (US)Full service retailer carrying most all of the official Arduino lineup, plus servo motors, solderless breadboards,and sensors.

Solarboticswww.solarbotics.comContinuous rotation servos, five-cell AA battery packs with attached 2.1 mm barrel connector, Arduino, andArduino-clone boards.

SparkFun Electronicswww.sparkfun.comReseller of the Arduino and manufacturer of customArduino-like hardware.

Sources

worldmagsworldmags

worldmags

Page 6: Robot With Arduino

If you’ve dabbled in Basic, you just need to rememberthat in C, keywords and variables are case sensitive. Insteadof using If/End If, in C, code blocks are grouped togetherusing the { and } (brace) characters. Statements areterminated with a ; (semi-colon) character, rather than just asimple line break. Any other differences, you’ll pick upquickly.

To get started with programming your Arduino, first goto: http://arduino.cc and then click on the Download tab.Find the platform link (PC, Mac, Linux) for your computerand download the installation file. Step-by-step instructionsare provided in the Getting Started section of the Arduinowebsite. Be sure to read through the entire instructions.

Be aware that the main Getting Started sectionassumes you’re using an Arduino Uno, Duemilanove, Nano,or Diecimila board. If you’re using another version of theArduino, be sure to check out its corresponding page onthe site.

Once installation is complete, you’re ready to try outyour Arduino. Start by connecting the board to your PC viaa USB cable. If this is the first time you’ve used an Arduinoon your PC, you must install the USB communicationsdrivers, as detailed in the Getting Started guide.

Using the Arduino programming environment is simple.First-time use of the environment requires you to specify theArduino board you are using, and as necessary, the serialport that is connected to the board (the Arduino’s USBconnection looks like a serial port to your computer). Youmay then open an existing example program which is calleda sketch in Arduino parlance, and download the program toyour board. Or, you may write your own sketch in the IDEeditor. Figure 3 shows the Arduino IDE with a short sketchin the main window.

After writing or opening an existing sketch, you needto compile it which prepares the code for downloading tothe Arduino. The Arduino IDE calls compiling a programverifying. At the bottom of the text editor is a statuswindow which shows you the progress of compiling(verifying). If the sketch is successfully compiled, it can thenbe downloaded to the Arduino where it will automaticallyrun once the download is complete.

Programming for Robots

As you go through the list of programming statementsavailable in the Arduino IDE (choose Help->Reference), youmight think there isn’t much power for doing things likerunning servos, operating stepper motors, readingpotentiometers, or displaying text on an LCD.

Like most any language based on C, the Arduinosupports the notion of “libraries” — code repositories thatextend core programming functionality. Libraries let you re-use code without having to physically copy and paste itinto all your programs. The standard Arduino softwareinstallation comes with several libraries you may use, and you can download others from the Arduino supportpages and from third-party websites that publish

Arduino library code.A good example of a library you’ll use with the ArdBot

— and likely many other robot projects — is Servo. Thislibrary allows you to connect one or more hobby R/C servosto the Arduino’s digital I/O pins. The Servo library comeswith the standard Arduino installation package, so adding itto your sketch is as simple as choosing Sketch->ImportLibrary->Servo. This adds the line

#include <Servo.h>

which tells the Arduino IDE that you wish to include theServo library in your sketch. With the functionality of thelibrary now available to you, you can use its variousfunctions to control one or more servos. For example, you can use the write function to rotate a servo to aspecific position, from 0 to 180 degrees. The followingcode

myServo.write(90);

moves a servo to its midpoint, or 90 degree position.Structurally, Arduino sketches are very straightforward

and are pretty easy to read and understand. The Arduinoprogram contains two main parts: setup() and loop(). Theseare programming functions that do what their namessuggest: setup() sets up the Arduino hardware, such asspecifying which I/O lines you plan to use, and whetherthey are inputs or outputs. The loop() function is repeatedendlessly when the Arduino is operating.

SERVO 11.2010 61

FIGURE 4.Schematic forListing 1testing circuit.

worldmagsworldmags

worldmags

Page 7: Robot With Arduino

Experiment By Doing

Listing 1 demonstrates a few fundamental Arduinoconcepts useful in any robotics development — that is,

reading an analog sensor and providing visual feedback.I’ve taken one of the examples that comes with theArduino IDE and modified it slightly to conform to the stylewe’ll be using throughout this series of ArdBot articles. Ituses a 10 kΩ potentiometer to alter how fast Arduino’sbuilt-in LED flashes.

Check out Figure 4 for a schematic of the circuit usedfor the program listing; Figure 5 shows a pictorialbreadboard view of connecting the potentiometer to theArduino hardware. The potentiometer is connected to theboard as a common voltage divider. That way, the Arduinodetects the value of the pot as a variable voltage from zerovolts (ground) to five volts.

Note that I’m using a standard mini solderlessbreadboard with 170 tie-points. The breadboard serves as aprototyping area for connecting to various hardware, and ispart of the ArdBot. You can use any other size of solderlessbreadboard, but none of the circuits for the ArdBot willrequire anything bigger.

Here’s how the program works:

The first two lines set variable constants, so hardwareconnected to the various I/O pins can be referred to byname and not pin number. This is merely for ourconvenience. The built-in LED is connected to pin 13, andthe potentiometer — named POT in our program — isconnected to analog pin 0.

Another variable is defined to hold the current value ofthe potentiometer which will be a number from 0 to 1023.This number is derived from the Arduino’s integrated 10-bitanalog-to-digital (ADC) converter, and it represents avoltage level from zero volts to five volts.

The setup() section gets the Arduino hardware readyfor the rest of the program. When first powered on, all theI/O lines are automatically defined as inputs. The LED pinneeds to be an output, however, so that distinction isdefined here. The programming statement that changes thefunction of an I/O line is pinMode. It expects two values(called arguments): the number of the I/O pin — in thiscase, it’s 13 as defined by the LED variable — and whetherthe pin is an OUTPUT or an INPUT.

The loop() section is automatically started the momentthe program has been downloaded to the Arduino. Thelooping continues until the board is either unplugged, thereset button on the Arduino is pushed, or a new program isloaded into memory. The loop begins by reading thevoltage on analog pin 0 — remember, it’s defined in thePOT variable at the top of the program. The program thenturns the LED on, and waits for a period of time defined bythe current position of the potentiometer before turningthe LED off again.

The waiting period is in milliseconds (thousandths of asecond), from 0 to 1023, the range of values from theArduino’s ADC. Very fast delays of about 100 millisecondsor less will appear as a steady light. You’ll be able to seethe LED flash with longer delays.

62 SERVO 11.2010

Listing 1

#define LED 13 // LED to digital pin 13#define POT 0 // pot to analog pin 0int potValue = 0; // variable for pot value

void setup() { // initialize digital 13 pin as an outputpinMode(LED, OUTPUT);

}

void loop() {potValue = analogRead(POT); // read pot

// value digitalWrite(LED, HIGH); // turn LED ondelay(potValue); // wait for pot

value// (milliseconds)

digitalWrite(LED, LOW); // turn LED offdelay(potValue); // wait for pot

value (milliseconds)}

FIGURE 5. Breadboard layout for Listing 1 testing circuit. Thepotentiometer is 10 kW, linear taper.

worldmagsworldmags

worldmags

Page 8: Robot With Arduino

Quick View of the ArdBot

Figure 6 shows the prototype ArdBot, made of 6 mm (about 1/4”) expanded PVC. In the nextinstallment, I’ll provide detailed construction plans,but here’s the robot in a nutshell:

• Two 7” “decks” provide generous room formotors, batteries, Arduino, and mini solderlessbreadboard, as well as future expansion. Thetop deck is secured by four machine screws to a set of 1-3/4” long aluminum hex standoffs.

• Two standard size continuous rotation servosdrive the robot using the differential steeringtechnique where the speed and direction ofeach motor determines where the robot travels.

• Half-inch wide tires provide traction indoors andout. The wheels measure 2-1/2” in diameter,and directly connect to the servo shafts.

• To keep costs down the ArdBot doesn’t usewheel casters or ball transfers. Instead is usestwo height-adjustable skids fore and aft whichkeep the robot level. The skids have roundedbottoms and act just like small rollers.

The bottom deck is used for mounting the servos andbattery packs. The deck is large enough for several four- orfive-cell AA battery holders, plus a nine volt cell or custombattery packs. There’s room in the corners of the deck formounting infrared, bump switch, or other sensors.

The top deck provides open access to the Arduino andsolderless breadboard, both of which you can placeanywhere you want. This way, you can program andreconfigure the board without anydisassembly of the robot. There’sroom for servo turrets,accelerometers, GPS receivers,sensor modules, and more. In theevent you need even more room foryour experiments, you can add athird deck for an additional 35square inches of space.

The ArdBot is a universal designwith components you can get froma variety of suppliers. See theSources box for a list of onlineretailers that sell the Arduino andother parts. You can build theArdBot platform yourself, or if youdon’t like mechanical construction,

as a convenience to SERVO readers, you can get the twobody decks and all mounting hardware from my Internetcompany, Budget Robotics.

So much for the basics. See you next time for detailedconstructions plans of the ArdBot and more. SV

About the AuthorGordon McComb is the author

of Robot Builder’s Bonanza. He can be reached at

[email protected].

FIGURE 6. Prototype ArdBot, a double-decker desktop robotusing the Arduino Duo or similar controller board. It’s designed

for easy expansion and experimentation. Construction will be covered in Part 2.

SERVO 11.2010 63

worldmagsworldmags

worldmags

Page 9: Robot With Arduino

In the last installment, we introduced the ArdBot andits central Arduino brain. This month, we’ll continuethe discussion with full construction plans for theArdBot. I built the reference design using 1/4”

expanded PVC plastic, but you can use wood, acrylic, foamboard, picture frame mat, or most anything else that is rigidenough for the components.

ArdBot Basic Design

The ArdBot uses two “decks” for mounting a pair ofservo motors, batteries, microcontroller, small prototypingboard, and other components you’d like to experimentwith. The bottom deck is basically a 7” diameter circle withcutouts for the wheels. The top deck is the same 7”diameter circle with the side lobes cut off.

The decks are separated by a set of four 1-3/4” longstandoffs. The actual length of the standoffs is not reallyimportant. You can make them shorter or longer — 1-1/2”

is the practical minimum and 3” the maximum.While it’s a bit more challenging to cut circles to make

a robot base, it’s the best overall shape for navigating tightplaces like mazes or the corner of a living room. Theconcept of the ArdBot is flexibility, however. There’s noreason your version must be circular. You can make asquare bot if you’d like, or cut off the corners of the squareto make an octagon.

If you don’t want to construct the mechanical pieces ofthe ArdBot at all, you can get them precut with all thehardware; see the Sources box. ArdBot is designed forexpandability. If the twin decks do not provide enoughspace for all your experiments, you can add more decks. Idon’t recommend any more than three decks total, as anymore may pose a weight problem for the drive system.

The brain of the ArdBot is an Arduino Uno — the latestof the all-in-one core designs of the Arduino. If you alreadyown an earlier version of the board — a Diecimila orDuemilanove — those will work, too. The only requirementis that you have version 0017 or later of the Arduinoprogramming environment. The ArdBot project was createdand tested using version 0019 — the latest as of thiswriting. Complementing the Arduino microcontroller boardis a mini solderless breadboard. It has 170 tie points —

Making RobotsWith The

The ArdBot is a low-cost, 7” diameter servo-driven robot base, ready forexpansion. It’s called ArdBot because it’s based on the popular and inexpensive Arduino microcontroller board. The ArdBot costs under $80 tobuild; even less if you already have some of the components, like thebreadboard, jumper wires, and battery holder.

ArduinoPart 2

By Gordon McComb

In preparing Part 1 of this series, I made a last-minutechange to include the new Ardunio board that's just beenreleased. Only I got the name wrong — in several places inthe article, I referred to the new board as the Duo. Thecorrect name for the board is the Uno.

52 SERVO 12.2010

worldmagsworldmags

worldmags

Page 10: Robot With Arduino

enough for the basic experiments we’ll be doing in thisseries of articles. Don’t let the small size of the breadboardlimit you. The ArdBot is large enough for biggerbreadboards, even multiple boards, should you need them.You might want to start with the mini breadboard, then asyou use the ArdBot for further experiments you can addmore prototyping space.

About the Servo Drive

The ArdBot uses differential steering where the base ispropelled by two motors and wheels on opposite sides. Tokeep costs down and minimize construction complexity, therobot uses a pair of skids placed in the front and rear toprovide balance. With this arrangement, the ArdBot is ableto move forward and back, turn left and right, and spin inplace. The skids are smooth and polished metal, so theypresent little drag on whatever surface the robot is rollingover. Even so, the ArdBot is best suited for travel on hardsurfaces or carpet with a short nap.

The two drive motors run off their own battery supplywhich is a set of four AA rechargeable or non-rechargeablecells. The motors are standard size radio control airplaneservos that have been modified for continuous rotation.

The ArdBot reference design uses servos that comefrom the factory already modified so you don’t have tohack them. I used a pair of GWS S-35 servos, but there areothers available (see Sources) for under $15 each. I won’tprovide instructions here on how to modify a servo forcontinuous rotation. That subject has been tackled in pastissues of SERVO and Nuts & Volts, so I’ll leave it at that.

Making the ArdBot Base

The ArdBot is constructed with four body pieces heldtogether with hardware fasteners. Table 1 provides a fulllist of mechanical parts. Tables 2 through 5 specify theother components to complete the ArdBot.

All body pieces assume 1/4” thick material. For yourreference, Figure 1 shows a completed ArdBot, ready to beprogrammed and played with. The body pieces include:

• Bottom deck measuring 7” diameter with cutouts forthe wheels (see Figure 2). The deck includes anumber of holes, of which only six are required. Anyother holes are up to you. I’ve included severaladditional holes at the front and back of the deck formounting bumper switches and other sensors. Thewheel cutouts measure 2-5/8” x 7-5/8”; sized forcommonly available 2-1/2” or 2-5/8” diameter roboticwheels for R/C servo motors.

• Top deck measuring 7” x 5” (see Figure 3). Only fourof its holes are critical; these mate with matchingholes in the bottom deck using a set of fourstandoffs. A 1/2” diameter hole in the center (orthereabouts) provides a throughway for wires fromthe bottom deck. The other holes as shown are

optional, and are for attaching sensors and otheraccessories.

• Pair of servo mounts (see Figure 4) for attaching theservos to the bottom deck. You can make these

www.servomagazine.com/index.php?/magazine/article/december2010_McComb

Table 1. Mechanical Parts.

Qty Description

1 7” diameter bottom deck with wheel well cutouts for the drive wheels.

1 7” × 5” top deck.

2 Servo mounts.

490° plastic L brackets for attaching the servo mounts to the bottom deck. These brackets

measure 3/4” × 3/4” with hole centers at 3/8”, and are made to work with the two servo mounts.

16 4-40 x 1/2” machine screws and nuts for attachingthe servos and servo mounts to the bottom deck.

4Deck risers consisting of: (4) 1-3/4” aluminum

(or plastic) risers with 4-40 threads; (4) 4-40 × 1/2”pan head machine screws; and (4) 4-40 × 1/2”

flat head machine screws.

2 Skids consisting of: (2) 8-32 × 3/4” machine screws;(2) 8-32 hex nuts; and (2) 8-32 acorn (cap) nuts.

3Sets of mounting hardware for Arduino Uno, consisting of (3) 4-40 × 1/2” machine screws;

(3) 4-40 nuts; and (3) plastic washers.

* For your convenience, all mechanical pieces — includingprecut decks and servo mounts — at are available through

Budget Robotics. See the Sources box for details.

Table 2. Motors and Wheels.

Qty Description

2 Standard size R/C servo motors, modified for continuous rotation.

2 2-1/2” or 2-5/8 diameter wheels with hubs to attach to the servo motors.

FIGURE 1. The completed ArdBot with Arduino microcontrollerboard, solderless breadboard, servos, wheels, and all body parts.

SERVO 12.2010 53

worldmagsworldmags

worldmags

Page 11: Robot With Arduino

yourself or, if you choose, purchase them separately.If you make the mounts, be aware that sizing iscritical. The two holes on either side of the mountmust be spaced 3” apart to accommodate the samehole spacing in the bottom deck.

The base parts may be cut from stock measuring 12” x 12” which is a common size for expanded PVC or otherplastic purchased through mail order. A motorized scrollsaw is the perfect tool for cutting out the ArdBot basecomponents, but if you don’t have one handy, a copingsaw also works. Use a wood blade; it’ll work whetheryou’re making the base with aircraft-grade plywood(available at the hobby store), PVC, or other plastic.

If using foam board or picture mat, you can cut thepieces using a sharp hobby knife or mat cutter. The usualsafety precautions apply. A circle cutting jig makes perfect

circles when using these materials. If you don’t own acircular jig yourself, see if the local picture frame store willmake the cuts for you. When using picture mat material,cut two of everything, and double-up the pieces for extrastiffness. Except for the large center hole in the top deck,all holes are drilled with a 9/64” bit.

Assembling the ArdBot

With the body pieces constructed (or purchased) andall other parts in hand, you’re ready to build your ArdBot.Here’s how.

Step 0Before assembly, you may want to use 150 grit

sandpaper to smooth the edges of the base parts. Orientthe bottom deck so that the holes are aligned as shown inFigure 5. Note that the holes for each servo are notsymmetrically placed on the deck. This is to accommodate

FIGURE 2. Layout pattern for cutting and drilling the bottomdeck of the ArdBot. The only truly critical dimensions are thecutouts for the wheels and the placement of the two sets of holesimmediately beside the wheel cutouts. These holes are for theservo mounts. See Figure 5 for a description of all holes.

Table 3. Electronic Parts.

Qty Description

1 Arduino Uno (or compatible) microcontroller board with USB programming cable.

1 Mini solderless breadboard; 170 tie points.

1Set of solderless breadboard wire jumpers (or make your own using 22 gauge solid

conductor wire).

1 AA x four battery holder, with female header connector; see text.

1 Nine volt battery clip, with 2.1 mm polarized barrel plug; see text.

1 Length of 12 (or more) breakaway 0.100” maleheader pins, double-sided (long) pins; see text.

Table 4. Power.Qty Description

4 AA alkaline or nickel metal hybride rechargable batteries.

1 Nine volt battery.

Table 5.Optional (but nice to have) Parts.Qty Description

1 Nine volt metal or plastic battery holder.

1Hook-and-loop (Velcro) strips for mounting battery holders and solderless breadboard;

small pieces of double-sided foam tape.

FIGURE 3.Layout

pattern forcutting anddrilling the

top deck ofthe ArdBot.

Critical holesare the four

small onesnearest the

center. Thesemust match

the fourservo

mountingholes in the

bottomdeck.

54 SERVO 12.2010

worldmagsworldmags

worldmagso

Page 12: Robot With Arduino

the offset of the servo drive shaft. While there istechnically no “front” or “rear” of the ArdBot, forthe purposes of assembly, the top of theillustration in Figure 5 is the front and thebottom is the rear.

Step 1Insert a servo into a servo mount by sliding it

back-end first through the mount. The fit may betight, depending on the make and model of theservo. (As necessary, enlarge the rectangle for theservo using a file or coarse sandpaper.) Do notforce the servo into the mount or the mount maybe damaged.

Secure the servo to the mount with 4-40 x1/2” screws and hex nuts (Figure 6). You can usefour screws for each servo, or only two. Whenusing two screws position them on oppositecorners of the servo mounting flange, as shown.

Repeat for the opposite servo and mount. Be sure toconstruct the second servo and mount in a mirror image tothe first! Refer to Figure 9 in Step 3 to see how the motorsshould be inserted into the mounts. For reference, also seeFigure 12 for an aerial view of the ArdBot and itscompleted bottom deck.

Step 2Using 4-40 x 1/2” machine screws and nuts, attach

two plastic L brackets to each of the servo mounts (Figure7). You’ll be make a “left” and a “right” mount assembly.

For the left mount assembly, the motor shaft shouldface to the left and toward the “top” of the deck (asreferenced in Figure 5). Attach the L brackets to the rightside of the mount. For the right mount assembly, the motorshaft should face to the right, also toward the top of thedeck. Attach the L brackets to the left side of the mount.

Insert the machine screws through the L bracket, thenthrough the servo mount. Secure on the other end with anut. Before tightening, be sure the bottom of the L bracketis flush with the bottom edge of the servo mount.

Step 3Attach the left mount assembly to the bottom deck

using two 4-40 x 1/2” screws and standoffs. The screwsshould come up from the underside of the deck, through

FIGURE 4. Layout pattern for cutting and drilling the servo mount. You’llneed two of these. If cutting the inside rectangle proves difficult, you can

instead make the mounts by cutting through at the dotted line. The mount will be a little more fragile, so handle it carefully.

Use all four screws to secure the servo in the mount, rather than just two.

FIGURE 5. Only four holes are critical for the bottom deck: the twosets marked Holes for servo mounting, and the front and rear Skid.

The rest are optional for sensors and other accessories you may want to add later.

FIGURE 6. Servo motor secured into one of the servo mounts.You need two of these.

SERVO 12.2010 55

worldmagsworldmags

worldmags

Page 13: Robot With Arduino

the L bracket, and then into the standoff as shown inFigure 8. When orienting the mount assembly, be sure thatthe servo shaft is centered in the wheel well cutout. Alignthe assembly so they are parallel with the wheel wellcutout, then tighten all the screws. Figure 9 shows howthe completed servo, mount, and standoffs should look.Repeat the same procedure for the right mount assembly.

Step 4Attach the front and rear skids as shown in Figure 10.

Each skid uses an 8-32” machine screw, hex nut, and acorn(cap) nut.

1. Using a screwdriver, thread a machine screw into thehole at the front and back of the deck (refer toFigure 5 for the location of these holes). The screwis inserted from the top of the deck (the side withthe servos). The holes for the skids are undersizedfor 8-32 machine screws. When using a soft materiallike wood or PVC plastic, the fastener will tap thehole as you screw it in. Continue threading the screwinto the hole until the head is about 1/4” from thedeck, as indicated in the picture.

2. Put the hex nut onto the screw, followed by theacorn nut. Tighten the acorn nut against the hexnut.

Repeat these steps for the other skid. You may adjustthe height of the skid by loosening or tightening themachine screw in the hole. If you need greater heightadjustment or the hole for the skid is too large to self-tap,

FIGURE 8. Secure the servo mounts to the bottom deck usingmachine screws and threaded standoffs.

The standoffs serve to separate the decks.

FIGURE 9. Here’s how the completed servo mount should lookwith standoffs in place.

FIGURE 10. ArdBot uses static skids (made with 8-32 metalfasteners) for front and back balance. You can adjust the height of each skid to compensate for the diameter of wheels you use.

FIGURE 7. Attach two L brackets to the servo mount. The Lbrackets should be flush with the bottom of the servo mount.

56 SERVO 12.2010

worldmagsworldmags

worldmags

Page 14: Robot With Arduino

merely use a longer machine screw and tighten into placeusing nuts on both the top and bottom of the deck, asshown in Figure 11.

Step 5Attach the wheels to the servos. Each wheel is secured

with a small self-tapping screw that is supplied with theservo. Note that the servo shaft is splined; this splinematches the wheel hub. Be sure to press the wheel ontothe shaft firmly while tightening the screw. Do not over-tighten the wheel mounting screw, but be sure the wheel ison snugly. Figure 12 shows the completed bottom deck ofthe ArdBot, with motors, mounts, and wheels attached.(I’ve bound the wire leads for the servos using cable ties tokeep things neat. You can do the same if you wish.)

Step 6Secure the side of the nine volt battery holder against

the side of the AA battery holder using a small piece ofdouble-sided foam tape or hook-and-loop (Velcro). Next,secure the AA battery holder to the approximate center ofthe bottom deck using a square or two of hook-and-loop tokeep it in place. Note the electrical connections for both thenine volt battery and the AA battery holder:

• The nine volt battery uses the traditional two-prongbattery clip, terminated on the other end with a 2.1mm barrel plug. This plug inserts into the power jackof the Arduino. You can make this power leadyourself by soldering a barrel plug onto a standardtwo-prong battery clip, or purchase one ready-made(see the Sources box). When constructing your own,be absolutely sure the + (positive) connection is thecenter of the plug; the – (negative) connection is theoutside of the barrel.

• The AA battery holder uses a female 0.100” pinheader connector. You can use a connector with twoor more pins; the additional pins can be used to help

assure proper polarity. With just two pins, you mustbe VERY careful to never (and I mean NEVER, EVER!)reverse the polarity of the connector. If you do, yourservos will be instantaneously and permanentlydamaged. By using (for example) a four pinconnector, you can block up one of the unusedterminals. This helps prevent you from reversing theconnector when you plug it in. (Of course, still becareful, no matter what system you use!) Insert freshbatteries into the holders and attach the clip to thenine volt battery. The holders with batteries areshown in Figure 13.

Step 7Find a favored spot on the top deck for your Arduino,

and mark three holes for mounting the board. Be sure not

FIGURE 12. The completed bottom deck of the ArdBot. Note theorientation of the servos in the mounts.

FIGURE 11. If you need additional height control for the skids or the hole for the skid cannot be threaded, use a longer 8-32 screw with hex nuts above and below the deck.

FIGURE 13. The bottom deck is large enough for several batterypacks, and they can be neatly placed in the center. The reference

design uses a nine volt battery to power the Arduino, and aholder with four AA cells to power the servo motors.

SERVO 12.2010 57

worldmagsworldmags

worldmags

Page 15: Robot With Arduino

to cover up any of the four holes used for securing the topdeck in place. Otherwise, you’ll have to remove the Arduinoin order to take off the top deck

Drill the three holes using a 9/64” bit. Secure theArduino board to the top deck using 4-40 machine screws,nuts, and plastic washers. The washers go between theheads of the screws and the board, and minimize thepossibility of a short circuit.

Mount the mini solderless breadboard so that it’s closeto the Arduino, but doesn’t block the 1/2” wiring accesshole in the top deck. Though most mini breadboards comewith double-sided self-adhesive tape, I recommend that youdon’t use the tape. Instead, mount the board using asquare or two of hook-and-loop. This allows you to easilyremove the board when you need to.

Step 8To complete the ArdBot, secure the top deck to the

standoffs using 4-40 x 1/2” flat head screws. Assuming youare using a soft material (wood, PVC plastic, foam board,etc.), the heads of the screws should countersink bythemselves as you tighten them and lay flush against thedeck. Thread the battery and servo leads through the centerhole of the top deck. To keep down cost and complexity,there are no power switches for the batteries, so leave thebattery leads unattached until you’re ready to program anduse the ArdBot. (When you’re done playing, be sure tounplug the batteries to keep them from draining.)

Two-Servo Wiring Plan

The Arduino lacks direct connections for attaching theservo motors. Instead, the mini breadboard providesprototyping space for connecting up both servos, as well asthe AA battery holder that powers the servos. Refer toFigure 14 (schematic) and Figure 15 (pictorial) for wiringthe solderless breadboard. Using a strip of 0.100” double-sided (long) male header pins, break off two sets of threepins, and one set of pins for the AA battery connection.

Note that you want the version of male header pinsthat are “double-sided” — they’re long on both sides. If youuse the standard header pins, the length of pins on oneside is shorter. These don’t make good contact when usedwith solderless breadboard designs. See the Sources boxfor a couple of mail order companies offering double-sidedlong header pins. In a pinch, you can use right-angle headerpins instead and straighten them out so that all the pins areflat. The reference design uses a AA battery holder with afour-pin female connector. The + and – leads are on thetwo outside positions of the connector. I’ve broken off thepin right next to the + connection of the male header, thenused a short piece of solid conductor hookup wire to fill inits corresponding hole in the connector. This prevents theconnector from being reversed when plugged in.

When wiring the solderless breadboard, be especiallycareful not to mix positive and negative leads to the servo.Reversing the power leads to a servo will permanently

Listing 1

/*ArdBot ServoTestTests servos of robot by moving them in different directionsRequires Arduino IDE version 0017 or later (0019 or later preferred)

*/

#include <Servo.h>

Servo servoLeft; // Define left servoServo servoRight; // Define rightservo

void setup() {

servoLeft.attach(10); // Set left servo to // digital pin 10

servoRight.attach(9); // Set right servoto

// digital pin 9}

void loop() // Loop through // motion tests

{ forward(); // Example: move

// forwarddelay(2000); // Wait 2000

// milliseconds // (2 seconds)

reverse();delay(2000);turnRight();delay(2000);turnLeft();delay(2000);stopRobot();delay(2000);

}

// Motion routines for forward, reverse, turns, // and stopvoid forward(){

servoLeft.write(0);servoRight.write(180);

}

void reverse(){

servoLeft.write(180);servoRight.write(0);

}

void turnRight(){

servoLeft.write(180);servoRight.write(180);

}

void turnLeft(){

servoLeft.write(0);servoRight.write(0);

}

void stopRobot(){

servoLeft.write(90);servoRight.write(90);

}

58 SERVO 12.2010

worldmagsworldmags

worldmags

Page 16: Robot With Arduino

damage it. Here’s an importantnote: The ArdBot uses separatebattery supplies for the Arduinoand the two servos. In order foreverything to function properly,the ground connections for theArduino and the servo batterysupply must be connectedtogether. This is shown in boththe schematic and pictorialcircuit views.

Make sure to also properlyorient the connectors for theservos when you plug theminto the board. Servo powerleads are color-coded, but thecolors aren’t universal.

• Ground (–) is typicallyblack or brown.

• Power (+) is most oftenred, and with modernservos is always in themiddle.

• Signal is white, yellow, orsometimes orange (buttake care — on someservos the power wire isorange!).

When in doubt, check the spec sheet that comes withyour servos. Don’t guess!

Servo Test Sketch

With the ArdBot constructed and the breadboardwired, you’re ready to test the robot and put it through itspaces. Refer to Listing 1 for a quick servo test sketch.

Start the Arduino IDE, connect a USB cable betweenyour computer and the Arduino (as noted on the GettingStarted pages of the Arduino website), and type theprogram as shown. When done, Verify(compile) the sketch and look for anysyntax errors. If there are none,download the sketch to your Arduino.

Once downloaded, put a smallbook under your ArdBot to lift itswheels off the ground. Disconnect theUSB cable, and — in this order — plugthe AA battery connector into thebreadboard, then plug in the nine volt

power to the Arduino power jack. (If you are using anArduino Diecimila, be sure to switch over the powerselection jumper from USB to EXTernal.) If everything isconnected properly, the servo motors should go through atest pattern.

Assuming the motors are working as they should,depress the Reset switch on the Arduino board and placethe ArdBot on the ground. Release the switch and therobot should perform its self-test maneuvers. If the motorsaren’t moving, double-check your wiring, making sure theservo connectors are properly oriented. They won’t work ifthe connectors are reversed on the breadboard.

FIGURE 15. Pictorial view of how toconnect the Arduino to the two servomotors. Note that the Arduino ground

connection is shared with the power for the servos. This is very important.

FIGURE 14. The wiring schematic for theArduino with two servos and separate power

supply for the motors.

SERVO 11.2010 59

worldmags

worldmags

Page 17: Robot With Arduino

Closer Look at the Test Sketch

Before closing out this month’s installment of the

ArdBot, let’s quickly review how the test sketch works. Firstoff is an include statement to the Servo.h library header filewhich is provided with the Arduino IDE installation. This fileand its corresponding C language program, provide all theactual coding to make the servos function.

Next comes two statements that create, or instantiate,two Servo objects for use in the remainder of the sketch.Each object represents a physical servo attached to theArduino. Methods of these objects include things likespecifying which digital pin is used to connect from theArduino to the servo, and the position of the servo. NoteI’ve given the two Servo objects descriptive names:servoLeft and servoRight. It’s easier to keep track of thingsthis way.

In the setup function, the servoLeft and servoRightobjects are “wired” to their respective pins on the Arduino;in this case, pin 10 for servoLeft and pin 9 for servoRight.

Now comes the main body of the program, provided inthe loop function. It contains a series of user-definedfunctions for forward, backward, and so on, plus a delay of2,000 milliseconds (two seconds) between each function.You can see that the robot repeats the same demonstrationsteps over and over:

• Goes forward for two seconds.• Reverses for two seconds.• Turns right for two seconds.• Turns left for two seconds.• Stops for two seconds.

Finally, each user-defined function specifies the specificmotion to apply to the servos.With the Servo object, servos arecommanded to move onedirection or another by (amongother ways) specifying an anglebetween 0 and 180. The servothen moves to that angle inresponse.

When using servos that havebeen modified for continuousrotation, 0 makes the servo rotateone direction; 180 makes theservo rotate in the oppositedirection; and 90 makes it stop.Pretty easy, isn’t it?!

In our next installment, we’lllook at servo programming indepth, as well as connecting somesensors to the ArdBot for reactivecontrol, getting feedback from therobot, and more! SV

Please note! The list of sources is not exhaustive, and ismerely designed to get you started in the right direction.There are other companies who sell these items, and not allsources are listed. Common parts like battery holders andbreadboard jumper wires are not included here, as they arereadily available at RadioShack and hundreds of onlineelectronics supply stores.

Check out www.fritzing.com for a user-to-user Arduinoproject community, including an Arduino development librarythat allows you to create virtual breadboard designs of yourprojects. You may then turn your projects into schematics andeven etchable circuit boards. We’ve used Fritzing to preparesome of the illustrations for this series of articles.

Sources

Gordon McComb can be reachedat [email protected].

Arduinowww.arduino.ccPrefabricated ArdBot bodypieces with all construction hardware.

Budget Roboticswww.budgetrobotics.com

AdaFruitwww.adafruit.com

HVW Techwww.hvwtech.com

Jamecowww.jameco.com

Parallaxwww.parallax.com

Pololuwww.pololu.com

Robotshopwww.robotshop.com

Solarboticswww.solarbotics.com

SparkFunwww.sparkfun.com

60 SERVO 12.2010

This is a selected list of North Americansources for the main components for theArdBot.

Arduino Duo or DuemilanoveSource Item or SKUAdafruit 50HVW Tech 28920 (Freeduino SB)Jameco 2121105RobotShop RB-Ard-03Pololu 1616SparkFun DEV-09950

Solderless Breadboard; 170 tie-pointsSource Item or SKUAdafruit 65HVW Tech 21380Jameco 2109801Parallax 700-00012RobotShop RB-Spa-139

Nine volt to 2.1 mm Barrel PlugCableSource Item or SKUAdafruit 80SparkFun PRT-09518

Continuous Rotation Servo

(Futaba spline)

Source Item or SKUParallax 900-00008Pololu 1248RobotShop RB-Gws-23 Solarbotics 36000SparkFun ROB-09347

2-1/2” or 2-5/8” Rubber Wheels

(Futaba spline)

Source Item or SKUAdafruit 167HVW Tech/Solarbotics SWParallax 28109Pololu 226RobotShop RB-Sbo-86

Double-sided (long) Male HeaderPinsSource Item or SKUParallax 451-00303Pololu 1065

Main Components Sources

worldmagsworldmags

worldmags

Page 18: Robot With Arduino

HandsOn Technology is a manufacturer of high quality educational and professional electronics kits and modules, uControllerdevelopment/evaluation boards. Inside you will find Electronic Kits and fully assembled and tested Modules for all skill levels. Please check back with us regularly as we will be adding many new kits and products to the site in the near future. Do you want to stay up to date with electronics and computer technology? Always looking for useful hints, tips and interesting offers?

http://www.handsontec.com

Inspiration and goals... HandsOn Technology provides a multimedia and interactive platform for everyone interested in electronics. From beginner to diehard, from student to lecturer... Information, education, inspiration and entertainment. Analog and digital; practical and theoretical; software and hardware... HandsOn Technology provides Designs, ideas and solutions for today's engineers and electronics hobbyists.

Creativity for tomorrow's better living... HandsOn Technology believes everyone should have the tools, hardware, and resources to play with cool electronic gadgetry. HandsOn Technology's goal is to get our "hands On" current technology and information and pass it on to you! We set out to make finding the parts and information you need easier, more intuitive, and affordable so you can create your awesome projects. By getting technology in your hands, we think everyone is better offWe here at HandsOn like to think that we exist in the same group as our customers >> curious students, engineers, prototypers, and hobbyists who love to create and share. We are snowboarders and rock-climbers, painters and musicians, engineers and writers - but we all have one thing in common...we love electronics! We want to use electronics to make art projects, gadgets, and robots. We live, eat, and breathe this stuff!!If you have more questions, go ahead and poke around the website, or send an email to [email protected]. And as always, feel free to let your geek shine - around here, we encourage it...

Page 19: Robot With Arduino

That’s the idea behind the ArdBot shown in Figure 1. It’sa low cost, expandable, and easy to build mobile robotbased on the popular Arduino microcontroller. Total cost

of construction is under $85, and even less if you already havesome of the common components, like RC servo motorsmodified for continuous rotation and a solderless breadboard.

The past two installments of this series introduced theArduino controller and the ArdBot chassis. Part 1 covered theArduino and why this $30 board is fast becoming a favoriteamong experimenters the worldover. Part 2 detailed the mechanicalconstruction of the ArdBot — aseven inch diameter desktop roverpowered by replaceable orrechargeable batteries and twin RCservo motors.

This time, you’ll learn moreabout the Arduino and itsprogramming. The Arduino leverages anumber of well supported open sourceprojects, and mashes them into aconvenient integrated developmentenvironment (IDE) that’s simple toinstall and easy to use. In futurearticles, you’ll apply what you learnhere to the ArdBot, including

writing your own motor control functions, responding tosensor feedback, and more.

A Closer Look at the Arduino

Arduino is more a concept than it is a specific product.Since its introduction in 2005, the Arduino microcontrollerboard has gone through many permutations, and eventoday there are over half a dozen “official” Arduino boards

that vary in size, shape, andcapabilities — add to this literallydozens of clone Arduinos that go byother names like Freeduino,Boarduino, and many others.

Figure 2 shows the Uno — oneof several Arduino boards — but onethat encapsulates the core set ofArduino functionality. It’s the latestversion of the most popular Arduinodesign which features a low costAtmel ATmega328 microcontrollermounted on a handy “stackable”development board. There are other

Making RobotsWith The

Part 3 -Inside the

ArduinoBy Gordon McComb

60 SERVO 01.2011

FIGURE 1. The ArdBot, with Arduinomicrocontroller and mini solderlessbreadboard for experimenting.

You can construct a fully autonomous programmable robot for less thanthe cost of dinner and a movie for two. Mind you, I’m not suggesting oneover the other — just pointing out that robots don’t have to be expensiveor difficult to build. It might have been true in the past, but it’s not now.

Arduino

worldmags

Page 20: Robot With Arduino

versions of the Arduino — bigger andsmaller — but it’s the 2-1/8” by 2-3/4” Unothat most people use, and the one selectedfor the ArdBot. (If you already have anearlier version Diecimila or Duemilanove,then those are okay, too, as long as you useversion 0017 or later of the Arduino IDE.)

Main points of interest of the ArduinoUno include:

• The ATmega328 microcontroller,running at 16 MHz. The board uses theDIP version of the ATmega328 so that ifyou “let the smoke out” of the thing, youcan easily replace just the chip, rather thanbuy a whole new Arduino board.

• Reset pushbutton. Press to reset the currently runningprogram.

• Integrated USB-to-serial communications, for bothdownloading programs from your PC and for serialcommunications back to the PC for debugging andmonitoring. The USB link includes a 500 mA resettablefuse to guard against possible damage caused by awayward Arduino to the USB ports on your PC. Whenplugged into a USB port, the Arduino takes its powerfrom it. With USB 2.0, drive current is limited to 500 mA,depending on the port design.

• DC power jack (2.1 mm, center positive) for use withan external power source. Recommended voltagerange is 7-12 volts.

• Low dropout regulators for 5Vand 3.3V. The five volt regulatorprovides up to 800 mA of current;the 3.3 volt regulator provides up to50 mA. Connection pins areprovided for both the 5V and 3.3Vregulated outputs. You can use thesepins to power low currentcomponents such as ultrasonicsensors or accelerometers.

• Indicator LEDs for power, serialtransmit and receive (labeled Tx andRx), and digital pin 13 (labeled L).

• Six-pin in-circuit serial programming(ICSP) header. This provides astandard connection with externalprogrammers for the Atmel AVRmicrocontroller chips.

• Six analog input/output (I/O) pinsand 14 digital I/O pins. The analogpins connect to an internal ten-bitanalog-to-digital converter (ADC),letting you read voltages fromsensors and other devices. All I/O

pins can be used as digital outputs, and can sink orsource up to 40 mA.

• Power pins to provide external access to theunregulated and regulated power supplies.

Let me pause here to point out that the ATmega328on the Uno board isn’t an empty chip; it contains a smallbootloader program for use with the Arduino developmenteditor. The bootloader assists in the download process. Youcan add the bootloader yourself (instructions are on thearduino.cc website), or you can buy a replacementATmega328 with the bootloader preinstalled.

Figure 3 shows the pin-out diagram of the 28-pinATmega328. The labels on the inside of the chip are the primaryfunction names for each of the pins. The labels outside in

www.servomagazine.com/index.php?/magazine/article/january2011_McComb

FIGURE 2. Pictorial overview of the mainpoints of interest on the Arduino Uno

microcontroller board.

SERVO 01.2011 61

While manufactured Arduino boardsare hardly expensive, you can go evencheaper by using the Uno as aprogrammer. Once you’ve downloadedyour sketch, remove the ATmega328 chipand transplant it into a solderlessbreadboard or other circuit. The chip runsunder five volts (4.5V minimum, 5.5Vmaximum), and only needs a 16 MHzcrystal and two 22 pF capacitors foroperation. You can even do away with thecaps if you use a 16 MHz three-pinresonator, and don’t need the extraprecision of a crystal oscillator.

Use an IC extractor tool to preventdamage to the ATmega328 pins when youremove it from the Arduino board. Thetool grips the ends of the chip and allowsyou to pull it straight out of its socket.

There isn’t even an absoluterequirement that you use an ATmega328with the Arduino bootloader preinstalled.You can use the Arduino developmentenvironment and download yourprograms directly into the chip. This

restores the Flash memory spacepreviously taken up by the Arduinobootloader. It also avoids theseveral seconds’ delay that occurs whenthe Arduino is first powered up; this delayis caused by the bootloader waiting to seeif a new program is about to arrive.

Programming without the bootloaderrequires suitable hardware, such as theAtmel STK500, AVR-ISP, or a homebrewparallel port programmer. The ArduinoUno has a suitable in-circuit serialprogramming (ICSP) header already onit. Just attach the six-pin cable from yourprogrammer to the ICSP header on theArduino.

Just so you know, serial programmingis just one method of burning softwareinto an AVR microcontroller. Many stand-alone programmers like the STK500 alsosupport what’s known as high-voltageprogramming which permits resetting certainsoftware fuse bits. These bits controlspecial behaviors of the chip, and aredocumented in the AVR datasheets.

The Chip-Only Arduino

worldmags

worldmags

Page 21: Robot With Arduino

parentheses are alternative uses — if any — for the pins. For example, pin 9 — labeled PB6 (for Port B, bit 6) — is

also used as a general-purpose I/O. In addition, it’s used as one oftwo connection points for an external oscillator. As the Arduinouses a crystal oscillator connected to this pin — as well as pinPB7 — neither of these are available for use in your programs.

Also shown in Figure 3 is pin mapping between theArduino and the ATmega328. It’s important to rememberthat the pin numbers are not the same between the two.Pin 12 on the ATmega328 is actually mapped to digital pinD6 on the Arduino. Pin mapping is not something you need

to worry about in typical Arduino programming, but it’snice to know what leads to where.

Writing and DownloadingPrograms

If you’ve used any kind of microcontroller, you knowthe process of programming it involves three steps: writethe program; compile the program; and run the program(see Figure 4). The Arduino is no different, except that itrefers to its programs as sketches.

Sketches are written in a programming language verysimilar to C. In fact, it is C (more accurately C++), but withsome simplifications to make it easier for newcomers to masterthe system. If you’ve ever looked at a C/C++ program andfelt your eyes glazing over because of the obtuse appearanceof the code, you don’t have to worry about that with the typicalArduino sketch. The Arduino is designed for beginners in mind,but still provides power and flexibility for more advanced users.

Taken indepth, the three steps of writing anddownloading Arduino sketches are:

1. Develop your sketch on your PC. The Arduino comes witha Java-based IDE that includes a fully featured text editor.It supports syntax highlighting and coloring (different partsof code are shown in different colors), but doesn’t give youpopup hints or keyword suggestions — like Microsoft’sIntellisense. If you’re already familiar with another programeditor like Eclipse or SEPY, you can use it instead. The fileformat for Arduino sketches is plain ASCII. (Even though SEPYis intended for programming ActionScript — the languageused to create Adobe Flash applications — it inherentlyunderstands most of the C syntax used in Arduino sketches.)

2. Once written, sketches must be compiled which in Arduino-land is referred to as verifying. During the compile/verifyphase, any errors are flagged and noted at the bottom ofthe Arduino editor window. The compiling process includesbuilding the sketch from component files. An Arduino sketchis not in itself completely compatible with C; for one thing,there’s no main() function which is required to tell the compiler

where the program is supposed to begin.In actuality, it’s still there, under the hood.When you compile your sketch, themain() function is added to the programfor you, along with some additional code.

3. The compiled program is downloaded tothe Arduino via a USB cable. The downloadprocess is automatic; the bootloaderprogram residing in the Arduino detectswhen a new sketch is arriving. It performsthe necessary steps of first erasing theold sketch in memory — if present — thenaccepting the new one. Once downloaded,the sketch starts automatically.

When you download a compiled

62 SERVO 01.2011

FIGURE 3. Pin-out diagram of the Atmel ATmega328 chip withthe pin mapping to the Arduino I/O lines.

FIGURE 4. Programs (sketches) are developed on your PC,compiled to a machine-readable format, then downloaded tothe Arduino via USB.

worldmags

worldmagso

Page 22: Robot With Arduino

sketch to the Arduino, it is stored in 32K bytes of Flashmemory inside the ATmega328. This memory is the sametype used in solid-state USB drives, and has a lifetime of over10,000 read/write cycles. Through the ATmega328, theArduino also supports 1K bytes of electrically erasable non-volatile EEPROM (data survives after power-down) and 2Kbytes of RAM. Data in RAM is volatile; it’s lost when poweris removed from the Arduino.

Arduino Architectureand Memory

Figure 5 shows a simplified block diagram of theATmega328 used in the Arduino. In center stage is thecentral processing unit, or CPU. This piece is what runs yourdownloaded sketches, performing all the number crunchingand other data processing tasks.

Feeding the CPU are the I/O lines, used to get datainto and out of the chip. The I/O lines are the 20 analogand digital pins. Some of the pins are connected to specialhardware within the ATmega328. For example, the sixanalog I/O lines go to the ADC, which translates anincoming voltage into any of 1,024 digital steps. Assuminga five volt incoming signal, the Arduino ADC provides aresolution of 4.9 millivolts per step.

The ATmega328 supports two external interrupts whichare mapped to Arduino digital pins D2 and D3. Interruptsserve as a way to signal the CPU that a special event hastaken place, without your sketch having to constantly checkfor it. Interrupts are set up in the Arduino IDE using theattachInterrupt programming statement. Along with thisstatement, you add the name of a function (I’ll get to functionsin a bit) that should run whenever the interrupt occurs.

There are also some blocks in the ATmega328 that arenot exposed in the current versions of the Arduino IDE.There are no standard programming statements for them.An example is the analog comparator which triggers aninterrupt when voltage on one comparator input equals orexceeds the voltage on another comparator input.

While current versions of the Arduino IDE don’t haveprogramming statements that directly support the analogcompare function, that doesn’t mean the Arduino isn’tcapable of using this feature on the ATmega chip.Remember, the Arduino programming language is based onC/C++ and links against the AVR Libc open source librarywhich is a de facto standard for writing C programs oneight-bit Atmel AVR microcontrollers. Any function availablein AVR Libc is also available on the Arduino. Or, let’s put itthis way: There’s more to the Arduino than meets the eye,so don’t be fooled by its apparent simplicity.

Anatomy of an Arduino Sketch

Part 1 of this series already touched on this topic, butit’s worth repeating here: All Arduino sketches have at leasttwo parts, named setup() and loop(). These are calledfunctions, and they appear in the sketch like this:

void setup() {}

void loop() {}

The () parentheses are for any optional arguments(data to be used by the function) for use in the function. Inthe case of setup and loop, there are no arguments, butthe parentheses have to be there just the same.

The {} braces define the function itself. Code betweenthe braces is construed as belonging to that function — thebraces form what’s referred to as a code block. There’s nocode shown here, so the braces are empty, but they have tobe there just the same.

The void in front of both function names tells thecompiler that the function doesn’t return a value when it’sfinished processing. Other functions you might use (orcreate yourself) may return a value when they are done.The value can be used in another part of the sketch. We’llsave this concept for a future article.

The setup() and loop() functions are required. Yourprogram must have them or the IDE will report an errorwhen you compile the sketch.

Arduino sketches may also have a global declarationsection at the top. Among other things, the declaration iswhere you put variables for use by the whole program (seethe following example). It’s also a common place to tell theIDE that you wish to use an external library to extend thebase functionality of the Arduino, and that programmingcode from that library should be included when your sketchis compiled.

Using libraries allows for convenient code re-use. Theexample code that follows uses the Servo library, which asits name suggests, provides an easy way to use R/C servomotors with the Arduino.

In Part 2, you saw a quick demonstration of operatingthe ArdBot’s two servo motors. Let’s review the coreconcepts behind that demo by looking at a simpler version;in this case, operating just one servo.

FIGURE 5. Simplified block diagram of the internals of theAtmel ATmega328 microcontroller.

SERVO 01.2011 63

worldmags

worldmags

Page 23: Robot With Arduino

The program in Code Example 1 swings the servomotor one direction, then the other, briefly pausing inbetween. You can use either an unmodified or modified(continuous rotation) servo to see the code in action. Referto Figure 6 for a diagram on hooking up the servo. Use astandard size (or smaller) analog servo; stay away fromlarger or digital servos, as they may draw too much currentfor the USB port on your computer to handle.

(In Code Example 1, text after the double slash //characters means a comment. It’s for us humans. Duringthe compiling phase, comments are ignored, as they arenot part of the functionality of the sketch.)

The first line, #include <Servo.h>, tells the IDE that youwant to use the Servo library which is a standard part ofthe Arduino IDE installation. (Other libraries may require aseparate download, but they are used in the same way.)The name of the main Servo library file is Servo.h, so that iswhat’s provided here.

The line Servo myServo creates, or “instantiates,” aservo object; the functionality of this object is defined inthe Servo.h library and its accompanying Servo.cpp

programming code file. Servo is actually a name of a class; that’s

how Arduino uses its libraries. With a class, youcan create multiple instances (copies) of anobject, without having to duplicate lots ofcode. In the case of servos, for instance, youcould create two objects: one for each physicalservo on your robot. That’s what we did in thecode example in the December ‘10 issue ofSERVO Magazine. Feel free to have a look atthat example sketch.

Again, note that Servo is the name of theclass to use, and myServo is the name I’vegiven to the object just created. You can usemost any name for an object, as long as itconforms to the requirements of the Clanguage. I won’t go into any detail here aboutthese requirements, as you can find plenty ofguides and examples on the Web. The mostimportant ones are: the name can’t have any

spaces, it may include only numbers, letters, and the _(underscore) character; and it can’t be the same as anyprogramming statements already defined for the Arduino.

The line int delay = 1000 creates a data variable nameddelay. Variables are used to hold information for usethroughout the sketch. The int tells the Arduino compilerthat you wish to create an integer type variable which canstore any whole number from -32,768 to 32,767. Otherdata types supported in the Arduino include unsigned intwhich holds values from 0 to 65,536, byte (holds 0 to 255),and Boolean (holds true or false).

The setup() function contains one statement,myServo.attach(9). Here’s what it all means:

• myServo is the name of the servo object that wasdefined earlier.

• attach is a method that you can use with the myServoobject. Methods are actions that you use to control thebehavior of objects. In this case, attach tells the Arduinothat you have physically connected the servo to digital pinD9 and you want to activate it. A period separates the

object name and method —myServo.attach.

Notice the ; (semi-colon) atthe end of the statement. It’s astatement terminator. This tellsthe compiler that thestatement is complete and togo on to the next line. Thesemi-colon is standard Cprogramming syntax, but ifyou’re used to a language likeBasic — which simply uses hardreturns to denote when astatement ends — the semi-colon business is bound to

FIGURE 6. Connectiondiagram for testing

servo functionality withthe Arduino.

64 SERVO 01.2011

#include <Servo.h> // Use the Servo library, included with// the Arduino IDE (version 0017 or later)

Servo myServo; // Create a Servo object to control the servoint delayTime = 2000; // Delay period, in milliseconds

void setup() {

myServo.attach(9); // Servo is connected to pin D9 }

void loop() {

myServo.write(0); // Rotate servo to position 0delay(delayTime); // Wait delaymyServo.write(180); // Rotate servo to position 180delay(delayTime); // Wait again

} CODE EXAMPLE 1

worldmags

Page 24: Robot With Arduino

cause some initial troubles. You’ll get used to itthough, and before long you’ll be adding semi-colons to everything you write — even grocerylists!

The loop() function contains the part ofthe sketch that is repeated over and over againuntil you download a new program or removepower from the Arduino. The function containsfour lines.

• myServo.write(0) is another method using themyServo object. The write method instructs theservo to move all the way in one direction.When using a modified servo, this statementcauses the motor to continually rotate in onedirection.

• delay(delayTime) tells the Arduino to wait the periodspecified earlier in the delayTime variable which is 2,000milliseconds (two seconds).

• The two statements are repeated again, this time withmyServo.write(180) to make the servo go the otherdirection.

Before continuing, I want to mention an importantnote about capitalization of variables, objects, andstatement names. Like all languages based on C, thesenames are case sensitive, meaning myServo is distinctlydifferent from myservo, MYSERVO, and other variations. Ifyou try to use

myservo.attach(9);

(note the lower-case s) when you’ve defined the object asmyServo, the Arduino IDE will report an error — “myservonot declared in this scope.” If you get this error, double-check your capitals.

More Experiments withServo Objects

The Servo class provides a number ofmethods that can be used on its objects. Irecommend you check out the documentationfor the Servo library on the arduino.cc website,but here are the principle ones you shouldknow about:

• attach connects a servo object to a specificpin of the Arduino. You can use any pin.

• detach removes the servo object, effectivelydisabling the servo and removing its power.

• write specifies where to position the servo.The method accepts several forms of values.A value of 0 to 180 denotes degrees; thispositions the shaft of the motor to acorresponding angle. (When used withmodified servos, 0 and 180 make the motorturn one direction or the other; 90 makes the

motor stop.) Values from 544 to 2400 are treated asmicroseconds and position the servo by generating pulsesof the specified duration. Typical servo specs are 1,000 to2,000 microseconds for a standard 60 degree arc.

• writeMicroseconds specifically indicates you wish to usemicroseconds to control the servo position.

• read returns the last specified position of the servo indegrees.

One technique to try is writing a position to the servobefore calling the attach method — attaching the servo iswhat gives it power. When you create a new Servo object,its position is automatically given a default of 0. By settinga position first, then attaching the servo, you can have itstart at a position other than 0 degrees. See CodeExample 2.

There’s also no absolute requirement that you use theattach method in the setup() function. You can place it inthe loop() function and use the detach method to removepower to the servo. Code Example 3 demonstratessweeping the servo right and left, while stopping it (actuallyturning it off) for four seconds in between. The action is abit easier to see when using a servo modified forcontinuous rotation.

SERVO 01.2011 65

Arduinowww.arduino.ccPrefabricated ArdBot body pieceswith all construction hardware.

Partial list of Arduino resellers:

Budget Roboticswww.budgetrobotics.com

AdaFruitwww.adafruit.com

HVW Techwww.hvwtech.com

Jamecowww.jameco.com

Pololuwww.pololu.com

Robotshopwww.robotshop.com

Solarboticswww.solarbotics.com

Sparkfunwww.sparkfun.com

Arduino circuits and sketches submitted by users:

Fritzingwww.fritzing.com

Sources

void setup() {

myServo.write(180); // Start at 180 degrees instead of 0myServo.attach(9);

} CODE EXAMPLE 2

void loop() {

myServo.attach(9); // Attach and apply powermyServo.write(0); // Position servodelay(delayTime); // Allow transit timemyServo.detach(); // Detach and remove power delay(4000); // Wait 4 secondsmyServo.attach(9); // Re-attach and apply powermyServo.write(180); // Move servo to other enddelay(delayTime); // Allow transit timemyServo.detach(); // Detach again

}

CODE EXAMPLE 3

worldmags

worldmags

Page 25: Robot With Arduino

Detaching the servo will prevent it from buzzing, or ifusing a servo modified for continuous rotation, will stop itfrom slowly “creeping” when you set its position to 0(stop). Since the servo is not being powered, it also savesbattery juice when your Arduino and servos are mountedon a mobile robot.

(Okay, detaching to remove power probably won’twork with digital servos. Detaching stops the Arduino fromsending pulses to the servo, which on analog models —what most people use — effectively shuts them off. Digitalservos will continue to hold position even when its pulsesgo missing. That’s what they are intended to do. So, theabove really applies to your typical, everyday, garden varietyanalog servo.)

Creating Your Own Functions

The flexibility of any programming language —Arduino included — comes in the ways you can developreusable code, such as creating user-defined functions. Tocreate a user-defined function, you give it a unique nameand place the code you want inside a pair of bracecharacters, like so:

void forward() {myServo.write(0);delay(delayTime);

}

All user-defined functions must indicate the kind of

data they return (for use elsewhere in the sketch). If thefunction doesn’t return any data, you use void instead. Youmust also include parentheses to enclose any parametersthat may be provided for use in the function. In the case ofthe forward user-defined function, there are no parameters,but remember you need the ( and ) characters just thesame.

That defines the function; you only need to call itfrom elsewhere in your sketch to use it. Just type itsname, followed by a semi-colon, to mark the end of thestatement line:

forward();

See Listing 1 for a full demonstration of an Arduinosketch that runs a servo forward and backward, then brieflystops it using the detach method. Recall the effect of thesketch is most easily seen when using a servo modified forcontinuous rotation, as is the case for a robot like theArdBot that uses continuous rotation servos to propel itacross the floor.

Finally, a Word About IDE Versions

The Arduino IDE and the standard programmingstatements and libraries often undergo changes with eachnew version. The Servo library as detailed here wasintroduced in version 0017 of the Arduino IDE. As of this

writing, we’re up to version 0021. If you already have an installed

version of the IDE and it’s old, you’llwant to fetch the newest version. Youcan keep multiple versions of theArduino IDE on your computer, andeven switch between them as needed —though that should seldom be required.

The ArdBot project requires version0017 or later. I’ve tested everything onversion 0019, plus the latest build(0021) just to make sure everythingstill works as it should. The ArduinoIDE is set to always check for the latestupdates. If you open the IDE and ittells you a new update is ready,download and install it, and be sure totake a look at the readme file for thelatest changes.

In future installments, you’ll beintegrating what you’ve learned herewith the ArdBot robot, including writingyour own customized servo motorcontrol functions, plus adding sensors toyour ArdBot to make it detect and avoidobstacles, and more. SV

66 SERVO 01.2011

Gordon McComb can be reached [email protected].

Listing 1#include <Servo.h>

Servo myServo; // Create Servo objectint delayTime = 2000; // Standard delay period (2 secs)const int servoPin = 9; // Use pin D9 for the servo

void setup() { // Empty setup}

void loop() { // Repeat these stepsforward(); // Call forward, reverse, servoStopreverse(); // user-defined functionsservoStop();delay(3000);

}

void forward() { // Attach servo, go forwardmyServo.attach(servoPin); // for delay periodmyServo.write(0);delay(delayTime);myServo.detach(); // Detatch servo when done

}

void reverse() { // Do same for other directionmyServo.attach(servoPin);myServo.write(180);delay(delayTime);myServo.detach();

}

void servoStop() { // Stop the servo by detachingmyServo.detach();

}

worldmags

worldmags

Page 26: Robot With Arduino

HandsOn Technology

http://www.handsontec.com

Low Cost 8051C Starter Kit/ Development Board HT-MC-02 HT-MC-02 is an ideal platform for small to medium scale embedded systems development and quick 8051 embedded design prototyping. HT-MC-02 can be used as stand-alone 8051C Flash programmer or as a development, prototyping and educational platform

Main Features:

8051 Central Processing Unit. On-chip Flash Program Memory with In-System Programming (ISP) and In Application

Programming (IAP) capability. Boot ROM contains low level Flash programming routines for downloading code via the

RS232. Flash memory reliably stores program code even after 10,000 erase and program cycles. 10-year minimum data retention. Programmable security for the code in the Flash. The security feature protects against

software piracy and prevents the contents of the Flash from being read. 4 level priority interrupt & 7 interrupt sources. 32 general purpose I/O pins connected to 10pins header connectors for easy I/O pins

access. Full-duplex enhanced UART – Framing error detection Automatic address recognition. Programmable Counter Array (PCA) & Pulse Width Modulation (PWM). Three 16-bits timer/event counters. AC/DC (9~12V) power supply – easily available from wall socket power adapter. On board stabilized +5Vdc for other external interface circuit power supply. Included 8x LEDs and pushbuttons test board (free with HT-MC-02 while stock last) for fast

simple code testing. Industrial popular window Keil C compiler and assembler included (Eval. version). Free Flash Magic Windows software for easy program code down loading.

PLEASE READ HT-MC-02 GETTING STARTED MANUAL BEFORE OPERATE THIS BOARD

INSTALL ACROBAT READER (AcrobatReader705 Application) TO OPEN AND PRINT ALL DOCUMENTS

Page 27: Robot With Arduino

Senses require sensors. In the practice of robotics,the basic senses make do with the most basic ofsensors: mechanical switches for detecting contactwith objects, and photosensitive resistors and

transistors for detecting the presence (or absence) of light.A robot can perform a remarkable amount of work withjust the sense of touch and the gift of simple sight.

In this month’s installment, you’ll learn aboutinterfacing switches and photosensors to the Arduino,along with how to use the information these sensorsprovide to interactively command a robot’s motors. Theseare the fundamental building blocks of most anyautonomous robot you build. Once you learn how to usethese sensors to do your bidding, you can apply them indozens of ways, for all kinds of robotic chores.

Arduino Robotics: What We’ve Covered So Far

This article builds upon previous installments in thisseries, which is all about the construction and use of theArdBot (see Figure 1) — an inexpensive two-wheeleddifferentially-steered robot based on the popular ArduinoUno and compatible microcontrollers. If you’d like to followalong, be sure to check out the previous three episodes, soyou’re familiar with the plot and characters.

Part 1 introduced the ArdBot project, the Arduino, andbasic programming fundamentals of this powerfulcontroller.

Part 2 detailed the construction of the ArdBot, usingcommon materials such as plastic or aircraft grade plywood.

Part 3 covered the Arduino in more depth, andexamined the ins and outs of programming R/C servomotors with the Arduino.

Making RobotsWith The

Part 4 - Getting Feedback With Sensors

By Gordon McComb

FIGURE 1. TheArdBot robot uses an

Arduino microcontroller and two R/C servo motors.

Robots need information about the world around them, or they juststumble about looking stupid. Just like us humans, a robot uses senses

to know when it’s run into something; when it’s light or dark; when it’stoo hot or too cold; when it’s about to fall over; or when it’s found the

way to the cheese at the center of a maze.

SERVO 02.2011 67

Arduino

worldmagsworldmags

worldmags

Page 28: Robot With Arduino

68 SERVO 02.2011

What’s covered here applies to most any robot thatuses the Arduino microcontroller, and that runs on twomotors and rolls on wheels or tracks. You’re free to adaptthe techniques and programming code to whatever botsyou’re constructing. The ArdBot is an expandable platform,but it’s also a concept that represents the typical desktop-size robot.

The subject of sensors is pretty involved. There’s noway to cover all the interesting things in just one article.

So, next month you’ll learn about other kinds ofinexpensive sensors you can use with your ArdBot (or other robot).

Getting in Touch With Your Robot

Sensors — whether in humans or inrobots — are designed to produce areaction. What that reaction is dependson the nature of the sensation. Type andquantity matter. We interpret the feelingof a soft summer breeze as a goodsensation. Increase the amount of airpressure to hurricane force and decreasethe temperature to something below

freezing, and suddenly the same senses produce a highlynegative reaction.

Touch — also called tactile feedback — is a primitivereactive sense. The robot determines its environment bymaking physical contact; this contact is registered through avariety of touch sensors. What happens when contact ismade is entirely determined by the programming you applywithin your robot.

Most often, a collision with an object is a cause foralarm. So, the reaction of the robot is to stop what it’sdoing, and back away from the condition. In other cases,contact can mean your robot has found its home base, or

that it’s located an enemy bot and isabout to pound the living batteries outof it.

The lowly mechanical switch is themost common — and most simple —form of tactile (touch) feedbackmechanism. Just about anymomentary, spring-loaded switch willdo. When the robot makes contact,the switch closes, completing a circuit.

I like to use leaf (or lever) switches(see Figure 2) because they function alot like a cat’s whiskers. These thingsare sometimes referred to as amicroswitch — after a popular brandname — but I’ll call them leaf switchesto avoid confusion. Regardless of makeor model, most are easy to mount, andcome with plastic or metal strips ofdifferent lengths that enhance thesensitivity of the switch.

You can enlarge the contact areaof the leaf by gluing or solderingbigger pieces of plastic or metal to it.For example, you can cut up some stiffmusic wire (available at hardwarestores) or a cheap wire clothes hanger,and bend it to some fancy shape.

www.servomagazine.com/index.php?/magazine/article/february2011_McComb

FIGURE 2. The leaf switch acts as a kind ofcat’s whiskers. It’s connected to a digitalI/O pin using a pull-down resistor.

The more you experiment with robotics,the more you’ll want to build a drawer-

full of reusable parts that easily plug intoyour projects. Sensors especially.

With just a bit of wire, some heatshrink tubing, and a length of snap-offmale header pins you can build modularsensors that can be shared betweenprojects. The pins easily plug into asolderless breadboard. Figure A shows aphotoresistor attached to an eight inchlength of wire which is terminated into athree-prong male header (only two pinsare used; the third is cut off).

First, start by cutting some 22 or 24gauge insulated stranded conductor wireto the desired length. Don’t be stingy withthe wire, but don’t make it so long theextra gets in the way. Give yourself anadditional inch or two so you can twistthe leads together to make a nice pigtail.

Strip about 1/4” insulation off bothends, and use your soldering pencil to pre-tin the wire. Do the same for the leadson the photocell and the header pins.Exercise care when soldering to thephotocell leads, as excessive heat candamage the component. After tinning iscomplete, carefully tack-solder the wiresto the leads or pins.

I like to use heat shrink tubing tofinish off the soldered ends. The tubing

makes for a more professional look, plus ithelps prevent short circuits. When appliedproperly, it acts as a strain relief to helpkeep the wires from pulling apart fromtheir joints. Buy a small assorted packageof tubing, and use the smallest diameterfor the best fit.

Header pins have a 0.100” spacingwhich is a fairly tight space for all but themost seasoned solder pros. So, you’llprobably want to snap off a set of threeor four pins, and remove the center pinsto make extra room for your solder joints.

Making Reusable Sensor Components

FIGURE A. Use male header pins toprepare connectors for easy

interchange with your variousprojects. The connectors plug into

a solderless breadboard.

worldmagsworldmags

worldmags

Page 29: Robot With Arduino

Solder the end(s) to the leaf. Or, you can usethin pieces of wood, plastic, or metal. Just besure the weight of the extension doesn’taccidentally activate the switch. You don’twant false alarms.

The switch may be directly connected toa motor or, more commonly, it may beconnected to a microcontroller. A typicalwiring diagram for the switch is shown inFigure 2. The 10 kΩ pull-down resistor isthere to provide a consistent digital LOW (0 volts) outputfor the switch when there is no contact. When contact ismade, the switch closes, and the output of the switch goesHIGH — usually five volts, as shown here.

Using Leaf Switches as Bumpers

Two standard leaf switches mounted to the front ofyour ArdBot let it detect when it’s hit something. With the switches situated to the sides, your bot can determine if the object is on the left or on the right, and then steeraround it.

Figure 3 shows a pair of leaf switches mounted likebumpers to the front of the ArdBot. Switches like these are available at many online electronics outlets, and arecommon as surplus. I bought these at All Electronics (a SERVO Magazine advertiser) for $1.60 a pop.

I haven’t augmented the switches with a larger contactarea, as I’m more interested in demonstrating the conceptsinvolved. Use your creativity in enhancing the switches toprovide the level of sense detection you want. For example,right off you can see that the robot is “blind” to smallobjects directly between the switches. You can deal withthis either by enlarging the contact area, or (my choice)using another form of “sense” to avoid collision in the first place.

To mount each switch, find two suitable holes in thebase of your robot, or drill new ones. Most leaf switcheshave three connections: common, normally open (NO), andnormally closed (NC). Wire the common and NOconnections. If space is tight, break off the NC connectionto make room.

Figure 4 shows the diagram for connecting the twoswitches to digital pins D2 and D3 of the Arduino. Figure 5shows the same circuit, but in breadboard view. Use theupper half of the ArdBot’s 170 tie point solderlessbreadboard. The bottom half is already in use by the servowiring for the ArdBot (see Part 2 of this series).

On my prototype, I made connectors for the switchesby soldering the two wires to pins of a breakaway maleheader. With these, you break off the number of pins you

FIGURE 5. Breadboard view of connecting the bumperswitches. Note that the bottom half of the solderless

breadboard is already in use, wired for the two servo motors.(See Part 2 of this series for details.)

FIGURE 3. A pair of leaf switches on theArdBot. You can attach things to the leaf of each

switch to enlarge its contact area.

FIGURE 4. Schematic view of connecting two bumper switchesto the Arduino microcontroller.

SERVO 02.2011 69

worldmagsworldmags

worldmagso

Page 30: Robot With Arduino

want to use. I cut one connector to three pins wide,removing the middle pin; I soldered the wires from theswitch to the outer two pins. For the other connector, I cutit to four pins wide, removing the middle two pins. You cansee in Figure 5 how the two connectors plug into thebreadboard.

Important! Make sure all the wires and othercomponents are firmly seated into their breadboard tie-point sockets. Loose connections are the second mostcommon cause of problems when using a solderlessbreadboard — the most common is plugging the wires intothe wrong tie points!

Listing 1 shows the demo program bumper.pde. TheArdBot sets off going forward until one of its front bumperswitches makes contact with an object. The moment theswitch closes, the robot quickly reverses direction, thenturns in the opposite direction of the obstacle. Time delaysare specified in milliseconds. The robot backs up for 500milliseconds (half a second). It then turns — actually spins —to the right or left for 1,500 milliseconds (1.5 seconds).

You can experiment with other delay settings,depending on how fast your robot travels. With faster servomotors, you can use a shorter delay. The idea is to spin therobot about one-quarter to one-half turn, so it moves awayfrom the obstacle.

Note that “left” and “right” (and “front” and “back”)are somewhat objective in a robot like the ArdBot. Eitherend can be the front, so left and right is relative. In myprototype, I put the two leaf switches on the end that hadmore mounting space available. That end became the“front.” The coding in bumper.pde reflects this designchoice. If your robot seems to behave opposite to what itshould, swap the values in the motion routines (forward,reverse, etc.). See Part 3 of this series for more details onwhat the servo commands do, and how they work.

Understanding thebumper.pde Sketch

As with all Arduino sketches, bumper.pde has threeprinciple parts: declaration, setup() function, and loop()function.

The declaration area at the top of the sketch sets upthe variables used throughout the program. It also preparestwo objects of the servo class. As you read in Part 3 ofMaking Robots with the Arduino, the servo class isprovided as a library that comes with the Arduinoprogramming tools. You use it to control one or more R/Cservos. The declaration also defines the two leaf switches asconnected to digital pins D2 and D3, and that we’ll beusing the Arduino’s built-in LED (internally connected to pinD13) as a visual indicator.

In the setup() function, the servos are defined asconnected to digital pins D9 and D10. The pins used for theLED and two switches are set as outputs and input,respectively.

The main body of the sketch is the loop() function

/*ArdBot bumper switch demo Requires Arduino IDE version 0017 or later (0019 or later preferred)

*/

#include <Servo.h>

const int ledPin = 13; // Built-in LEDconst int bumpLeft = 2; // Left bumper pin 2 const int bumpRight = 3; // Left bumper pin 3int pbLeft = 0; // Var for left bumpint pbRight = 0; // Var for left bumpServo servoLeft; // Define left servoServo servoRight; // Define right servo

void setup() { servoLeft.attach(10); // Left servo pin D10servoRight.attach(9); // Right servo pin D9// Set pin modespinMode(bumpLeft, INPUT); pinMode(bumpRight, INPUT); pinMode(ledPin, OUTPUT);

}

void loop() { forward(); // Start forward// Test bumper switchespbLeft = digitalRead(bumpLeft); pbRight = digitalRead(bumpRight);

// Show LED indicatorshowLED();

// If left bumper hitif (pbLeft == HIGH) {reverse();delay(500); turnRight();delay(1500);

}

// If right bumper hitif (pbRight == HIGH) {reverse();delay(500); turnLeft();delay(1500);

}}

// Motion routinesvoid forward() {

servoLeft.write(180);servoRight.write(0);

}

void reverse() {servoLeft.write(0);servoRight.write(180);

}

void turnRight() {servoLeft.write(180);servoRight.write(180);

}

void turnLeft() {servoLeft.write(0);servoRight.write(0);

}

void stopRobot() {servoLeft.write(90);servoRight.write(90);

}

void showLED() {// Show LED if a bumper is hitif (pbRight == HIGH || pbLeft == HIGH) {

// Turn LED ondigitalWrite(ledPin, HIGH);

} else {

// Turn LED offdigitalWrite(ledPin, LOW);

} }

Listing 1 -bumper.pde.

70 SERVO 02.2011

worldmagsworldmags

worldmags

Page 31: Robot With Arduino

which repeats indefinitely. It begins by activating the twoservos to move the robot forward. The sketch then uses thedigitalRead statement to store the current state of the twoswitches. The instantaneous value of the switches is kept ina pair of variables (pbLeft and pbRight — the pb forpushbutton). These variables are used elsewhere.

Of main interest in the loop() function are the two ifstatements. Here’s the one that tests the left leaf switch:

if (pbLeft == HIGH)

reverse();

delay(500);

turnRight();

delay(1500);

}

pbLeft == HIGH checks to see if the contents of thepbLeft variable (set earlier based on the state of the leftleaf switch) is HIGH. If it is, then the left switch is closed,and the robot has made contact with something. If it’sLOW, then the switch is open, and the robot continues onits way.

Bumper.pde also includes a number of user-definedfunctions. Most — like forward() and reverse() — relate todriving the servo motors. Another function, showLED(),toggles the LED on pin D13 of the Arduino on or off,depending on whether a switch is closed. Use this as avisual indicator that the programming code is working as itshould.

Switch Triggers Using Polling or Interrupts

The programming in bumper.pde relies on what’sknown as polling: The sketch repeatedly checks the statusof the two switches. If a switch is closed, its value goesfrom LOW to HIGH; when HIGH, the robot is commandedto steer to a new heading. The switches are checked —polled — many times each second.

Polling is an acceptable method when the sketch isrelatively simple, and the demands on the Arduino are light.For code that is more processing intensive, there is aremote chance the controller will miss when a leaf switchhas closed. It’ll be busy doing something else in betweenpolls and be unaware anything has happened.

In truth, you can have a fairly involved sketch and it willstill detect 99 percent of all switch closures. The reason:The switch will likely be closed for what are very longperiods of time to a microcontroller. For a microcontrollerrunning at 16 MHz, even a brief 100 millisecond (one-tenthsecond) contact is like a lifetime, and so in all likelihood theswitch closure will be registered.

Still, if you absolutely must ensure that even the mostfleeting contact is registered, you might want to considerusing hardware interrupts rather than polling. With aninterrupt, special code is run if — and only when — aspecific external event occurs. Because the main program

/*ArdBot interrupt bumper demo Requires Arduino IDE version 0017 or later (0019 or later preferred)

*/

#include <Servo.h>

const int ledPin = 13;const int bumpLeft = 2; const int bumpRight = 3;int pbLeft = 0;int pbRight = 0;Servo servoLeft;Servo servoRight;

void setup() { servoLeft.attach(10);servoRight.attach(9);// Set pin modespinMode(bumpLeft, INPUT); pinMode(bumpRight, INPUT); pinMode(ledPin, OUTPUT);

// Set up interruptsattachInterrupt(0, hitLeft, RISING);attachInterrupt(1, hitRight, RISING);

}

void loop() { forward(); // Start forwardshowLED(); // Show LED indicator

// If left bumper hitif (pbLeft == HIGH) { reverse();delay(500); turnRight();delay(1500);pbLeft = LOW;

}

// If right bumper hitif (pbRight == HIGH) { reverse();delay(500); turnLeft();delay(1500);pbRight = LOW;

}}

// Motion routinesvoid forward() {

servoLeft.write(180);servoRight.write(0);

}

void reverse() {servoLeft.write(0);servoRight.write(180);

}

void turnRight() {servoLeft.write(180);servoRight.write(180);

}

void turnLeft() {servoLeft.write(0);servoRight.write(0);

}

void stopRobot() {servoLeft.write(90);servoRight.write(90);

}

void showLED() {// Show LED if a bumper is hitif (pbRight == HIGH || pbLeft == HIGH) {

digitalWrite(ledPin, HIGH);} else {

digitalWrite(ledPin, LOW); }

}

// Interrupt handlersvoid hitLeft() {

pbLeft = HIGH;}

void hitRight() {pbRight = HIGH;

}

Listing 2 -interrupt.pde.

SERVO 02.2011 71

worldmagsworldmags

worldmags

Page 32: Robot With Arduino

72 SERVO 02.2011

loop() doesn’t have to continually check the state of thepins, it frees up the controller to do other things. Reactiontime of an interrupt is measured in microsecond timing,even if the Arduino is busy doing something else. (Actually,this is not always true, depending on how other hardwareon the controller is being used. But any additional delay isusually minimal.)

The Arduino Uno supports two hardware interrupts(the Arduino Mega supports six) internally connected withinthe Arduino to digital pins D2 and D3. These are the pinsthat the leaf switches are already connected to, so the onlychange needed is in the software.

See Listing 2 for interrupt.pde. Here, the bumper.pdesketch has been revised to “listen” to a state change onboth of the hardware interrupts with the statements:

attachInterrupt(0, hitLeft, RISING);

attachInterrupt(1, hitRight, RISING);

Note that the interrupts are referred to as 0 and 1.These correspond to pins D2 and D3, respectively. Thelabels hitLeft and hitRight are the functions that are calledwhen the interrupt is triggered. Finally, RISING is a built-inconstant that tells the Arduino to trigger the interrupt on aLOW-to-HIGH signal transition. This type of transition occurswhen the switch closes.

Both hitLeft and hitRight set their corresponding “pb”variable to HIGH. The program then immediately exits theinterrupt handler. The next time the Arduino repeats itsloop(), it notices that a pushbutton is HIGH and performsthe needed obstacle avoidance maneuver. (Note also thatthe pushbutton value is manually set back to LOW, inanticipation of the next bump.)

You might be asking why the code to control theservos isn’t in the interrupt handlers. The reason is this: The

delay statement — which is used to steer the robot aroundan obstacle — is disabled while in an interrupt. In any case,it’s usually best not to place time-intensive functionalitywithin interrupt handlers.

To Let Bounce or Debounce?

In a perfect world, mechanical switches would produceclean, reliable digital signals for our microcontrollers. Wedon’t live in a perfect world; instead, we must suffersomething called switch bounce. Instead of a nice LOW-to-HIGH digital pulse when a switch closes, what we get arefive, 10, maybe even dozens of irregular glitches, all causedas the metal contacts in the switch settle into position. Allthis happens very quickly; usually in just a few milliseconds.

For some applications, it’s absolutely necessary todebounce the output of a switch. In debouncing, all theglitches are removed, providing the microcontroller withthat single sweet pulse we want. You can debounce withsome extra hardware: a capacitor and resistor create an RCnetwork that acts to delay the rise and fall of the switchsignal — that effectively removes the glitches. You can alsodo it in software, typically using delays so that themicrocontroller ignores all but the first signal transition.

Both the bumper.pde and interrupt.pde examples don’tdirectly use switch debounce. Software delays are alreadybuilt into the code, plus R/C servos are slow creatures anddon’t react fast enough for bounce to be a problem. Servosare commanded in 20 millisecond “frames” — that is, theiroperation is updated once every 20 milliseconds. Turns outthat’s about the worst-case duration of bounce glitchesfrom most switches. So, even with a switch bouncing alongmerrily, it has little or no effect on the operation of theservos.

Should you need to debounce your switch inputs,there’s a separate class library you can download

and use with the Arduino. The library is calledBounce, and it’s available from the mainArduino language reference pages. There’s alsoa Debounce code example that comes with theArduino programming IDE.

Mounting Alternatives, More Switches

A few quick notes before moving on. Sofar, I’ve talked about the two switches in thefront of the robot, situated right and left. Feelfree to put switches anywhere you want. Youmight instead have a front and back switch, ora bunch of switches all around the periphery ofthe robot.

If you use more than two switches, you’llhave to rely on polling, as there are only twopins that support hardware interrupts (whenusing the Arduino Uno). If you use more thanfour or five switches, you may want to use a

If you’d like to build the ArdBot,be sure to start with theNovember ‘10 issue of SERVOMagazine for Part 1 of this series.Also check out the followingsources for parts:

Example code and more:

Arduinowww.arduino.cc

Fritzingwww.fritzing.org

Prefabricated ArdBot bodypieces with all constructionhardware:

Budget Roboticswww.budgetrobotics.com

Partial list of Arduino resellers:

AdaFruitwww.adafruit.com

HVW Techwww.hvwtech.com

Jamecowww.jameco.com

Pololuwww.pololu.com

Robotshopwww.robotshop.com

Solarboticswww.solarbotics.com

Sparkfunwww.sparkfun.com

Sources

worldmags

worldmags

Page 33: Robot With Arduino

parallel-to-serial (PISO) shift register chip, such as the74HC165 or CD4021. These are integrated circuits that takeeight parallel inputs and provide a serial data output thatcan be read by the Arduino. Assuming eight switches, thePISO reduces the number of required I/O pins from eight tothree. There’s a code example for how to do this atarduino.cc/en/Tutorial/ShiftIn.

Let There Be Light (and let your ArdBot see it!)

Next to tactile feedback, reacting to light is the mostcommon robotic sense. In lieu of actual vision, the robotuses electronic components such as photoresistors andphototransistors that are sensitive to light. Your bot mayreact to the simple absence or presence of light, or it maybe able to measure the brightness, color, or otherqualitative aspect of the light.

Photoresistors — also called photocells, light dependentresistors, or CdS (for cadmium sulfide) cells — are perhapsthe easiest to use as simple light sensors. The photocell is aresistor whose value changes depending on the amount oflight that strikes its sensing surface. In darkness, thephotocell has a high resistance, typically in theneighborhood of 100 kΩ to over one megohm, dependingon the component. The resistance falls as more light strikesthe cell. In high brightness, the resistance may be as low as1 kΩ to 10 kΩ.

The exact dark/light resistance values differ dependingon the component, and even among photocells of the samemake and model. Typical value tolerance is 10 to 20percent. You can purchase photocells new, but they’recommon finds in the surplus market. Get a variety pack,and use your multimeter to “grade” each one. Cracks andother injury spell doom to a photocell; air and moisturedegrade the sensing surface, rendering it useless. Toss anythat don’t react properly to a nearby desk lamp.

Being a resistor, you can convert the output of aphotocell to a varying voltage merely by connecting anotherresistor to it in series, as shown in Figure 6. The value ofthe series resistor depends on the dark/light resistancerange of the photocell, and how you want to use it. Thecells I used had a dark resistance of about 40 kΩ and alight resistance of 30 ohms. In average room brightness,the cells had 10 kΩ resistors, so I selected a 10 kΩ seriesresistor.

The voltage at the point between the photocell andseries resistor is a ratio of the two resistance values. Withthe two resistances equal, the divided voltage betweenthem is one-half of the supply voltage; in the case of fivevolts in average room light, the output voltage is 2.5 volts.

FIGURE 6. By connecting another resistor in series with aphotoresistor, the output is converted to a varying voltage.

In this particular arrangement, the voltage increases under stronger light.

SERVO 02.2011 73

Listing 3 - simplecds.pde./*ArdBot CdS cell demo

*/

int cds = 0;

void setup() { Serial.begin(9600);

}

void loop() { // Read analog pin A0 and display value// on Serial Monitor windowcds = analogRead(A0);Serial.println(cds, DEC);delay (200);

}

FIGURE 7. Schematic view of connecting two photocells to theArduino microcontroller.

worldmagsworldmags

worldmags

Page 34: Robot With Arduino

The voltage decreases in darkness and increases as morelight strikes the photocell.

You will need to experiment with the series resistor todetermine its best value, based on the specific photocellsyou use. You might want to try a 50 kΩ or 100 kΩpotentiometer in place of a fixed resistor, allowing you tofine-tune the series resistance as needed.

Listing 3 shows simplecds.pde, a basic sketch thattests the operation of the photocell. Wire the photocell asshown in Figure 6 and connect the output to analog pin

A0 of your Arduino. Compile and upload the sketch, thenopen the serial monitor window. You’ll see a series ofnumbers; they correspond to the output voltage of thesensor converted to a 10-bit (0 to 1023) numeric value. Youshould get a low number when all light to the photocell isblocked, and a higher number under full illumination.

Steering Your Robot With a Flashlight

By using two photocells mounted on each side of yourArdBot, you can literally steer it by flashlight. Under justroom light, the robot is set to stop, waiting for yourcommand. Aim the flashlight so that light falls more or lessequally on both photocells, and the robot will moveforward. When the light levels aren’t equal, the robot willturn toward the photocell that has more light falling on it.

Refer to Figure 7 for a schematic of the two-photocellsetup. Figure 8 shows the same circuit but in breadboardview. For my prototype, I made small mounts for thephotocells using scrap PVC plastic, then attached themounts to the top deck of the ArdBot with metal brackets.The photocells I used measured 0.29” x 0.25” (ellipticalshape). I drilled holes just slightly smaller, then used a rat-tail file to enlarge the holes so that the cell just fit inside.On my prototype, the cells are held in just by friction, buton yours you can use hot-melt glue or other adhesive thatwhen set leaves no moisture for a possible short circuit.

(Bear in mind light can strike the photosensitive surfaceof the cell from the rear. You may want to add a layer ortwo of black tape to prevent light spoilage.)

Figure 9 shows my ArdBot with the two photocell“eyes” attached to the front. I’ve bent the brackets back abit so that the cells point slightly upward.

Refer to Listing 4 for lightsteer.pde. It uses the currentvalues of the photocells to make quicksteering adjustments to the left or to theright. In the declarations area, the code:

const int ambient = 600;

const int threshold = 800;

sets two comparison values used elsewherein the sketch. You will need to experimentwith these values depending on the roomenvironment and photocell characteristics!These values worked for me; you can startwith them, but expect to try other values asyou fine-tune the performance of thesteering.

The ambient value sets the upper levelof just the ambient (natural) light in the

FIGURE 8. Breadboard view of connecting the photocells.

FIGURE 9. Mount the photocells on the top ofthe ArdBot — toward the left and right sides —to make eyes for following the flashlight beam.

74 SERVO 02.2011

worldmags

worldmags

Page 35: Robot With Arduino

room. This is the amount of light that hits thephotocells under normal lighting conditions. For me,the ambient light value was about 520 to 530, so Imade it a little higher (600) for extra headroom.

The threshold value sets the lower level of thelight beamed from your flashlight. I set the value at800 based on using a nine-LED flashlight (with freshbatteries), 1-2 feet away from the robot. For bestresults, use a bright flashlight near the robot — thefarther away you get, the less light that falls on thephotocells.

More Light Tricks

Just by switching around some of the code youcan have your robot run away from you rather thantry to follow you. Or, by placing colored gel filtersover the photocells and using a color LED flashlight(blue and green are popular), your robot can morereadily discriminate between light to follow and lightto ignore.

You might also add one or two “room light”sensors that aren’t in the direct line-of-sight of theflashlight beam. These could be used to set theambient light level of the room.

Small lenses over the photocells help to focus theflashlight beam, improving steering performance andhelping the bot reject any light not directly to thefront.

These are just some of the things you can do togive your ArdBot (or other Arduino-powered bot) thegift of sight. Feel free to experiment. Photocells andother light sensitive components are inexpensive, andchanging the code in an Arduino sketch is absolutelyfree.

Coming Up ...

In our next installment, you’ll discover even moresenses you can provide, including ultrasonic sound formeasuring distances to objects, and infrared light todetermine the proximity of nasty things that are in the way.

You’ll also read about ways for your robot to scanthe room to soak up its environment, rather than justsee life through a narrow tunnel in front of it. Excitingstuff (at least for your ArdBot), so don’t miss it! SV

Gordon McComb can be reached [email protected].

Listing 4 - lightsteer.pde./*ArdBot steering by light demoRequires Arduino IDE version 0017 or later (0019 or later preferred)

*/

#include <Servo.h>

// CdS cell reference values// (you need to experiment)const int ambient = 600;const int threshold = 800;

int lightLeft = 0;int lightRight = 0;

Servo servoLeft;Servo servoRight;

void setup() { servoLeft.attach(10);servoRight.attach(9);

}

void loop() { // Read light sensors connected to // analog pins A0 and A1lightLeft = analogRead(A1);lightRight = analogRead(A0);

// Stop robot if below ambientif (lightRight < ambient || lightLeft < ambient) {

stopRobot();} else {

forward();// Steer to right if right CdS below thresholdif (lightRight < threshold) {

turnLeft();delay (250);

}// Steer to left if left CdS below thresholdforward();if (lightLeft < threshold) {

turnRight();delay (250);

}}

}

// Motion routinesvoid forward() {

servoLeft.write(180);servoRight.write(0);

}

void reverse() {servoLeft.write(0);servoRight.write(180);

}

void turnRight() {servoLeft.write(180);servoRight.write(180);

}

void turnLeft() {servoLeft.write(0);servoRight.write(0);

}

void stopRobot() {servoLeft.write(90);servoRight.write(90);

}

SERVO 02.2011 75

worldmagsworldmags

worldmags

Page 36: Robot With Arduino

HandsOn Technology http://www.handsontec.com

1

ISP to ICP Programming Bridge: HT-ICP200In-Circuit-Programming (ICP) for P89LPC900 Series of 8051 Flash �Controller…

…ICP uses a serial shift protocol that requires 5 pins to program: PCL, PDA, Reset, VDD and VSS. ICP is different from ISP (In System Programming) because it is done completely by the microcontroller’s hardware and does not require a bootloader…

That the 80C51-based controllers are extremely popular is nothing new, certainly when considering the large number of designs that can be found on the web. The reason may well be the fact that the tools (both hardware and software)that are available for this controller are very affordable and there is an enormous amount of information readily available. In addition, a very active forum provides answers to many questions. One of the most significant features of the P89LPC900 Family is that the core now requires only 2-clock Cycles Per Instruction (CPI).8051 experts will already know that this used to be 12 or 6 cycles until now. In practice, this means that the crystal frequency can be drastically lowered to achieve the same processing speed as their classic counter parts.

ISP Programming is only available for 20, 28 and 44pin parts. IAP is only available once your IAP program has been loaded in to the LPC900 part. ICP -can be used to program all the LPC900 parts.

The LPC90x devices can only be programmed using a ICP programming method. In contrast to some of the larger LPC900 family members, the LPC90x devices do not offer other programming methods like Parallel Programming, In-System Programming (ISP) or complete In-Application Programming (IAP). HOWEVER - ICP requires hardware control/ signaling of the LPC900 to be programmed.In some high-end applications, there may be a need to replace the code in the microcontroller without replacing the IC itself. This article described in detail the operation of the In-Circuit-Programming (ICP) capability which allows these microcontrollers to be programmed while mounted in the end product.

P89LPC9xx parts (affectionately know as the LPC900 series of micro-controllers) can be programmed 4 ways...

1. ISP (In-System-Programmed) using the UART of the LPC900.2. IAP (In-Application-Programmed) .. or "self programmed" by reprogramming the flash under code execution.3. ICP (In-Circuit-Programming)... using "Synchronous Serial".... Similar to SPI signaling - each data bit is clocked

in/out under clock signal control.4. Parallel Programmer, available in expensive industry grade tools.

1. INTRODUCTION

HT-ICP200 P89LPC900 Target Application Board

To communicate between a PC (running Flash Magic) and the LPC900 Micro-Controller to be programmed an "ICP Bridge" circuit is required as shown in Figure 1.

Figure 1: Hooking up ICP to the P89LPC900 Application Board

Page 37: Robot With Arduino

In last month’s installment, you learned how to giveyour ArdBot (or other Arduino-based automaton) thesense of touch and light. Augmenting these basicsenses are methods to detect objects in proximity to

your robot — seeing what’s there without having to actuallybump against them.

Proximity detection forms the basis of collisionavoidance — how to keep your bot from crashing intothings in the first place. Collision avoidance takes manyforms. Some of these techniques are designed to detectobjects very close to the robot, while others are made todetect objects several feet away.

In this installment, you’ll learn about two popular formsof proximity detection — ultrasound and infrared — andhow these low cost sensors are interfaced and used withthe Arduino.

The State of the ArdBot

This article series has been on the construction and useof the ArdBot (see Figure 1) — an inexpensive two-wheeled

differentially-steered robot based on the popular ArduinoUno and compatible microcontrollers. Here’s what pastinstallments covered:

• Part 1 (Nov ‘10) introduced the ArdBot project, along

Making RobotsWith The

Part 5 - Adding Sensors To Explore The World

By Gordon McComb

FIGURE 1. The ArdBot Arduino-based expandable robot,shown with this month’s enhancements: a rotating turret,

ultrasonic distance ranger, and infrared proximity detector.

You’ve spent hours designing and building your latest robot creation. You bring it into your living room, fire it up, and step back. Behold! Your beautiful new robot smashes into the fireplace and scatters itself into tiny pieces over the living room rug. You remembered things likemotor speed controls, colorful blinky lights, even a synthetic voice, but you forgot to provide your robot with the ability to look before it leaps.

SERVO 03.2011 43

Arduino

Page 38: Robot With Arduino

44 SERVO 03.2011

with the popular Arduino microcontroller and basicprogramming fundamentals of this powerful controller.

• Part 2 (Dec ‘10) detailed the construction of the ArdBot,using common materials including PVC plastic and aircraftgrade plywood.

• Part 3 (Jan ‘11) covered the Arduino in more detail. Italso examined the ins and outs of programming R/Cservo motors that provide the locomotion for the ArdBot.

• In Part 4 (Feb ‘11), we learned about using bumper

switches with polling and hardwareinterrupts to detect physical contactwith objects, and ways to usephotoresistors to steer the robot bylight.

Be sure to check out theprevious four issues of SERVOMagazine for more details. Thisinstallment describes threeimportant robotic functions:programming an ultrasonictransducer to accurately measurethe distance to objects; how to usea Sharp infrared distance modulefor monitoring proximity; and waysto add a rotating turret so theArdBot can scan the room to lookfor things nearby.

In the next issue, we’ll concludewith putting all the pieces together,combining what you’ve learned tocreate an autonomous room

wanderer that’s able to seek things out, investigate itsenvironment, and follow the direction of its master —that’s you.

About Non-Contact Near-Object Detection

Last time, we learned how leaf switches are used as aform of touch sensor to detect contact with objects.Contact detection provides an immediate signal thatsomething looms directly in the way.

Non-contact detection senses objects withouthaving to hit them first. Near-object detection doesjust what its name implies: It senses objects that areclose by, from perhaps just a breath away to asmuch as eight or 10 feet. These are objects that arobot can consider to be in its immediate space;objects it may have to deal with, and soon. Theseobjects may be people, animals, furniture, or otherrobots.

By detecting them, your robot can takeappropriate action which is defined by theprogramming you give it. Your bot may beprogrammed to come up to people and ask for theirname. Or, it might be programmed to run awaywhenever it sees movement. In either case, it won’tbe able to accomplish either behavior unless it candetect the objects in its neighborhood.

There are two common methods of achievingnear-object detection: proximity and distance.

• Proximity sensors care only that some object iswithin a zone of relevance. That

www.servomagazine.com/index.php?/magazine/article/march2011_McComb

From time to time, Sharp discontinuessome models of their infrared distance

sensors, allowing the stock that remains“in the channel” (still held in resellerinventory) to be depleted. New versionsare in production, but they may not beuniversally available.

You may have noticed that several ofthe Sharp infrared distance sensors havebecome hard to get from some sources —most particularly from Digi-Key, who atone time was a major seller of the things.These sensors are discontinued and/ornot available as new stock in retailchannels.

However, most of the sensors canstill be purchased from a number ofspecialty online shops, such as SparkFunand Pololu, both of whom carry largeinventories of several Sharp models.What remains of the current stock may

not be useful for creating a new mass-market product, but there’s plenty stillaround for us robo-tinkerers.

Sharp has introduced a relativelynew style of sensor — the GP2Y0D805and GP2Y0D810 — that are smaller andless expensive. The ‘05 has a set 5 cm proximity range; the ‘10 has a set 10 cmrange. Output is a digital LOW or HIGH.

This new class of sensor comes in aDIP-size package, but it requires someexternal components. Online retailerssuch as Pololu (see the Sources box)offer the sensors on a breakout board foreasy use in your projects. Even with theaddition of the breakout board, thesesensors are roughly half the cost of theirpredecessors. They also have a muchimproved response time: over 350 Hz(350 updates per second), as opposed toabout 25 Hz of the older sensors.

Where Have All the SharpDistance Sensors Gone?

If you’d like to build theArdBot, be sure to start withthe November ‘10 issue ofSERVO Magazine for Part 1 ofthis series. Also check out thefollowing sources for parts:

Prefabricated ArdBot bodypieces with all constructionhardware; 360 degree rotationsensor turret:

Budget Roboticswww.budgetrobotics.com

Arduino Resources:

Arduinowww.arduino.cc

Fritzingwww.fritzing.org

Online Retailers of Arduino,Sharp sensors, and/or ultrasonic sensors:

Acronamewww.acroname.com

AdaFruit Industrieswww.adafruit.com

HVW Techwww.hvwtech.com

Jamecowww.jameco.com

Lynxmotionwww.lynxmotion.com

Mark III Robot Storewww.junun.org

Pololu Robotics & Electronicswww.pololu.com

Robotshopwww.robotshop.com

SparkFunwww.sparkfun.com

Sources

Page 39: Robot With Arduino

is, if an object is near enough to beconsidered important. Objects beyond theproximal range of a sensor are effectivelyignored because they are not seen. Out ofview, out of mind.

• Distance measurement sensors determinethe space between the sensor andwhatever object is within detection range.Distance measurement techniques vary;almost all have notable minimum andmaximum ranges. Few yield accurate dataif an object is smack-dab next to therobot, or very far away.

Collectively, these sensor types are oftenreferred to as rangefinders, though only adevice that actually measures and reportsthe distance of the covered range is a truerangefinder.

Among the most common proximity anddistance measurement detectors used inrobotics are ultrasonic transducers, andspecialty infrared sensors made by Sharp.Depending on the design of the specificsensor, either can be used for proximity ordistance measurement. In practice however,the Sharp IR sensors are best suited forproximity, and ultrasound sensors are theideal choice for measuring distance. That’show these two detectors are used in theArdBot.

Using the SharpGP2D120 InfraredDetector

The Sharp GP2D120 is among a seriesof remarkable distance measuring devicesoriginally intended for industrial control.They’re common finds in amateur robotprojects. These sensors rely on thedisplacement of reflected light across a linearsensor (see Figure 2).

Here’s how they work: A beam ofmodulated infrared light from the sensorilluminates an object. The beam reflects offthe object and bounces back into the sensor.The reflected beam is focused onto what’s known as aposition sensitive device, or PSD. The PSD has a surfacewhose resistance changes depending on where light strikesit. As the distance between sensor and object changes, sodoes the linear position of the light falling on the PSD.Circuitry in the sensor monitors the resistance of the PSDelement, and calculates the distance based on thisresistance.

Among the Sharp detectors currently available through

retail channels are two general types:

• Distance judgment sensors provide a simple digital(LOW/HIGH) signal that represents whether an object iswithin detection range. That range is set at the factory,and depends on the specific model of the sensor.Common distances are five, 10, 24, and 80 centimeters.

FIGURE 3. The analog output of theSharp GP2D120 sensor is a non-linear

voltage of between (approximately)0.25 volts and 2.55 volts.

FIGURE 4. Connection schematic for the Sharp GP2D120,showing a transistor used to turn the sensor on and off.

FIGURE 2. The Sharp infrared distancemodules rely on the displacement of

reflected light across a linear plane todetect variations in distance.

SERVO 03.2011 45

Page 40: Robot With Arduino

For example, with the GP2Y0D810 sensor, the output is adigital LOW when an object is within its 10 cm proximityrange, and HIGH otherwise.

• Distance measurement sensors provide an analog voltagethat’s more or less proportional to the distance from thesensor to the detected object. The voltage output is non-linear, as shown in Figure 3. These detectors work over aspan of minimum and maximum distance, usually no

closer than a few inches and up toseveral feet.

Distance judgment sensorsare ideal for interfacing withsimple electronics, as they don’trequire analog-to-digitalconversion. Since the Arduino Unois equipped with a six-input ADC,we can use either type. For theArdBot project, I’ve selected aGP2D120 which has a range of 4cm to 30 cm (about 1.5 inches to12 inches).

The distance is reported as avarying voltage, from approximately 0.25 volts (nodetection) to 2.55 volts (detection at minimum distance).That’s according to the spec sheet, but know that there canbe a normal variation of a few tenths of a volt from onesensor to another.

While the GP2D120 is capable of reporting distancewith acceptable accuracy, for the ArdBot I’ve elected to useit as a “multi-zone” proximity detector. That is, instead of

hassling with converting its analog voltage tosome quasi-precise distance measurement, forthe ArdBot the GP2D120 will instead simplyindicate when an object is within preset zones.

The ArdBot relies on a separate ultrasonicrangefinder for accurate distance measuringand as a secondary near-object detectioncheck. More about the ultrasound rangefinderin a bit.

See Figure 4 for a schematic diagram forconnecting the GP2D120 to the Arduino.Figure 5 has the same circuit, but inbreadboard view. See that I’m being cleverhere, and I’ve added a small 2N2222 NPNtype transistor in order to turn the GP2D120on and off.

The transistor is an optional enhancement,but there are a couple of reasons for it. First,like all of the Sharp sensors, the GP2D120takes constant measurements — about 25 asecond — as long as the device is powered.Current consumption can go as high as 50milliamps when no object is detected. Whilethat’s not a huge current demand, it’sunnecessary power consumption when thesensor is not actually being used.

Listing 1 - SharpIR.pde.const int irCtrl = 12; // Digital pin D12const int irSense = A5; // Analog pin A5int distance = 0;

void setup() {pinMode(irCtrl, OUTPUT);digitalWrite(irCtrl, LOW);Serial.begin(9600); // Use Serial Monitor window

}

void loop() {Serial.println(irRead(), DEC);

}

int irRead() {int averaging = 0;

// turn on, wait 250 ms to completely stabilizedigitalWrite(irCtrl, HIGH);delay(250);

// Get a sampling of 5 readings from sensorfor (int i=0; i<5; i++) {

distance = analogRead(irSense);averaging = averaging + distance;delay(55); // Wait 55 ms between each read

}distance = averaging / 5; // Average out readingsdigitalWrite(irCtrl, LOW); // Turn sensor offreturn(distance);

}

46 SERVO 03.2011

FIGURE 5. Breadboard view ofthe Sharp GP2D120-to-Arduinoconnection. Note the pinout andwiring order of the GP2D120 sensor.Important! The wiring diagram relieson existing connections on thebreadboard. See Part 2 of MakingRobots with the Arduino (Dec ‘10)for details.

Page 41: Robot With Arduino

Second, each time the sensor takes anew reading there’s extra line noiseinduced into your robot’s power supply. Byturning the sensor off when it’s notneeded, the noise is completely removed.(You can also help filter the noise byadding some decoupling capacitors acrossthe +V and ground power connections, asclose to the sensor as possible. Try a 47 μFelectrolytic capacitor and a .1 μF ceramiccapacitor. Be sure to observe correctpolarity of the electrolytic capacitor.)

Listing 1 shows a sketch thatdemonstrates how to use the GP2D120with the Arduino. This is an example sketchonly; in the next installment, you’ll see howthe GP2D120 can be implemented forobject seeking and avoidance, as theArdBot is set loose in your living room andleft to discover what’s around it.

A couple of things to note in thissketch:

• To make a reading, the sensor is turnedon and then allowed to settle for 250milliseconds (ms) before taking areading. The datasheet for the GP2D120indicates a much shorter delay uponstartup, but I’ve found the longer periodis often necessary to avoid spuriousreads.

• The sketch takes five “samples,” eachseparated by a delay of 55 ms. The fivesamples are averaged to remove possibleincorrect readings due to momentaryglitches.

• After the sensor is read, it’s turned back off again.

Open the serial monitor window to observe the actualvalues reported by the sensor, converted from an analogvoltage to 10-bit digital values (0 to 1023) by the Arduino’sADC. Note that because the sensor does not output a fullfive volts when an object is closest, you won’t get the full1,024 steps. Minimum values are about 40 to 60; maximumvalues are in the 625 to 675 range, depending on thesensor and the reflectivity of the object (dark colors tend toproduce slightly lower values). Anything outside theseranges can indicate a spurious reading.

Important! Take note of the connection diagram forthe GP2D120. Sharp uses a polarized JST connector wherethe +V power lead is on the outside and ground is in themiddle. This is potentially dangerous when the other end ofthe wiring is non-polarized, as is often the case withconnectors on general-purpose microcontrollers.

Numerous sources (such as Lynxmotion) sell adaptercables that go from the JST locking connector to a standardthree-pin 0.100” female header. On many of these cables,

the wiring order is “corrected” to place the +V power leadin the center. In this arrangement, damage is less likely tooccur if the connection is flipped. I have shown such acable in the breadboard wiring view in Figure 5. Regardlessof whether you use a cable type that re-arranges the wiringorder, be absolutely sure to observe correct polarity. Orpoof goes your sensor.

Using the Devantech SRF05 Ultrasonic Ranger

Ultrasonic distance measurement —also called ultrasonicranging — is now an old science. Polaroid used it for yearsas an automatic focusing aid on their instant cameras. Tomeasure distance, a short burst of ultrasonic sound (usuallyat a frequency of around 40 kHz) is sent out through atransducer; in this case, the transducer is a specially builtultrasonic speaker. The sound bounces off an object andthe echo is received by the same or another transducer (thisone is an ultrasonic microphone). A circuit then computesthe time it took between the transmit pulse and the echo,

SERVO 03.2011 47

FIGURE 6. Connection schematicfor the Devantech SRF05 ultrasonicranging module.

FIGURE 7. Breadboard view of theDevantech SRF05-to-Arduino connection.

Page 42: Robot With Arduino

48 SERVO 03.2011

and comes up with distance.At sea level, sound travels at a speed of about 1,130

feet per second (about 344 meters per second) or 13,560inches per second. This time varies depending onatmospheric conditions, including air pressure (which variesby altitude), temperature, and humidity.

The time it takes for the echo to be received is inmicroseconds if the object is within a few inches to a fewfeet of the robot. The overall time between transmit pulseand echo is divided by two to compensate for the round-trip travel time between robot and object.

Given a travel time of 13,560 inches per second forsound, it takes 73.7 μs (microseconds or 0.0000737seconds) for sound to travel one inch. If an object is 10inches away from the ultrasonic sensor, it takes 737 μs totravel there, plus an additional 737 μs to travel back, for atotal “ping” time of 1,474 μs. The calculation is:

(1,474 / 73.7) / 2 = 10

First, divide the total transit time by 73.7 (use 74 toavoid using floating point math), then divide by 2. Theresult is the distance from sensor to object, in inches.

For the ArdBot, I’ve selected the SRF05. This sensor isamong a series of ultrasonic rangers by UK-basedDevantech, and were among the first to be marketeddirectly to robot experimenters. The SRF05 is relatively low-cost and easy to use, requiring just one signal line to theArduino, in addition to power and ground.

There are, of course, other ultrasonic rangers that dopretty much the same thing. You can substitute if you’dlike. There’s the Parallax Ping (which is modeled after theSRF0x form factor), and various models by Maxbotix. All are

excellent products and are wellsupported by their manufacturers.

Figure 6 is a schematic diagramfor connecting the SRF05 to theArduino, and Figure 7 shows thesame circuit in breadboard view.Hookup is simple — just route wiresbetween the sensor andmicrocontroller. The SRF05 comes toyou with plated-through holes forthe electrical connections. You cansolder wires directly to the board, orbetter yet use a five-pin maleheader. You can solder the headerfrom either side. I like attaching thewires from the rear (opposite thetransducers), so that they don’t getin the way of the business-end ofthe sensor.

Be careful not to cross up thepower and ground wires. Reviewthe datasheet for the correctpinout. Note that there are two setsof five plated-through holes on the

SRF05 circuit board. Don’t use the set closest to the LEDthat’s mounted on the back (component) side of the board.Those are used for programming the thing at the factory.

As used in the ArdBot, the SRF05 is set up in single-pinmode, using one pin (the one in the middle) for bothTrigger and Echo. Refer to Listing 2 for a demonstrationsketch that shows how to take a reading from the SRF05and display it in the serial monitor window. The valuereturned by the readSonar() function is converted to wholeinches. According to its documentation, the SRF05 canmeasure distances from 1 cm to four meters. That equatesto a range of 0.4 inches to 157 inches.

Adding a Sensor Turret

Anchoring a sensor directly to a robot has itsdisadvantages. The bot can only “see” what’s directly infront of it. To widen its field of view and see at otherangles, the robot must literally reorient itself — somethingakin to spinning around while walking. Okay for theMinistry of Silly Walks, but immensely silly for robots.

With a motorized sensor turret, your robot can scan itsenvironment without ever taking a step — or rolling awheel. One or more sensors are attached to an R/C servomotor which is commanded to sweep back and forth whilethe sensors send back data.

Accuracy is somewhat diminished when using anultrasonic or infrared sensor when it’s attached to arotating sensor turret. Movement affects the reading.During any motion, you can use the measurements forgeneral proximity detection, but you may wish tomomentarily stop the turret (and robot) to get a moreaccurate distance reading.

Listing 2 - usonic.pde.

int duration; // Stores duration of pulseint distance; // Stores distanceint srfPin = 7; // SRF05 connected to dig pin D7

void setup() {Serial.begin(9600);

}

void loop() {Serial.println(sonarRead(), DEC); // Show in Serial Monitordelay(200);

}

int sonarRead () {pinMode(srfPin, OUTPUT); // Set pin to OUTPUTdigitalWrite(srfPin, LOW); // Ensure pin is lowdelayMicroseconds(2);digitalWrite(srfPin, HIGH); // Start ranging delayMicroseconds(10); // with 10 microsecond burstdigitalWrite(srfPin, LOW); // End rangingpinMode(srfPin, INPUT); // Set pin to INPUTduration = pulseIn(srfPin, HIGH); // Read echo pulsedistance = duration / 74 / 2; // Convert to inchesreturn(distance); // Return value

}

Page 43: Robot With Arduino

Figure 8 shows a sensor turret with both Sharp IR andultrasonic modules attached to it. This particular turret(from Budget Robotics; see the Sources box) can spin thesensors a full 360 degrees, enabling the bot to literally seewhat’s in front, to the sides, and behind. You can use astandard servo-driven turret which provides up to 180degrees of side-to-side vision.

You’ll want to select a sensor mount that accepts boththe IR and ultrasonic detectors. The mount in the picture ismade of lightweight plastic, keeping down the overallweight of the robot. Plastic also doesn’t contribute tomicrophonic ringing that can be caused whenever theultrasound module does its “ping” thing. When using ametal mount, you may wish to add small rubber grommetsto the mounting screws — they’re included with most R/Cservos — as a form of insulator. Be sure the exposed backof the sensor does not make direct contact with the metal,or else a short circuit could occur.

Listing 3 shows a demo sketch forrotating the turret in small segments of anarc, sweeping from one side to the other. I’veintentionally limited the span of the turret toprevent the wires from getting tangled, andfrom having either sensor deliver inaccurateresults because of the wire harness at therear. As shown in the sketch, the turret hasan approximate 250 degree span. If you use a360 degree turret, you can experiment withlarger or smaller arcs.

Refer to Figures 9 and 10 for aschematic and breadboard view, respectively,of connecting the turret servo to the Arduino.Note that the breadboard view assumes the

lower half of the breadboard is already populated with thewiring described in Part 2 of this series.

As a demonstration, the turret is made to stopperiodically every 25 degrees, or 10 times when going

SERVO 03.2011 49

FIGURE 8. A servo turret capable of a full 360 degreerotation. (See the text for details.) You can use a standard

servo turret (capable of 180 degree rotation) if you prefer.

Listing 3 - turretScan.pde.

#include <Servo.h>

Servo myServo;const int delayTime = 2000;const int servoPin = 8;

void setup() {myServo.attach(servoPin);

}

void loop() { turretL(); turretR();// Rotate turret in steps// Arguments: min-position, max-position,// delay between stepsturretStep(40, 140, 150);turretCenter();delay(delayTime);

}

void turretR() {myServo.write(40);delay(delayTime);

}

void turretL() {myServo.write(140);delay(delayTime);

}

void turretStep(int minVal, int maxVal, intstepDelay) {

for(int i=minVal; i<=maxVal; i+=10) {myServo.write(i);delay(stepDelay);

}}

void turretCenter() {myServo.write(90);delay(delayTime);

}

FIGURE 9. Connection schematic for the servoturret. Note the use of the separate power

supply for the servo.

Page 44: Robot With Arduino

from one extreme to the other. During each stop, you’dtake a reading from either or both of the IR andultrasonic sensors. Next month, when there’s a little morepage space to play with, we’ll examine an all-in-one

“wanderbot” sketch that combines the sensorturret motion, infrared proximity readings, andultrasonic pings.

Notice that for the 360 degree turret and aGWS S03 servo, the turretR() and turretL()functions work in reverse. The turretR() functionactually scans to the left, and turretL() scans tothe right. This is because the gearing used on theturret flips the direction of travel of the servo. Ileft it this way in case you use a regular non-360enhanced turret. Otherwise, you can simplyrename the functions to flip their logic.

Coming Up

Next month, we’ll add a line followingmodule, and conclude with putting what we’ve learned togood use. You’ll find ideas and programming code for yourArdBot to wander about a room, looking for people, pets,and things to investigate. SV

Gordon McComb can be reached [email protected].

50 SERVO 03.2011

FIGURE 10. Breadboard view of connecting theservo turret to the Arduino. Note that you need toalready have the servo wiring in place (from Part 2 ofthis series) in the bottom half of the breadboard.

Page 45: Robot With Arduino

34 SERVO 04.2011

No, really! Many high-techfactories use line following,where a predefined path ismarked on the ground. The

path can be a painted black or whiteline, a wire buried beneath a carpet, orany of several other methods. The pathto follow can be changed simply bypeeling off the tape and laying down a

new stripe. You can easily and

inexpensively incorporate atape-track navigationsystem in your robot. Theline following feature canbe your bot’s only meansof intelligence, or it can bejust one part of a moresophisticated machine. Youcould, for example, use thetape to help guide yourrobot back to its batterycharger nest. (Beatsclicking your heels threetimes and saying, “There’sno place like home ...”)

So with that in mind, let’s talkabout line following in this installment.

About This Project

As with the previous parts in thisseries, this article builds on earlierissues of SERVO, starting withNovember ‘10. From there, you’ll finduseful information about building andprogramming the ArdBot which is alow-cost expandable desktop robotthat uses an Arduino Uno (or

compatible) microcontroller as its brain. The ArdBot is shown in its fully

“decked out” form in Figure 1. Thepictured version incorporates all of thefeatures we’ve talked about individuallyin previous installments, plus the linefollowing functionality of this month’sarticle. The ArdBot can be constructedout of plywood, plastic, even pictureframe mat board. It’s designed to

Making RobotsWith The

FIGURE 1. The ArdBot complete withall hardware detailed in this and

previous installments.

You want simple. You want cheap. You want effective. And, of course, you want fun. Thatpretty much sums up line following — probably the simplest of all navigation systems formobile robots. The basic idea goes back centuries, and is well known to anyone who’s taken atrain ride. Only in robotics, instead of a mechanical track the vehicle stays on course by shininga light onto a piece of tape that’s stuck to the floor. Pretty advanced stuff.

ArduinoPart 6 - Follow That Line!

By Gordon McComb

ArdBot UpdateLike all expandable robots, the

ArdBot is designed as a permanent workin progress. It's never truly finished. Inlast month's article, I demonstrated amethod of depowering the ArdBot'sSharp infrared proximity detector, as away to conserve power when it's notneeded. As I've refined the Ardbot'ssoftware, I have determined the methodis not necessary. Turns out that inpractice, it slows things downconsiderably and introduces as muchsignal noise as it eliminates.

If you've been following in theconstruction of the ArdBot, just skip theextra control electronics to the Sharpsensor and wire it directly. For moreinformation on this and otherenhancements for the ArdBot, see theArdBot Construction Notes atwww.robotoid.com/servomag.

Page 46: Robot With Arduino

allow easy prototyping — it’s a robotmade for your own freedom ofexpression.

In last month’s issue, I mentionedthis article would conclude the series.Well, turns out there was too much tocover in one last installment. So, thistime around we’ll tackle just the linefollowing component, and thenconclude with putting all the piecestogether. Next time, we’ll combinewhat you’ve learned to create a fully-capable dual-function robot thatfollows predescribed paths, andexplores rooms and seeks outinformation about its environment.

The Basics of Line Following

With a line following robot, youplace white, black, or reflective tape onthe floor — the color of the tape isselected to contrast with the floor.Using simple optics, the robot thenfollows that line.

Black PVC electrical tape absorbsinfrared light, and it’s cheap and easyto use. So, the most popular methodof making a track is to lay down a pathof electrical tape onto white paper, likethat in Figure 2. I prefer using a stiffposter board that’s coated with asmooth finish on at least one side. Thecoating reflects more light, and helpsprevent the paper from beingtransparent to the infrared light. Trythe nearby dollar store for inexpensiveposter board. I get mine for 50 cents asheet. Each sheet measures 22 x 28inches. It comes in colors, but youwant to start out with white.

For the best results, the floorshould be hard, like wood, concrete, orlinoleum, and not carpeted. You canalso use a large table. To sense theline, optical sensors are placed in frontof or under the robot. These sensorsincorporate an infrared LED (emitter)and an infrared phototransistor(detector). The output of thephototransistor indicates whether ornot it sees light reflected off the floor.Assuming a black line on a white floor,the absence of reflected light meansthe robot is over the line.

You can use most any infrared LEDand phototransistor for the emitter and

detector. Mount them closeto one another, and pointthem in the same direction.All you need to finish thecircuit is a couple ofresistors, as shown inFigure 3.

Let’s take a closer lookat the components used inmaking a line followingcircuit.

Emitter LED and Current LimitingResistor

The electronics for linefollowing are technicallytwo separate circuitsconnected to the same power source.The first part is the emitter LED and itsresistor. The purpose of the resistor isto limit current flowing through theLED. You select the value of theresistor based on how much currentyou want to pass through the LED. Themore current, the brighter the LED willglow.

Ideally, the LEDs you use comewith specifications, so you knowthings like forward voltage drop andmaximum forward current. With thisinfo, you can use some simple mathto calculate the value of the resistoryou need. Here’s the formula:

R = Vin - Vdrop / If

Vin is five volts. Assuming Vdrop is1.7 volts (kinda typical for infraredLEDs), and a desired 30 mA current,the formula becomes:

110 = 5 - 1.7 / 0.030

If the result isn’t a standardresistor value, always choose the nexthighest. In this case, 120 Ω.

(Notice If is given as a decimalfraction. The formula expects amps,but these LEDs are rated in milliamps.You need to move the decimal pointover to convert amps to milliamps; avalue of 0.030 is 30 milliamps.)

If you like to buy from surplus(like I do), you may not have anyspecs for the infrared LEDs you use.Instead, you can apply some educatedguesswork to select a resistor valuethat’s close to what you need. Iusually start with a 470 Ω resistor, asthis provides enough drive current toallow the LED to glow, but not somuch that it will burn it out.Depending on the LED, you may needto reduce the value of the resistor,knowing that if you get too low (say,

www.servomagazine.com/index.php?/magazine/article/april2011_McComb

FIGURE 2. Black PVC electrical tape onwhite poster board makes an excellent

line following course.

FIGURE 3. The basic line followingcircuitry has two parts: emitter and

detector. Light from the emitter reflectsoff a surface and into the detector.

SERVO 04.2011 35

Page 47: Robot With Arduino

36 SERVO 04.2011

under 150 Ω or so), the chances ofburning out the componentdramatically increase.

Fortunately, many IR LEDs areengineered for fairly high maximum

forward current, so you have a bit ofwiggle room. While the averagevisible-light LED might have amaximum forward current of 30 mA,the typical IR LED is often ratedhigher, some 50 mA or more. (Ofcourse, there are always exceptions.For the sake of science, you should beprepared to blow out an LED now and then.)

Should you always choose to drivethe LED “hard” with lots of current?Not necessarily. For one thing, doingso ends up consuming more batterypower. It can also cause unnecessarylight spoilage — why use a searchlightwhen a candle works just as well? Tostart, always go with a lower current,and then decrease the value of theresistor if your circuit isn’t responsiveenough.

If you have a choice, pick an LEDwith a narrow viewing angle. It shinesmore light into one spot. The genericT-1 size (3 mm diameter) water-clearLED is a good choice. These have abuilt-in lens, and are both plentifuland cheap. They’re also easy tomount by drilling a 1/8” diameter holeinto the bottom of the robot.

Phototransistor and Divider Resistor

The second half of the linefollower circuit is composed of aphototransistor, along with a resistorthat forms a voltage divider. The valueof this resistor depends on thecharacteristics of the phototransistorand the circuit you’re connecting to;the higher the value of the resistor,the more sensitive the transistorbecomes to variations in light

intensity.The easiest way to

determine the value of theresistor is throughempirical testing. Wire thephototransistor as shownin Figure 3, starting witha 10 kΩ resistor. Connecta voltmeter between theoutput and groundconnections. Use anincandescent (not

fluorescent or LED) desk lamp toalternately shine or block light to thephototransistor. You should see thevoltage fluctuate on your meter. Itmay not be much.

Now try incrementally largerresistance values until you observe agood voltage swing — the differencein voltage between darkest andlightest conditions. It won’t be the fullzero to five volts of the power supply,but the larger the difference, thebetter. You don’t need (or want) toselect ever-higher resistance valueswhen a lower one works just as well.For the phototransistors I used for myprototype ArdBot, I found goodsensitivity and voltage swing with 100 kΩ resistors.

What if the phototransistor stilldoesn’t respond well to light, evenwhen using very high values? Thephototransistor may be bad, or it maybe connected in reverse. Try flipping itaround in the circuit or select anotherone. (See Figure 4 for how todetermine the leads of the typical LEDand phototransistor. Note that in aphototransistor, the flatted side/shortlead is usually the collector.)

Like LEDs, phototransistors comein a variety of package styles. Look forthe same package type you use forthe LED. A phototransistor in a T-1package has its own built-in lens, andit’s easy to mount through a hole inthe bottom of your robot.

Arranging theInfrared LED &Phototransistor

The LED emitter andphototransistor detector should bemounted side by side, and pointing inthe same direction. To avoid light“crosstalk” — light that shines fromthe side of the LED and directly into

Is That Infrared LED On or Off?

How do you know if an infrared LEDis actually emitting infrared light? Yourbest bet is to use the camera in yourmobile phone. Most of these camerasare at least partially sensitive to theinfrared light wavelengths produced byIR LEDs (typically about 800 to 950nanometers).

Activate the LED and point thecamera at it. Look at the scene from thedigital viewfinder of the camera. If the IRLED is working, you’ll see its light aswhite or pale blue. Figure A shows theinfrared emitters mounted on theunderside of the ArdBot. The picturewas taken using an Apple iPhone.

If the camera isn’t picking upanything, do one last test to ensure itcan see IR light. Point any infraredremote control at the camera and presssome buttons. You should see a seriesof bright flashes.

FIGURE A.

FIGURE 4. Detail of a typical LED andphototransistor T-style package. Use theshort lead and/or flatted side todetermine the pinout.

FIGURE 5. Two “store bought”reflective sensors mounted on theleading edge of the ArdBot. They’reused to follow a 3/4” line made ofblack electrical tape.

Page 48: Robot With Arduino

the phototransistor — addsome black heat shrinktubing around the LED, thephototransistor, or both. Or,place a small piece of metalor opaque plastic betweenthe two to act as a baffle.

While using separateLEDs and phototransistors isthe least expensive methodof creating a line followingsensor, an easier approach isto use an all-in-one reflectivesensor. These come invarious shapes and sizes,and are fairly common on the surplusmarket.

Figure 5 shows a pair ofreflective sensors mounted on theoutside edge of the ArdBot. Thesesensors — which I bought surplus whoknows when — provide their ownmounting flange (many do; you justhave to be patient and look around).They’re easy to use, but because thisstyle of reflector is bulky, they can’t bemounted under a low profile robotsuch as the ArdBot. Instead, they haveto be placed on the outside edge.That’s okay, as it demonstrates one ofmany ways to perform line following.

Since I’m on the subject ofmounting, reflective sensors like to beas close to the ground as possible,while not making actual contact. Asnoted in Figure 6, the ideal distancefrom the sensor to the ground is 1/8”to 3/8”, depending on the design ofthe sensor. I mounted the two sensorsto the underside of the ArdBot usingplastic spacers, in order to decreasethe distance from sensor surface andfloor.

Several online sources offerunitized emitter/detector modules, likethe QTI sensor from Parallax shown inFigure 7. The resistors and allcomponents are mounted on a smallcircuit board. Simply attach wires tothe module: power, ground, andsignal. A single hole allows you tomount the module almost anywhereon the robot.

Another variation is theemitter/detector array whichcombines two or more pairs ofinfrared LEDs and phototransistors ona single circuit board. All componentsare already on the board, and theLED/phototransistor pairs are spaced

3/8” to 1/2” from one another —ideal for line following. In a bit, you’llsee how to use one of these arrayswith the ArdBot.

Whether you use homebrew linefollowing sensors or rely on ready-made modules, the emitter anddetector can be aligned either incolumn or row orientation, whateverfits best. By their nature, linefollowing requires at least two pairs ofemitters/detectors. These are placed aspecific distance from one another, inorder to determine the location of theline under the robot.

(In a pinch, you can even shareone LED and several phototransistors.In this scheme, the light of the LED

provides a large enough spot for twophototransistors — one on each side.This method is not recommendedthough, unless space is extremelylimited.) The spacing of theemitter/detector pairs depends on thewidth of the tracking tape. To beeffective, at least one sensor shoulddetect the line at any one time. Withtoo much space, a thin line can get“lost” between sensors. You can fixthis either by grouping theemitter/detector pairs closer together,or using a wider tape. Figure 8 showssome variations. As most, PVC

FIGURE 6. Placement ofthe reflective sensors on

the robot. For best results, theface of the sensors should be1/8” to 3/8” from the ground.

SERVO 04.2011 37

FIGURE 8.The spacing

betweenreflectivesensors is

dependent onthe width ofthe line. Theline must bevisible to at

least onesensor at any time.

FIGURE 7. Parallax QTI reflective sensor,useful for line following (and other

things). Note that the output of thissensor is a pulse, not an analog voltage.

FIGURE 9.Circuit for

connecting twoLEDs and

phototransistorsto the Arduino.See the text for

the values ofthe four

resistors.

Page 49: Robot With Arduino

38 SERVO 04.2011

electrical tape is 3/4” wide; a spacing of 3/8” to 1/2” ismost common.

By the way, when we talk of spacing, it means thedistance between the optical centers of eachemitter/detector pair, regardless of the physical dimensionsof the sensor. Given sensors that are physically 1/4” wideand 3/8” between optical centers, the actual spacing

between each component is only 1/8”.

Constructing a Two-Sensor Line Follower

The most basic line follower uses two emitter/detectorpairs. To work properly, the pairs must be close enough

together to both see the line when the robot is directlyover it. If the left sensor doesn’t detect the line, it meansthe robot has veered too far to the right. To compensate,the robot steers back over to the left. Conversely, if theright sensor doesn’t detect the line, the robot corrects itspath by briefly steering back toward the right.

Figure 9 shows the schematic view of connectingtwo IR LEDs and two phototransistors to the Arduino.Since the output of the phototransistors is a variablevoltage, we use two of the Arduino’s analog-to-digitalconverter inputs; specifically, pins A3 and A4. Figure 10shows the same circuit but in breadboard view. (Thebottom of the breadboard is dedicated to the servowiring. See Part 2 of this series for more information.)

Resistor values to start (see the previous discussion forselecting the values based on the LEDs andphototransistors you use) are:

R1, R2: 470 ΩR3, R4: 100 kΩ

Listing 1 shows a simple line following sketch. Aftersetting up the two servos, the analog values of the twosensors are read. These values are then applied to one ofseveral actions:

• Line is detected by both sensors; keeps going forward.• Line is detected only by the left sensor; steer briefly to

the left.• Line is detected only by the right sensor; steer briefly

to the right.• Line is not detected by either sensor; steer in a circle,

Listing 1 /*ArdBot line following demo using2 reflective sensors

Requires Arduino IDE version 0017 or later (0019 or later preferred)

*/

#include <Servo.h>

Servo servoLeft; // Define left servoServo servoRight; // Define right servoconst int lineLSense = A3;const int lineRSense = A4;

int irReflectR = 0;int irReflectL = 0;int thresh = 400;

void setup() { servoLeft.attach(10); // Left servo pin D10servoRight.attach(9); // Right server pin D9

}

void loop() {

// Read reflective sensorsirReflectL = analogRead(lineLSense); irReflectR = analogRead(lineRSense);

if (irReflectL >= thresh && irReflectR >= thresh) {line_forward(); // on line

}

if (irReflectL >= thresh && irReflectR <= thresh) {line_spinLeft(); // veering off rightdelay(4);

}

if (irReflectL <= thresh && irReflectR >= thresh) {line_spinRight(); // veering off leftdelay(4);

}

// If line is lost try to reacquireif (irReflectL < thresh && irReflectR < thresh) {

line_spinRight();delay(20);

}

}

// Motion routines for line followingvoid line_forward() {

servoLeft.write(0);servoRight.write(180);

}

void line_slipRight() {servoLeft.write(90);servoRight.write(180);

}void line_slipLeft() {

servoLeft.write(0);servoRight.write(90);

}void line_spinRight() {

servoLeft.write(180);servoRight.write(180);

}void line_spinLeft() {

servoLeft.write(0);servoRight.write(0);

}

FIGURE 10. Breadboard view of the circuit in Figure 9.

Page 50: Robot With Arduino

and attempt to re-acquire the line.(If you use a self-contained

emitter/detector module, thenconnection is much easier. Just attachthe power pins of the module to 5Vand Gnd of the Arduino, and thesignal pin to either analog pin A3 orA4. If you use a self-contained module,be sure its output is analog, or else itwon’t work with the program inListing 1. As we’ll see, some variations inmodules — including the aforementionedParallax QTI — use a timed pulse ratherthan a varying voltage.)

Important! On a bidirectionalrobot like the ArdBot, front and back— and therefore right and left — arearbitrary. The sketch in Listing 1assumes the line following optics areactually in the rear of the robot. It'sdone this way because othernavigation sensors on the ArdBot aremounted on the opposite end. We'lluse this feature in the next installment,where the ArdBot serves as a dual-purpose bot and travels in thedirection dictated by its current mode.

If your robot goes the wrongway, you can simply swap the servoconnections on the breadboard; leftbecomes right, and right becomes left.

As I said before, I mounted thetwo sensors on the outside edge ofthe robot rather than underneath.Though there are advantages toputting the emitters/detectors underthe bot, this method works too. Iespecially like this approach as ademonstrator because it’s much easierto visually see how the robot istracking the line.

To play with the ArdBot as a line

follower, you’llneed to construct

a track for the robot to follow. Seethe sidebar “Building a Line FollowingCourse” for some basic ideas.

Note the thresh variable and thenumeric value I’ve given it. In mytests, I found that the sensor readingswent from 30 when over white and850 when over black. I picked athreshold value of 400; that’s about

halfway between. You’ll need tocalibrate the thresh value based onthe sensors you use. Listing 2provides a simple routine fordisplaying the numeric values returnedby an analog line following sensor.

To use it, compile and downloadthe sketch in the usual manner, thenopen the Serial Monitor window. Placethe sensor connected to analog pinA3 over the black line. Note the value.

Forget protractors, compasses, andstraight edges for now. For a basic linefollowing course — good for practiceand experimentation — just pull out acouple of sheets of poster board andlay down some tape.

Using just a single sheet of posterboard, begin by making a U-shape. Keepthe line away from the very edges of theboard. As you apply the tape give it abit of stretch, but not too much. Thetape might contract as it springs backinto its former size. You want to avoidexcessively tight corners. If the edges ofthe tape pucker up in a curve, it’sprobably too tight.

On the same or another sheet ofposter board, make a few sinusoidalcurves like the ones in Figure B wherethe radius of the curves is the radius ofthe ArdBot’s wheel base or larger. Whenusing spin turns (rather than slip turns)and with a sensor array like the QTR-8,you can expect the ArdBot to managecurves that are at least as small as itsown wheel base diameter.

If you need a larger course, placetwo or more sheets of poster board endto end. Cut the tape off right at theedges of the paper. You don’t need tooverlap the tape for a perfectlyseamless transition, but avoid gaps ofmore than 1/84”.

Wanting to use something otherthan electrical tape? Feel free toexperiment, but know that what looksblack to you might be opticallytransparent to infrared light. Black

marker is a good example. Unless youheavily apply marker ink to both sides of the paper, odds are it’ll prove to be a poor choice for making line followingtracks.

If you have a laser printer, you canexperiment with making segments oftracks using a graphics program. Printout each sheet and tape them together.Be sure to use a fresh toner cartridge,and adjust the toner density to make itdarker. The same technique may (or maynot) work for ink jet printers. Whilepitch black to our human eyes, the ink isnot opaque to infrared light.

Alternatives to black PVC electricaltape include black masking tape (trymore than one layer thick), charting andgraphics tape, and decal making tapes.While it’s most common to use blacktape on a white background, you canreverse the tones — just remember toalso flip the programming logic in yoursketch. Try using black constructionpaper or poster board and silverreflective tape.

Building a Line Following Course

FIGURE B.

SERVO 04.2011 39

FIGURE 11. The Pololu QTR-8 is an arrayof eight reflective sensors mounted on a3” wide circuit board. You can usemultiple sensors (the ArdBot uses five) tobuild an effective line follower. I’veselected the QTR-8RC which is theversion that provides a timed pulse (as opposed to ananalog voltage) tomeasurelight levels.

FIGURE 12.Orientation of the

QTR-8RC on theunderside of the

ArdBot. I’ve offsetthe board so that

sensor 3 iscenterline. This ispurely subjective,

and you can mountthe board in anyway you choose.

For a moreelaborate system,

use all eightsensors and mount

the centerlinebetween sensors

4 and 5.

Page 51: Robot With Arduino

40 SERVO 04.2011

Now place it over the whitebackground. For best results, thereshould be a variation of at least 200points. (Example: If the value overblack is 600, then the value over whiteshould be under 400.) Set the threshvariable in your sketch somewherebetween the values you obtainedbetween black and white.

Feel free to experiment with thesketch to see how to improve theperformance of your line followingArdBot. I’ve intentionally kept it simpleto make it easier to understand. Tryusing the line_slip functions ratherthan the line_spin functions. How doesthis affect maneuverability of the robot?

Constructing a Five-Sensor Line Follower

The two-sensor line followerprovides good results even on courseswith reasonably tight turns. It offers agood starting place to try things out.With more sensors, you can betterdetermine where the line is, was,and/or should be. Adding moresensors is a simple matter ofconstructing more emitter/detector

pairs. If you go that route, I adviseyou build your own self-containedmodule using a solderboard topermanently connect all thecomponents. This dramaticallydecreases the number of wires youmust attach to the Arduino andsolderless breadboard.

A better approach — and one thatdoesn’t cost that much — is to use aready-made emitter/detector array,like the one in Figure 11. This array —the QTR-8 from Pololu — containseight sensor pairs, though for thefollowing project we’ll only use five ofthem. Everything comes on thesurface-mount board which is thinenough to mount underneath theArdBot (see Figure 12). Just attachpower, ground, and signal wires tothe sensor pairs you wish to use.

Note that I’ve lined up thesensors so that sensor 3 (third fromthe left) is centerline in the base. I’monly using the first five sensors,leaving sensors 6-8 unconnected (seeFigure 13). With this arrangement, Iobtain values from sensors 1 through5, with sensor 3 directly in the middleof the ArdBot.

The QTR-8 is available in twoversions: analog and RC. I’ve selectedthe RC version (part QTR-8RC), as itcan be connected to either the analogor digital pins of the Arduino. The RCcomes from the resistor and capacitorused with each sensor. In operation,the output of each sensor of the arrayprovides a pulse whose lengthdepends on the relative darkness orbrightness of the light detected by thephototransistor (the Parallax QTI worksin the same way). By measuring thelength of this pulse, it’s possible toobtain very accurate readings fromeach sensor. As it turns out, Pololumakes available a handy library forusing the QTR-8 array with theArduino. The library simplifies the useof the sensor array, and it’s ideallysuited for line following. See Sourcesfor URLs for the documentation forthe QTR-8 and the Arduino library(there’s also a library for generic AVRmicrocontrollers; be sure to get theone fine-tuned for the Arduino).

The Arduino QTR-8 library comesin a zip archive file. Download it toyour computer, then:

1. Exit the Arduino IDE if it’s alreadyrunning.

2. Find your Arduino sketchbookfolder (normally it's in MyDocuments).

3. Look for and open the librariesfolder. If there isn't a foldernamed libraries, create one.Extract the contents of theArduino QTR-8 library into thisfolder. This creates a new foldernamed PololuQTRSensors.

4. Depending on the way your zipextraction program works, thefiles in PololuQTRSensors may belocated within yet another folder.

Listing 2

// ArdBot reflective sensor demo

int irReflect = 0;

void setup() { Serial.begin(9600);

}

void loop() { // Connect sensor to analog pin A3irReflect = analogRead(A3);Serial.println(irReflect, DEC);delay (200);

}

FIGURE14.“Turningcircles”when using spinturns asopposedto slipturns. In aslip turn,the circle is twice as large.

FIGURE 13.Breadboardview ofhooking upthe QTR-8RCto theArdBot.

Page 52: Robot With Arduino

Move the files out of this innerfolder, so they are directly underPololuQTRSensors.

5. Start the Arduino IDE. In the IDE,choose Sketch->Import Library->PololuQTRSensors. (If thePololuQTRSensors item is notshown, exit the IDE and double-check that you have unpacked thezip file to the proper place.Restart the IDE and look again.)

When you select thePololuQTRSensors library item, thefollowing should be inserted into yoursketch:

#include <PololuQTRSensors.h>

This establishes that you wish touse the PololuQTRSensors library andall its features in your sketch. Listing3 shows a complete demonstration ofusing the QTR-8RC with the Arduinoand ArdBot. It uses thePololuQTRSensors library to do mostof the heavy lifting. (As with Listing1, this sketch assumes the QTR-8 hasbeen mounted on what I've definedas the rear of the ArdBot. If yourrobot goes in the opposite direction,simply swap the left servo connectionfor the right.) Points of interest in thissketch include:

• It creates a single object thatrepresents the QTR-8 sensor array.The name of the object is qtrrc. Itsconstructor (the programmingstatement that creates the object)requires a number of parameters,including the Arduino pins used forconnecting to the array and thetotal number of sensors. I’m usingdigital pins 4, 5, 6, 11, and 12.

• The PololuQTRSensors libraryincludes a method for calibratingthe sensors. This method is calledwith the line qtrrc.calibrate(). Thiscalibration takes place in the setup()function when the Arduino firstruns the sketch. During calibration,the built-in LED on pin D13 of theArduino lights up. This is your cueto slowly move the sensor arrayover the lightest and darkest areasof your line following course. Thisstores the minimum and maximumdetected levels, and automaticallyadjusts for differences in the

individual sensors. The LED goes outwhen calibration is done.

• I’m using only the position valueprovided by the PololuQTRSensors

library which combines the resultsfrom all the sensors into one (youcan get the results from theindividual sensors, as well). The

SERVO 04.2011 41

Listing 3 - QTR-8RC Line Following Sketch./*ArdBot line following demo usingPololu QTR-8RC sensor array

Requires Arduino IDE version 0017 or later (0019 or later preferred)

Requires PololuQTRSensors library(available from Pololu; see text)

*/

#include <PololuQTRSensors.h>#include <Servo.h>

Servo servoLeft; // Define left servoServo servoRight; // Define right servo

#define NUM_SENSORS 5 // Number of sensors#define TIMEOUT 2500 // Maximum timeout per sensor

// QTR-8 connected to digital pins 4, 5, 6, 11, and 12PololuQTRSensorsRC qtrrc((unsigned char[]) {4, 5, 6, 11, 12},

NUM_SENSORS, TIMEOUT, QTR_NO_EMITTER_PIN);unsigned int sensorValues[NUM_SENSORS];int variance = 300; // Variance from center (2000)

void setup() {servoLeft.attach(10); // Left servo pin D10servoRight.attach(9); // Right server pin D9

delay(500);pinMode(13, OUTPUT);digitalWrite(13, HIGH); // Show calibrate modefor (int i = 0; i < 400; i++) {

qtrrc.calibrate(); // Read sensors to calibrate}digitalWrite(13, LOW); // Calibrate completeddelay(1000);

}

void loop() {unsigned int position = qtrrc.readLine(sensorValues);

if (position > (2000 - variance) && position < (2000 + variance)) {line_forward();

}if (position > 2000 + variance) {

line_spinLeft(); delay(2);

}if (position < 2000 - variance) {

line_spinRight(); delay(2);

}}

// Motion routines for line followingvoid line_forward() {

servoLeft.write(0);servoRight.write(180);

}

void line_slipRight() {servoLeft.write(90);servoRight.write(180);

}void line_slipLeft() {

servoLeft.write(0);servoRight.write(90);

}void line_spinRight() {

servoLeft.write(180);servoRight.write(180);

}void line_spinLeft() {

servoLeft.write(0);servoRight.write(0);

}

Page 53: Robot With Arduino

position value indicates the relativeposition of the array over the line.With five sensors, the value will gofrom 0 to 4000.

Incremental values between 0 and4000 are possible. These indicate theline is between sensors. For example,a value of 1500 means the line ismidway between sensors 2 and 3.

Recall that I’ve lined up sensor 3with the centerline of the robot. Avalue of 2000 means the line isdirectly centered under the robot. Anyvalue less than 2000 means the robothas gone off course to the left, so itshould be steered over to the right.Conversely, any value more than 2000means it’s gone off course to the right.

Even when the robot is over theline, the position value will rarely beexactly 2000. So, I’ve added avariance to the centerlinemeasurement to prevent the robotfrom constantly “hunting” right andleft. With a variance of 300,“centered” means anywhere between1700 to 2300. You are free to playaround with this value. Just changethe variance variable accordingly.

Slip Turns Versus Spin Turns

Take another look at the sketchesin Listings 1 and 3. You’ll see twosets of functions for turning right andleft. One set is referred to as slip, andthe other as spin. Here’s the difference:In a slip turn, one motor stops whilethe other continues. In a spin turn,one motor reverses direction while theother continues. As shown in Figure14, the two approaches affect howsharp of a turn the robot can make.

In a slip turn, a differentially-steered vehicle like the ArdBot turns ina circle equal to double its wheelbase. Since the ArdBot has a seveninch wheel base, that means therobot can trace the path of a 14 inchcircle. If you cut out a section of that14 inch circle to make a curve (anddepending on the number and/orplacement of sensors), that curverepresents the tightest corner therobot can reliably manage.

As it happens, curves from a 14inch circle are still pretty tight.However, the ArdBot can manage

even better if its wheels rotate inopposite directions in a turn. In a spinturn, the vehicle can trace a muchsharper path; the minimum curvaturewill greatly depend on the numberand placement of the sensors.

Each type of turn has its place.Slip turns tend to be smoother. Onlythe tightest corners require spin turns,and ordinary cornering can use slipturns. It’s not practical to determine ifa corner is too steep when using atwo-sensor line follower, but it’s quitepossible in systems that use five ormore sensors. The further away theline is from the center sensor, thesharper the turn.

In a more detailed sketch, youcould use the position informationprovided by the QTR-8 (or equivalent)sensor to determine which type ofturn is required. For example, if thevalue is between 2300 and 3000, therobot need only correct its courseusing a slip turn. If the value is above3000, a spin turn will do the trick.

Line FollowingEnhancements

There are plenty of ways toenhance the functionality of theArdBot’s line following feature,especially when using a sensor array.

For example, by placing a three tofive inch strip of tape perpendicular tothe end of the track, you can haveyour robot know when it’s reached itsdestination. Add a routine where iffour or more sensors see black, thecourse is finished and the robotshould stop.

We’ll talk about this enhancementand a few others in our nextinstallment. In the meantime, feel freeto experiment on your own. Buy anextra roll of electrical tape, a stack ofposter board, and have fun!

Coming Up ...

Now with all the hardware inplace, we’ll finish up by putting whatyou’ve discovered to good use. You’lllearn more tricks of the trade for linefollowing, plus unearth ideas andprogramming code to allow yourArdBot to explore a room, looking forpeople, pets, and other objects toinvestigate. SV

If you’d like to build the ArdBot, be sure to start with the November ‘10 issue ofSERVO Magazine for Part 1 of this series.Also check out the following sources forparts:

Prefabricated ArdBot body pieces withall construction hardware:

Budget Roboticswww.budgetrobotics.com

Arduino Resources:

Arduinowww.arduino.cc

Fritzingwww.fritzing.org

Online Retailers of Arduino, infraredsensors for line following, and components:

AdaFruit Industrieswww.adafruit.com

Jamecowww.jameco.com

Lynxmotionwww.lynxmotion.com

Pololu Robotics & Electronicswww.pololu.com

RobotShopwww.robotshop.com

SparkFunwww.sparkfun.com

Pololu QTR-8 Datasheets and ArduinoLibrary:

User Guidewww.pololu.com/docs/pdf/0J12/QTR-8x.pdf

Library Documentationwww.pololu.com/docs/pdf/0J19/QTR_arduino_library.pdf

Library files (in zip format)www.pololu.com/file/download/PololuQTRSensorsForArduino.zip?file_id=0J403

Sources

Value Meaning

0 Line is under sensor 1 or hasmoved beyond sensor 1.

1000 Line is under sensor 2.

2000 Line is under sensor 3(the middle).

3000 Line is under sensor 4.

4000 Line is under sensor 5 or hasmoved beyond sensor 5.

42 SERVO 04.2011

Page 54: Robot With Arduino

HandsOn Technology http://www.handsontec.com

1

USB-RS232 Interface Card: HT-MP213A compact solution for missing ports…Thanks to a special integrated circuit from Silicon Laboratories, computer peripherals with an RS232 interface are easily connected to a USB port. This simple solution is ideal if a peripheral does not have a USB port, your notebook PC has no free RS232 port available, or none at all !

After a slow and faltering start, the USB port has become commonplace on PCs, to the extent that the latest GHz machines have just one RS232 port left, or none at all. The compact USB-RS232 interface described in this article allows your good old RS232 peripherals (printer, programmer system, etc.) to be hooked up to a USB port. The free driver programs for Win 2000/XP, Linux and Apple Macintosh make the interface virtually transparent, enabling the USB port to behave like a regular COM interface.The driver and the conversion chip from Silicon Laboratories allow a full serial data link to be set up on a 9-way RS232 connector, including all handshaking signals.

1. THE SILICON LABORATORIES CP2103 SYSTEMS OVERVIEW

The CP2103 is a highly-integrated USB-to-UART Bridge Controller providing a simple solution for updating RS-232/RS-485 designs to USB using a minimum of components and PCB space. The simplified block diagram of the CP2103 is shown in Figure 1 and the pin assignment, in Figure 2. Royalty-free Virtual COM Port (VCP) device drivers provided by Silicon Laboratories allow a CP2103-based product to appear as a COM port to PC applications. The CP2103 UART interface implements all RS-232/RS-485 signals, including control and handshaking signals, so existing system firmware does not need to be modified. The device also features up to (4) GPIO signals that can be user-defined for status and control information. Support for I/O interface voltages down to 1.8 V is provided via a VIO pin. In many existing RS-232 designs, all that is required to update the design from RS-232 to USB is to replace the RS-232 level-translator with the CP2103. Silicon Laboratories has taken care of the PC side of things by supplying royalty-free Virtual COM Port (VCP) device drivers. If you've ever used a PC RS-232-to-USB converter, you know that it looks like a standard COM port to the PC and its applications. The VCP device driver also pretends to be a standard COM port. That means that we can use our newly acquired microcontroller USB interface to communicate with a Tera Term Pro terminal window on a computer just as if we were using RS-232 hardware on the embedded side.

2. HT-MP213 USB-to-RS232 CONVERTER BOARD

The HT-MP213 is designed to transition a piece of hardware from an RS-232/485 interface to a USB interface. We were attracted to the CP2103 because of its skinny schematic diagram. If we believe what the CP2103 datasheet schematic is telling us, it doesn't require any external resistors or crystals to bring a fully compliant USB 2.0 interface to life. The silicon encapsulates a level 2.0 full-speed function controller, transceiver, EEPROM, oscillator, and UART in a tiny QFN-28 package. The internal EEPROM is used for storing vendor-specific information in commercial applications. If we find that we need to access the EEPROM, there is easy access and programming via its USB interface.

Page 55: Robot With Arduino

48 SERVO 05.2011

Microcontrollers changed all that. Instead ofaltering hardware, you just revise a line or twoof programming code. It’s easier, faster, andyou’re not as likely to burn your fingers. You

definitely don’t have to make as many trips to RadioShack —in your bell bottom pants or otherwise.

What’s even better than using microcontrollers withyour robot? Using cheap microcontrollers, of course! Theopen source Arduino is a leader in low costmicrocontrollers. For about $30, you get a completedevelopment board. Just plug it into your computer viaUSB, fire up the free software, and start coding.

For the last six months, I’ve been writing about theArdBot — an expandable and affordable robot test platformthat uses an Arduino Uno as its brain. Previous articles havediscussed core concepts and have introduced important motorand sensor interface techniques. In this seventh and final

installment, you’ll discover ways to mash all the individual bitsand pieces into one autonomous and fully functioning bot.

About the ArdBot Project

As a review, this article builds on earlier issues ofSERVO Magazine, starting with November ‘10. From there,you’ll find useful information about building andprogramming the ArdBot.

The ArdBot is shown in Figure 1 fully populated withall sensors and accessories discussed in the previousinstallments. The ArdBot can be constructed out ofplywood, plastic, or even picture frame mat board.

This part assumes you’ve read the previous articles —and ideally, built the ArdBot.

ArdBot Hardware Revisted

Up until now, the ArdBot has used a mini breadboard(with 170 tie-points) as aprototyping area. That workedwhen discussing individualsensors, but it doesn’t offerenough room when puttingeverything together.

To expand the space, youcan add another minibreadboard or use a 300 tie-point board like the one shownin Figure 2. These boards arecommonly available with 400tie-points, including two

Making RobotsWith The

FIGURE 1. The fully featured ArdBot with allhardware attached.

ArduinoPart 7 - Putting It All Together

By Gordon McComb

It was the 1970s when I first started playing with robotics. Back then, it was bell bottompants, disco, and robots that used hard-wired circuits. If you wanted to change thefunctionality or behavior of your bot, you had to pull out the trusty soldering iron.

FIGURE 2. Use a 300 tie-pointbreadboard when constructingthe fully featured ArdBot.

Page 56: Robot With Arduino

removable contact rows. You don’t need the rows,so just slip them off and save them for somethingelse. An example is the PB-400 ($4) from AllElectronics. Refer to the following illustrations for apictorial view of wiring the solderless breadboard:

• Figure 3 shows just the servo wiring. Note that theservos are powered by their own 4.8 to 6 volt supply.

• Figure 4 shows the header connections andcomponent wiring. Important! Some of thewiring may differ slightly from that in previousinstallments of this series, so if you’retransferring parts from the mini breadboard besure to double-check.

• Figure 5 shows interconnections between thesolderless breadboard and the Arduino.

(Feel free to use another wiring layout if youwish. Just be sure to observe correct polarity ofwiring, and take care that there is only oneground connection between the Arduino and thecomponents on the breadboard. Having multipleground connections can cause a ground loop anderratic behavior.)

See Figure 6 for component values and ageneral schematic wiring guide for the switch,photocell, and basic line following sensors. SeeParts 4 and 6 of this article series for additionalguidance. Figures 7 and 8 show the wiring forthe ultrasonic and Sharp infrared sensors. I’musing a Devantech SRF05 ultrasonic sensor formeasuring distance, and a Sharp GP2D120 analogoutput infrared sensor for detecting proximity. Note thereorientation of the wiring to the Sharp sensor. This wiringfollows accepted practice of placing the 5V wire in the middle.Many third-party cables designed to interface with the SharpIR sensors use this wiring scheme (but check to be sure!).

Note: I’m using a revised connection scheme for theSharp unit. In Part 5, I discussed how to use a transistor toselectively switch the Sharp sensor on and off. I’ve since

determined this is counterproductive and adds more codeoverhead. So, you’re advised to wire the power connectionsto the sensor directly as shown.

www.servomagazine.com/index.php?/magazine/article/may2011_McComb

FIGURE 3. Breadboardview for wiring the servos.

SERVO 05.2011 49

FIGURE 4.Breadboard view for

wiring the various sensors to the ArdBot.

FIGURE 6. Schematic diagram for wiring the CdSphotocells, contact switches, and line followingemitter/detector pairs. You need two of each.

FIGURE 5.Breadboard view of

connecting to the Arduino port pins.

Page 57: Robot With Arduino

50 SERVO 05.2011

Figure 9 is the wiring guide for the optional PololuQTR-8RC array, used as an alternative to the basic two-sensor line following optics. While the array contains eightseparate infrared emitters and detectors, only five are usedon the ArdBot (lack of available pins). The pin-outs areshown on the diagram. The wiring can go directly into theArduino’s digital port connectors.

Both forms of line following sensors are shown in Figure 10,mounted on the underside of the ArdBot. For your reference,Figure 11 shows the pin assignments for all the componentsconnected to the Arduino. Digital pin D13 is left free, allowinguse for the Arduino’s built-in LED. The serial transmit andreceive pins (D0 and D1) are likewise kept free.

Powering the ArdBot

Thanks to its three servos and its complement ofsensors, the ArdBot consumes a hefty amount of current.The servos operate from their own separate supply. For theservos, you can use a four-cell AA holder, with rechargeable

or non-rechargeable batteries. Note: Be ABSOLUTELY sure not to reverse the power

and ground connections, or your servos will be INSTANTLYRUINED! As described in Part 2, the four-pin headerconnector on the breadboard is polarized to help preventplugging the batteries in backward. The connector ispolarized using the old broken-pin-in-the-middle trick.

The completed ArdBot contains numerous sensors thattogether draw over a 100 milliamps. The Arduino providesregulated five volts to these parts, so you’ll want to poweryour Arduino from a set of AA or AAA cells, rather thanthe traditional nine volt battery. Use a six-cell holder orpack. Voltage with non-rechargeable cells is nine volts; it’s7.2 volts for rechargeables. Observe that the ground fromthe servo battery pack is electrically connected to theArduino’s Gnd path. This is by design, and is necessary toensure proper operation of the Arduino and the servos.Without this common ground connection, the servos maynot operate or they may behave erratically.

Programming the ArdBot

Listing 1 contains a full Arduino sketch fordemonstrating the combination of hardware applied on theArdBot. This is available in the downloads for this article.The sketch has two operating modes: Explore and LineFollow. The mode is set using a jumper block between themiddle/left or middle/right pins of the Mode Select header(see Figure 12). Analog pin A2 is used as a digital input toread the mode setting.

FIGURE 7. Wiringdiagram for the SharpGP2D120 infraredproximity sensor andthe Devantech SRF05ultrasonic sensor. FIGURE 8. Schematic view of connecting the Sharp GP2D120

to the Arduino.

FIGURE 9. Wiring diagram for the Pololu QTR-8RC linefollowing array module to the Arduino. Find convenientconnection points for the 5V and Gnd wires.

FIGURE 10. Theunderside of the ArdBot

showing both the two-sensor and array

module; both are usedfor line following.

Page 58: Robot With Arduino

• When brought LOW (grounded), the mode is setto Explore.

• When brought HIGH, the mode is set to Line Follow.

Let’s dissect the sketch and discuss its mostimportant parts. In the declarations area at the topof the sketch are references to three libraries:

#include <Servo.h>#include <PololuQTRSensors.h>#include <MsTimer2.h>

The Servo library comes with the Arduino IDE,but the other two require separate downloads. ThePololuQTRSensors library is available from the Pololu.com site (see Part 6 for details) and the MsTimer2 libraryis available from the Arduino page (arduino.cc/en/Reference/Libraries). Look under the Timing section.

As a reminder, follow these steps to add acustom library to the Arduino IDE:

1. Quit the IDE if it’s running.2. Locate the folder containing your Arduino

sketches. On a Windows machine, for example,this is typically My Documents\Arduino.

3. Create a libraries folder if one doesn’t already exist.4. Unpack and place the library within the libraries folder.5. Restart the Arduino IDE. The added library should be

visible in the Sketch->Import Library menu.

The remaining lines in the declaration area aredefinitions for objects, constants, and variables usedelsewhere in the sketch. For example,

Servo servoLeft;

creates a new Servo object called servoLeft. (See Parts 1and 3 for much more on working with Servo objects.)

The required setup() function attaches the three servosto Arduino digital pins, specifically D8, D9, and D10.Depending on the setting of the Mode Select header, thesetup() function then either readies the ArdBot to follow aline (digitalRead(A2) == HIGH) or to explore.

The required loop() function branches off to either oftwo methods: mode_line_follow or mode_explore,depending on the setting of the Mode Select header.

ArdBot Explore Mode

When in the Explore mode, the ArdBot wanders abouta room, trying its best to stay out of trouble. It follows thisroutine, over and over again:

1. The robot moves forward for a predetermined period oftime while monitoring its ultrasonic distance sensor forobjects immediately ahead. If there’s an obstacle, the botslows down, then briefly backs up, turns, and heads offin a new direction.

2. While keeping a lookout for objects straight ahead, theArdBot also checks the condition of its two CdSphotocells. If both cells are exposed to bright light, theArdBot responds by doing a scared side-to-side shimmy

dance before heading in a new direction.3. Every 10 seconds a special timer (provided by the MsTimer2

library) makes the ArdBot momentarily stop and check forwalls or obstacles to the immediate left or right. If there’san object close by, the bot briefly steers in the oppositedirection to get away from it. The MsTimer2 librarydemonstrates using one of the timers in the Arduino totrigger a hardware interrupt. More about it in a bit.

4. As an extra precaution, the ArdBot’s two front bumperswitches are rigged to the Arduino’s external interrupt ports,pins D2 and D3. If either or both of these ports are triggered(brought from LOW to HIGH), the sketch is interrupted.The ArdBot is commanded to steer in the oppositedirection of the obstacle. An object that triggers the leftbumper makes the robot turn to the right, and vice versa.

Note that the Explore routine demonstrates just one ofthousands of combinations you can develop using the motorsand sensors on the ArdBot. Remember, that’s the beauty ofworking with code: You can “rewire” your robot just bychanging some programming lines. You’re encouraged toexperiment and try different things. As an aside, Figure 13

SERVO 05.2011 51

FIGURE 11.Overview of the

Arduino port pinsused with the fully

featured ArdBot.

FIGURE 12. Use the Mode Select jumper to set the operatingmode of the ArdBot to either explore a room or follow a line.

Page 59: Robot With Arduino

52 SERVO 05.2011

shows a method of attaching a 1/16” brass rod (availableat hobby stores; K&S Metals stock #1626) to increase thesurface area of the bumper switches. The rod is attached tothe leafs of the switches using cable ties and hot melt glue.

This approach makes the switches more sensitive tocontact on either side of the robot, but decreases sensitivity(due to the springy nature of the metal) to bumps directlyin the middle. Feel free to experiment with different frontbumper designs, including cutting 1/8” out of the middleof the rod and reinforcing the bridge with a rubber tube.

Using the MsTimer2 Interrupt

The MsTimer2 library is a convenient method foradding a timed event to the Arduino. (There are manyalternative libraries available; I picked MsTimer2 because it’sreadily accessible from the Arduino website and is verysimple to use.) Under the hood, MsTimer2 uses theArduino’s eight-bit Timer2 hardware timer. This timer is ashared resource. It’s available for use in your sketches aslong as another library or function isn’t already occupyingit. Apart from the Servo library — which depends on othertimer hardware — the timers on the Arduino are used forPWM (analogWrite) functionality. As the ArdBot doesn’t usePWM for anything, this means Timer2 is free and clear.

To use MsTimer2, you need only to add its #includereference at the top of the sketch and two lines of code inthe setup() function:

MsTimer2::set(10000, turret_scan);MsTimer2::start();

(Note the :: double colons. This is standard C++ syntax.)The first line sets up the timer to trigger every 10,000milliseconds (ms), or once every 10 seconds. The turret_scanreference indicates which function is called when the timerdings. The second line starts the timer running. Unless youuse the MsTimer2::stop method (which we don’t), the timerautomatically resets itself, and triggers every 10 seconds.

When the timer is triggered, it simply sets a valuecontained in the turret_scan function (mstimer = true). The nexttime the Arduino goes through its loop (which it does manytimes each second), the sketch checks the value of mstimer. Ifthe value is true, the robot stops and scans its sensor turret rightand left. The ultrasonic and infrared sensors are on this turret.

(During this scan, only the IR sensor is read. This is

simply an arbitrary design choice made to keep the lengthof the code listing reasonably short. In your ArdBot, you’refree — and encouraged — to use both the IR and ultrasonicsensors as a means of double-checking the validity of thevalues from the two sensors. It’s always a good idea to get asecond opinion!) The timer trigger is ignored (more accuratelynot immediately acted upon) at various points in the sketch.This is to prevent the turret scan from occurring when itshouldn’t. This is accomplished using the turret_enablevariable. If this variable is set to true, the turret action isenabled. If false, it’s skipped for that iteration of the loop.

Responding to Bright Light

Purely as a fun diversion, the ArdBot is set to avoid brightlight directly ahead. When the light falling on its two variableresistor (CdS) photocells exceeds a set threshold, the robotshakes back and forth a few times, then hightails it in a differentdirection. This added routine is there to make things moreinteresting, and to provide you with another means toexternally influence the behavior of the ArdBot. Recall fromPart 4 that CdS photocells are variable resistors. They areconnected to the Arduino using a second fixed resistorwhich turns their output into a varying voltage. The brighterthe light, the higher the voltage. This voltage is read by twoof the Arduino’s analog-to-digital converter (ADC) inputs;specifically pins A0 and A1. The voltage is converted to a10-bit binary value, ranging from zero to 1023.

Also recall from Part 4 that different photocells canhave markedly different output characteristics. Selection ofthe fixed resistor requires some experimentation (I like tomake it about the same resistance as the photocell whenexposed to normal room light). Likewise, the resultingvoltage output can differ. You can compensate for thesevariations with the line:

#define BRIGHT 800

which here stipulates that a bright light is anything that causesthe ADC to read 800 or higher. If your CdS cells are more sensitive,try an even higher value; if less sensitive, try a lower value.

Reading the Ultrasonicand Infrared Sensors

The ArdBot uses both ultrasonic and Sharp infrared sensorsto measure distance and proximity. While both sensors cantechnically be applied to either job, on the ArdBot theultrasonic sensor is used for measuring distance, while theinfrared sensor is used to determine close proximity.

The sketch uses separate functions for reading theultrasonic and IR sensors, though they both operate in asimilar fashion. Each time the function is called (sonarRead()for the ultrasonic sensor; irRead() for the infrared sensor),its value is retrieved five times. The five separate readingsare then averaged out, to help avoid spurious results.

In the case of the Sharp IR sensor, each read is separated by50 milliseconds. This represents the worst-case delay of theinternal samples taken by the sensor (which, according to thedatasheet, is about 38 ms, ± 10 ms). The delay is required sothat each reading is from a different sample taken by the sensor.

FIGURE 13. Here’s one method of creating a front bumper forthe ArdBot. The bumper is made with 1/16” brass rod, glued(using hot glue) to the leafs of the switches.

Page 60: Robot With Arduino

The Devantech SRF05 sensor doesn’t require so much timebetween each reading. Its time delay is set at just one millisecond.

Note that readings from the ultrasonic and IR sensorsare not taken while the turret servo is in motion. The servois commanded to a new position and stops to take thereading. This is to help reduce measurement errors.

Likewise, the ultrasonic sensor is not read when therobot is turning. Lateral motion while taking an ultrasonicmeasurement can result in wild inaccuracies, though thisgreatly depends on the specific sensor you’re using. Youget the best results when the robot is still or moving at areasonable speed forward or backward.

As noted above, the ultrasonic sensor continually “pings”for objects straight ahead while the robot is travelingforward. If an object is detected to within three inches, theservos are slowed down (by adjusting their values close tocenter, which is a value of 90). If an object is detected towithin an inch, the robot stops, backs up, spins for half asecond to reorient itself, and then continues forward again.

Adjusting Timing Delays

The sketch relies heavily on delays to steer the robot, andto position the turret servo before taking a sensor reading. Forthe purpose of programming, the length of these delays isdetermined empirically. The delay values are based on the speedof the servos when operated from a fresh battery supply. Someservo motors are particularly fast; some are downright sluggish.

Bear in mind that servo motors slow down as thebattery voltage decreases. A one second delay when thebatteries are fresh might turn the robot one complete circle.But when the batteries are about dead, the same onesecond delay might turn the robot only half way.

In the ArdBot, most timing delays are set directly incode. An exception is the T_DELAY value, specified in thedeclaration area of the sketch. This value determines thedelay used when rotating the sensor turret. The delay mustbe long enough to transit the servo from one extreme tothe other, plus the time it takes to read the IR sensor(which is about 270 ms for all five samples).

You should strive to set delays based on average speeds.The ArdBot as presented lacks sensors for true navigation(compass, gyro, and wheel encoders for odometry), so the motionroutines are intended only to demonstrate basic maneuverability.In a more elaborate ArdBot setup, you could use wheel encodersand/or a compass to more precisely determine how far therobot has turned. (It’s best to use both, if you can; wheels slip,resulting in errors in the wheel encoders. The compass is usedto reorient the position of the robot to a known reference.)You may also wish to explore ways to avoid using delays, as thedelay() statement literally stops the sketch until the specifiedtime period has elapsed. The MsTimer2 library is a goodexample of using other techniques to time events. A numberof ready-made libraries provide this kind of functionality,and allow you to easily create multiple timing objects.

As an example, try Metro, also available from theArduino Libraries page. Metro allows you to create multipletiming objects, with each object set to “expire” after acertain length of time. With some crafty coding, you couldreplace most or all the delay() statements in the sketch with

Metro timers, allowing the program to be more multi-tasking and responsive to sensor events.

ArdBot Line Following Mode

When the Mode Select header is placed so that pin A2is brought HIGH, upon startup the ArdBot is put into linefollowing mode. As described in Part 6, I’ve provided twovariations of line following sensors:

1. Basic two-sensor detector, using a pair of infraredemitters/detectors side by side. The two detectors are meantto straddle the 3/4” line of a length of black electrical tape. Usethe mode_line_follow method with the two-sensor detector.The sketch assumes the detectors are wired as shown in thefigures, and are connected to Arduino pins A3 and A4.

2. Enhanced multi-sensor array, using (in this case) aPololu QTR-8RC eight-detector array. These units are verycompact and cost less than when purchasing separateready-made infrared emitter/detector modules. Use themode_line_follow_array method with the QTR-8RC. The ArdBotuses five of the eight available emitters/detectors, and theseare connected to digital pins D4, D5, D6, D11, and D12.

Listing 1 includes the code for both line followingvariations. When using an array — like the QTR-8RC — it isalso possible to detect a “finish line” in the line followingcourse. See the ArdBot Construction Notes site (check theSources box) for more information.

For More Arduino Coverage

Though this is the final article in this series, there isplenty more to share about combining the Arduinomicrocontroller with robots. After all, there’s so much moreto talk about. So, stay tuned! Be sure to check out theArdBot Project updates, free code, and additional examplesat www.robotoid.com/servomag/. SV

If you’d like to build theArdBot, be sure to start withthe November ‘10 issue ofSERVO Magazine for Part 1 ofthis series. Also check out thefollowing sources for parts:

Prefabricated ArdBot bodypieces with all constructionhardware:

Sensor Turret Budget Roboticswww.budgetrobotics.com

ArdBot Construction Notes:Downloadable code, updates,additional sketches, andexamples. www.robotoid.com/servomag

Arduino Resources:

Arduinowww.arduino.cc

Fritzingwww.fritzing.org

Online Retailers of Arduino,

infrared sensors for linefollowing, and components:

AdaFruit Industrieswww.adafruit.com

All Electronicswww.allelectronics.com

Digi-Keywww.digikey.com

Jamecowww.jameco.com

Lynxmotionwww.lynxmotion.com

Parallaxwww.parallax.com

Pololu Robotics & Electronicswww.pololu.com

RobotShopwww.robotshop.com

SparkFunwww.sparkfun.com

Sources

SERVO 05.2011 53