Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14...

11
ROBOTICS An Environment-Sensing System for Mobile Robots A Serial Network Hub for an Animatronics System Directional Light Sensor Design: Phase 2 Use RFID Technology to Control Apps Build a Calibrated Decibel Meter CIRCUIT CELLAR www.circuitcellar.com THE MAGAZINE FOR COMPUTER APPLICATIONS $5.95 U.S. ($6.95 Canada) #236 March 2010 Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle-Solving Programs, p. 62 • Embedded Design Security, p. 68

Transcript of Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14...

Page 1: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

ROBOTICSAn Environment-Sensing System for Mobile Robots

A Serial Network Hub for an Animatronics System

Directional Light Sensor Design: Phase 2

Use RFID Technology to Control Apps

Build a Calibrated Decibel Meter

CIRCUIT CELLAR

www.circuitcellar.com

T H E M A G A Z I N E F O R C O M P U T E R A P P L I C AT I O N S

Cover - 236.qxp 2/11/2010 10:18 AM Page 1

$5.95 U.S. ($6.95 Canada)

#236 March 2010

Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle-Solving Programs, p. 62 • Embedded Design Security, p. 68

Page 2: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

FOUNDER/EDITORIAL DIRECTORSteve Ciarcia

EDITOR-IN-CHIEFC. J. Abate

WEST COAST EDITORTom Cantrell

CONTRIBUTING EDITORSJeff Bachiochi Robert LacosteGeorge MartinEd Nisley

NEW PRODUCTS EDITORJohn Gorsky

PROJECT EDITORSGary BodleyKen Davidson David Tweed

ADVERTISING800.454.3741 • 978.281.7708 • www.circuitcellar.com/advertise

ADVERTISING REPRESENTATIVEPeter Wostrel Strategic Media Marketing, Inc.2 Main St., Gloucester, MA 01930 USA800.454.3741 • [email protected] • www.smmarketing.usFax: 978.281.7706

ADVERTISING COORDINATORValerie LusterE-mail: [email protected]

CONTACTSSUBSCRIPTIONS

Information: www.circuitcellar.com/subscribe, E-mail: [email protected]: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650Address Changes/Problems: E-mail: [email protected]

GENERAL INFORMATION860.875.2199, Fax: 860.871.0411, E-mail: [email protected] Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected]

AUTHORIZED REPRINTS INFORMATION860.875.2199, E-mail: [email protected]

AUTHORSAuthors’ e-mail addresses (when available) are included at the end of each article.

CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit CellarIncorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues)subscription rate USA and possessions $29.95, Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub-scription rate USA and possessions $49.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable inU.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription ordersand subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call800.269.6301.

Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for theconsequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read-er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon orfrom plans, descriptions, or information published by Circuit Cellar®.

The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right tobuild things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right toconstruct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction.The reader assumes any risk of infringement liability for constructing or operating such devices.

Entire contents copyright © 2010 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc.Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

PUBLISHERHugo Vanhaecke

ASSOCIATE PUBLISHERShannon Barraclough

CUSTOMER SERVICEDebbie Lavoie

CONTROLLERJeff Yanco

ART DIRECTORKC Prescott

GRAPHIC DESIGNERSGrace Chen

Carey Penney

STAFF ENGINEER John Gorsky

Cover photography by Chris Rakoczy—Rakoczy Photographywww.rakoczyphoto.com

PRINTED IN THE UNITED STATES

Our editorial mission is to provide serious embeddeddesigners, programmers, and academics with essential “need-to-know” information that will enable them to stay on thecutting edge of technological development. The informationwe provide enables project engineers to bring new design con-cepts to their company’s design meetings, helps entrepreneursdeliver new MCU-based technologies to the market, and pre-pares programmers to write more efficient code. You mightnot want the same sensor system Guido Ottaviani describeson page 14, but you’ll take what you learn and apply it toinnovative projects of your own. You probably don’t need tobuild a replica of Brian Millier’s RFID-based liquid controlsystem for a nitrogen tank (p. 24). But if you understand whyand how he designed it, you’ll be a step ahead of engineerswho don’t have the knowledge to build a custom RFID con-trol system of their own.

The main point is simple: When reading a Circuit Cellararticle, it isn’t always the end product that matters. What’smost important is what happens from the time an idea ishatched to the time the project first powers up. You won’tfind our complex embedded design content in trade journalsand hobby magazines. Those publications won’t enable you todesign a truly novel application that will make you money.Nor will they give you the in-depth information you’ll needwhen your project manager says: “I need a solution to thisdesign problem. And it’s due ... yesterday.” Nor will anyhobby projects, once finished, move your resume to the top ofthe pile on a potential employer’s desk.

This month’s articles cover many of the complicated top-ics that you need to master in order move ahead and excel atyour workbench, at your job, or at your university: robotics,embedded security, audio output measurement, networking,RFID technology, MCU-based sensor system design, andmore. To learn about networking a complex animatronics sys-tem, turn to Peter Montgomery’s article on page 30, where heexplains why building a six-port RS-485 hub for a custom net-work packet system can simplify node wiring. On page 38,Marco Aiello describes how to design and program a “miniro-bot” along with a handy navigation system. If you’re an audioenthusiast, Larry Cicchinelli’s article on page 46 presents acalibrated decibel meter for measuring audio output levels.On page 54, Jeff Bachiochi describes the last phase of his suntracker design project, which involves time keeping and dis-playing data on the LCD. Turn to page 62 to learn how GeorgeMartin created a puzzle-solving program in C. Finally, checkout Tom Cantrell’s article on page 68 about notable advancesin embedded design security.

With all of this information packed into one issue, your“engineering quotient” is sure to rise. Absorbing need-to-know information is the best way to stay one step ahead ofthe pack.

Need-to-Know Info

[email protected]

4 CIRCUIT CELLAR® • www.circuitcellar.com

Mar

ch 2

010

– Iss

ue 2

36

TASKMANAGER CIRCUIT CELLAR®

THE MAGAZINE FOR COMPUTER APPLICATIONS

Task_Masthead_236.qxp 2/11/2010 10:20 AM Page 4

Page 3: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

6 CIRCUIT CELLAR® • www.circuitcellar.com

Mar

ch 2

010 –

Issue

236

INSIDE ISSUE

TASK MANAGER 4Need-to-Know Info

C. J. Abate

NEW PRODUCT NEWS 8edited by John Gorsky

TEST YOUR EQ 13

CROSSWORD 74

INDEX OF ADVERTISERS 79April Preview

PRIORITY INTERRUPT 80A Matter of History

Steve Ciarcia

54 FROM THE BENCHSun Tracker (Part 2)Power Up and Start TrackingJeff Bachiochi

62 LESSONS FROM THE TRENCHESPutting C Language to the Test (Part 1)A Sudoku Puzzle-Solving ProgramGeorge Martin

68 SILICON UPDATETales from the CryptoA Look at Embedded Design SecurityTom Cantrell

23614 A Sensor System for Robotics Applications

Guido Ottaviani

24 RFID-Based Liquid Control (Part 2)Monitoring System ImplementationBrian Millier

30 Serial Network Hub (Part 1)Network Topology and Design PlanningPeter Montgomery

38 Design and Program a “Minirobot”Marco Aiello

46 Calibrated Decibel Meter DesignLarry Cicchinelli

March 2010 • Robotics

Robot SensorSystem, p. 14

er6

Mobile RobotDesign, p. 38

SerialNetwork

Hub, p. 30

TOC_236.qxp 2/11/2010 10:20 AM Page 6

BONUS CONTENTThe Arduino-Based

"MiniEric" Robot

Page 4: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

14 CIRCUIT CELLAR® • www.circuitcellar.com

Mar

ch 2

010 –

Issue

236

hoto 1—My upgraded robotics platform features a new sensor sys-tem that enables obstacle avoidance and location recognition.

2103017_Ottaviani.qxp 2/11/2010 10:28 AM Page 14

If you’re developing an interactive robotics platform, you’ll have to incorporatea well-designed sensor system at some point. This article covers how to add“senses” to a robotics design, from sight to hearing to touch and more.

A Sensor System for RoboticsApplications

I

FEA

TURE

ARTICLEby Guido Ottaviani

n my 2009 article series titled “Robot Navigation and Control,” I explained how to build a navigation control

subsystem for an autonomous differential-steering exploringrobot called the “Rino” (Circuit Cellar 224 and 225). I cov-ered everything from the mechanical platform to the hard-ware and software used for guidance and system orientation.During the last several months, I upgraded the system with anew sensor system that enables obstacle avoidance and loca-tion recognition (see Photo 1). In this article, I’ll describe howI designed and implemented the sensor system. Read on tolearn how to add senses like sight, smell, and sound to yournext robotics application.

ARDU-RINOThe first step in the design process for the updated Rino

robot was selecting the right controller . With MicrochipTechnology PIC experience under my belt, I figured it wouldbe more exciting to try something else—so long as it would-n’t require too much programming effor t.

I knew an 8-bit MCU was more than enough to drive thesensors normally used in amateur robotics, because sensorsI’d usually used had a response time measured in ter ms ofseveral milliseconds or more. While developing the remoteconsole that I described in my 2009 ar ticles, I learned a lotabout the Arduino hardware and software platfor m. It’s inex-pensive and powerful. (And it’s developed in Italy. I’m a bitpatriotic.) The best thing is that Arduino is growing in popu-larity all over the world. It’s completely open-source, so it’seasy to find any kind of hardware inter face or softwarelibrary you need. You have the option to use an off-the-shelfpiece of software or build your own librar y using C program-ming and even controlling every single bit of the included

Atmel microcontroller. For all of these reasons, I chose to usean Arduino Diecimila board—and so the “ArduRino” wasborn (see Photo 2).

The Arduino’s specifications include the way the expan-sion boards must be implemented. They are called“shields.”[1] But I didn’t follow the standard. I used a per fboardto build my own version of a shield (see Photo 3). The sock-ets on the perfboard are for interfacing the Arduino with the

PPhhoottoo 11——My upgraded robotics platform features a new sensor sys-tem that enables obstacle avoidance and location recognition.

Page 5: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

www.circuitcellar.com • CIRCUIT CELLAR® 15

Mar

ch 2

010 –

Issue

236

with just few lines of code. [2]

Sample code to control theMAX127 is also availableonline. A couple of lowdropout voltage regulators onthe board supply the Arduinoand Figaro TGS822 gas sen-sors (see Figure 1). A compo-nent layout of the shield isposted on the Circuit CellarFTP site.

SMELLA gas source (e.g., slowly

evaporating alcohol) is a fre-quently used “target” inmany robotics competitions.The TGS822 gas sensor has high sensi-tivity to organic solvent vapors such asethanol (see Photo 4). It includes a semi-conductor element that, in presence ofdetectable gas, increases its conductivityin proportion to the gas concentration inthe air. The sensor works linearly onlyat a specific temperature. To obtain that,

rest of the components and boards.Among them are some signaling LEDs,switches, and a Maxim MAX127 dataacquisition system (i.e., eight analog-to-digital channels with an I2C interface).This is also useful for expandingArduino analog ports for future applica-tions. With the “Wire” library forArduino, it’s easy to use the I 2C bus

the sensor contains a heater that warmsup the semiconductor. This heater isthe most power-consuming part of theentire sensor. For this reason, a dedicat-ed voltage regulator is used on the sen-sor board. It requires some time afterpower-up to begin working linearly.

On the board in the lower part ofthe platform are two gassensors to increase the rangeof detection (see Figure 2).The signals from the sensorsare mixed in one outputonly with two diodes andconnected to an ADC inputon the MAX127 IC.

The highest voltage levelbetween the two sensorsbreaks the diodes’ thresholdand goes to the A/D por t. Infact, we don’t need to knowwhich sensor is involved inmeasuring. This configura-tion saves one port of theconverter. When the levelcrosses a certain threshold,the robot stops and illumi-nates a red LED to showthat the goal is reached.

SIGHTProviding a robot with the

sense of sight enables it toavoid obstacles and detecttargets. Different technolo-gies (e.g., as ultrasonic sight,infrared, and visible light)provide you with differentobject-detection options (seePhoto 5). Each technologyhas its pros and cons.

Figure 1—The board is based on an Ar duino. Thus, most of the circuits serve to connect and adapt vari-ous sensors to the Arduino’s ports. The only active component is the MAX127 A/D-to-I 2C expander.

Photo 2—This is my robot’s sensor boardwith most of the necessary devices installed.

Photo 3—I have my own version of a shield for theArduino.

2103017_Ottaviani.qxp 2/11/2010 10:28 AM Page 15

Page 6: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

16

Mar

ch 2

010 –

Issue

236

Ultrasonic sight is what bats use tosee. It involves waiting for the echo ofultrasonic waves reflected by objects.My design features three DevantechSRF08 ultrasonic range finders thatare driven through the I 2C bus (seePhoto 6a). With a protocol similar to theone used to read and write a 24CL xxxEEPROM, they can be programmed andread.

Using ultrasonic waves at 40 kHzwith a good range of measurement isachieved, but with a large beam width.This is useful for detecting obstacleswith a limited number of sensors, butnot to map the object in its exact coor-dinates. Something better can beobtained with 200-kHz ultrasonic sen-sors, but at a higher price. There areseveral different mathematical and sta-tistical methods for decreasing uncer-tainty, such as the virtual force field(VFF) method and the vector field his-togram (VFH) method. (For moredetails, refer to the documents andwebsite listed in the Resources sectionat the end of this article.)

For infrared sight, Iused three SharpGP2D120 analog dis-tance-measuring sensors(see Photo 6b). This kindof sensor uses an array ofreceivers to compute theangle of the infraredbeam after the reflectionon the object. The inter-nal circuit returns a volt-age proportional to thedistance with a transferfunction specified in thedatasheet. They arecheaper and smaller than

ultrasonic sensors, but the meas-uring range is limited. For thisreason, there are different mod-els for different ranges. The GP2D120 isthe best option for this applicationbecause it starts from 4 cm, whichenables the robot to detect nearbyobjects. This is fine for mapping theobjects with precision, but there is arisk of missing thin obstacles. It workswell with mat surfaces. But shiny orglossy objects can be problematicbecause the IR beam can be reflectedaway from the sensor. For instance, Ihave a cylindrical umbrella stand in myhouse that’s similar to a large metalliccan. The robot can’t avoid it with onlythe IR sensors. Furthermore, IR sensorscan go blind or return false measure-ments if an intense light (even in visi-ble range) hits them directly. The ana-log output of the sensors is readthrough three ports on the MAX127ADC to I2C chip. I can use the samebus used for SRF08 sensors.

Another target in many explorerrobot competitions is a light source.

The goal is for the robot to detect thelight source, stop a predetermined dis-tance from the light, and then illumi-nate a green LED. To do this, the robotmust measure the distance from theobject and detect the light. When thelight intensity breaks a predeterminedthreshold and the distance is less than20 cm, the robot initiates its “job done”procedure.

Note that a CDS photoresistor isalready installed on the SRF08 module.It can measure the ambient light inten-sity and put the value in a registerthat’s readable through the I2C bus inthe same fashion as distance values.

TOUCHThe bumpers I added to the design are

intended to detect objects that come intocontact with the robot (see Photo 7a).They are useful particularly if the othersensors fail or if an object can’t bedetected for some reason.

Photo 5—Most of the sensors—range finders, IR dis-tance measuring sensors, mechanical bumpers, andCDS photoresistors—are located in the front. All ofthem are replicated on three sides with an angle of45° to expand the system’s range of sight.

Photo 4—Figaro TGS822 gas sensors are installedon the bottom of the robot.

Photo 6a—The SRF08 module contains a complete circuit that handles the procedures for measuring distances between 3-cm and 6-m withultrasonic waves. b—The GP2D120 infrared module can accurately measure objects from 4 to 30 cm.

a) b)

2103017_Ottaviani.qxp 2/11/2010 10:28 AM Page 16

Page 7: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

18 CIRCUIT CELLAR® • www.circuitcellar.com

Mar

ch 2

010 –

Issue

236

The bumpers are based on fork-shapedphoto-interrupters (see Photo 7b). Whenthe lower part of the bumper touchesthe object, the top part rises and allowsthe IR light beam to reach the photo-transistor and close the circuit. It needsjust a little touch to move the bar rierenough to close the circuit. After that,the bumper can still move back a fewcentimeters so the robot can smoothly

decrease its speed to zero withoutblocking the motor.

SOUNDSounds are also common targets in

robotics competitions. For instance,let’s say a speaker in one of the course’ sboxes emits a 4-kHz tone. Once sound-ed, the robot must sense the sound,stop close to the box emitting the

sound, and illuminate a yellowLED.

A simple method for recogniz-ing a tone is to use microphonesto receive the sound, amplify it,and then filter it. You can use atone decoder to trigger the con-troller when the signal exceedsthe threshold. This requires therobot to travel randomly until itcomes close to a speaker.

A more sophisticated sound-detection method uses an “elec-tronic ear” to detect the direc-tion from which the sound origi-nates. The setup requires a cou-ple of microphones at a distanceof one wavelength (about 8 cm)to each other. You then mustperform some math withMicrochip dsPIC DSP librariesto measure the phase differencebetween the two signals. Butthis method is beyond thescope of this article.

I’ll focus on the “simple”solution. I used it for one of myprevious robots, which had somesuccess in robotics competi-tions. It isn’t easy to detect asingle tone in a noisy environ-ment (with most of the noisebeing generated by the robotitself). You can use two Texas

Instruments OPA2244 double op-amps,a single quad op-amp chip, or some-thing else with similar features.

Refer to the complete schematic inFigure 3. Let’s start with the virtualground section. The first difficulty isthe power supply. Usually, you have asingle 5-V power supply for yourrobot. To have an output signal levelswing wide enough to avoid spuriouswaves generated by signal clipping, youneed at least a quasi rail-to-rail op-amp.Fortunately, many modern op-ampscan work with a single power supplyand an output swing from ground toVCC – 1 V, allowing an output signalof 1.4 V

RMS with a 5-V power supply.Using a single power supply, you needto create a “virtual ground,” offsettingthe input and output signals to half ofthe power supply. There are some dif-ferent techniques to do this. Many elec-tronics books cover the topic. A goodreference is also Bruce Carter’s applica-tion note titled “A Single Supply OpAmp Circuit Collection” (Texas Instru-ments, 2000).

With a multiple-stage amplifier, thebest solution is to dedicate one sectionof the chip to obtain a single low-impedance virtual ground circuit for allof the stages. The resistors and capaci-tors needed to obtain a filtered refer-ence are only connected to this op-amp.The output can be used as the signalground for all of the other stages.

Refer to the mixer section in Figure 3.To catch the sound from every direc-tion, three Electret microphones aremounted in three different directions.In this stage, the signals are mixed andslightly amplified. Each stage has a lit-tle gain, getting an overall gain factor of250. In this way, you get all the gainneeded to drive the tone decoder at theright level, with the best characteristicsin terms of stability and input imped-ance for each stage. The decouplingcapacitors, together with input resis-tors, have a first 3-kHz high-pass filtereffect that cuts off most of the noise.

Experience has taught me the impor-tance of the decoupling filter formed byR36, C33, C34, C35, and C36. It filtersthe power supply for the active micro-phones. The NE567 has an internal oscil-lator to act as a PLL (see descriptionbelow). This oscillator works at the same

Figure 2—The lower board includes the opticalswitches for the bumpers and some components forsignal conditioning.

Photo 7a—The bumpers on the front of the robotcan detect small and low objects that the othersensors can’t pick up. b—This fork-shaped photo-interrupter can detect the bumper ’s movement.

a) b)

2103017_Ottaviani.qxp 2/11/2010 10:28 AM Page 18

Page 8: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

20 CIRCUIT CELLAR® • www.circuitcellar.com

Mar

ch 2

010 –

Issue

236

frequency we want to reveal (4 kHz) . Inthe power supply line, there is thereforesome 4-kHz noise coming from the

NE567. Due to the high gain of theamplifier chain, the power supply ofthe microphones (the input of the

chain) has to be well filtered to avoidundesirable behaviors.

Now refer to the band-pass filter sec-tion in Figure 3. After mixing and afirst amplification, the signal goes tothe band-pass section that filters outall the unwanted signals. This stagehas a gain factor of five in 4-kHz cen-tral frequency with an 8% bandwidth(320 Hz). Once again, there are a lot ofprograms online that can do the entirejob of finding the right values for resistorsand capacitors (e.g., Captain’s Universe,www.captain.at/electronics/active-filter/).Using a variable resistor for R17, you canaccurately trim the central frequency.

Note that the 4-kHz signal alonegoes to the final stage that amplifies itfor another gain factor up to 14. Thisstage adjusts the sensitivity of thecomplete system. The regulation trim-mer is at the input of the stage toavoid saturation.

Refer to the tone decoder section ofFigure 3. The correct signal level is sentto the input of the tone decoder . This isa classic application of the PhilipsSemiconductors tone decoder/phase-locked loop (PLL) NE567. When thefrequency of the input signal is thesame as the internal NE567 oscillator,the PLL locks and sets the digital out-put pin low. The internal Voltage

Figure 3—This three-chip board, usedto detect the 4-kHz tone generated bythe sound target, could be logicallydivided into five sections, each onewith its precise purpose in the decod-ing process (as noted by the numbersin this figure and detailed in the text).To increase this circuit’s performance,the board’s overall gain is obtained witha small amount of gain for each stage,as noted with the “G” parameter in thediagram.

2103017_Ottaviani.qxp 2/11/2010 10:28 AM Page 20

Page 9: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

www.circuitcellar.com • CIRCUIT CELLAR® 21

Mar

ch 2

010 –

Issue

236

Controlled Oscillator (VCO) fre-quency depends on some externalcomponents. The primary functionof this component is to drive a loadwhenever a sustained signal withinits detection band is present at theinput. The bandwidth, center fre-quency, and output delay are inde-pendently determined by means offour external components. The val-ues of these components can becalculated with the formulas in thedatasheet or with a program (e.g.,NE567.bas at http://web.tiscali.it/i2viu/electronic/electron.htm). Eventually,the output of NE567 becomes a digitalsignal that can be connected to an inputport on the microcontroller so you canknow when the sound target is revealed(see Photo 8).

DIRECTIONA roboticist wants the ability to track

a robot’s location and direction ofmovement. But designing such a sys-tem is not so easy. In my 2009 articles,I described a method to estimate posi-tion without any external reference byodometry—meaning, by reading the dis-tance traveled by each wheel. As Idetailed in my 2009 article, this proce-dure could also be very precise whenusing high-resolution encoders andwheels with a small contact area withthe floor. But, even with a smallamount of error for each turn, the preci-sion decreases proportionally with thespace traveled since the error is cumu-lative. This increases the uncertaintycircle after several dozens of meters,especially with an irregular floor, wherewheel slipping and jumping can occur.

To increase dead-reckoning precision,many kinds of “sensor fusion” methodsare experimented with. Gyrodometry isa sophisticated method.[3] This uses acombination of sensors that requiressome computation capabilities for boththe microcontroller and the program-mer who writes the code.

Knowing the absolute orientationmay be useful to partially compensatefor the errors caused by odometry. Asimple and affordable way to measurebearing is with a digital compass. Thiskind of sensor is popular because it iseasy to find and inexpensive. Plus, youcan find a lot of code examples on the

Internet in every programming lan-guage.

The popular Devantech CMPS03electronic compass can be interfaced indifferent ways. I chose I2C interfacing.This method makes it easier to drivethe compass for various purposes. Thebearing value can be read in a 2-bytevariable with a theoretical resolution of0.1° (from 0 to 3,599, meaning 359.9°),which is much higher than the real pre-cision. The calibration procedure can bestarted with a specific command, evenwith an automatic sequence that tur ns

the robot 90° and performs a meas-ure, then turns another 90° step andperforms another measure, and soon, for each cardinal point untilreaching 360°. As described in themanual, calibration is importantand must be performed at least onceafter installation for the purpose ofprecision. It compensates for somestatic magnetic fields, and it cor-rects the inclination reading. Mag-netic field inclination variesthroughout the world.

To correctly use the valuesreturned by the compass, keep in mindthat this electronic device uses exactlythe same physics as a regular magneticneedle compass, with all the pros andcons. The compass must be kept paral-lel to the floor to avoid reading the ver-tical axis of the Earth’s magnetic field.Some digital compasses are tilt-com-pensated with a three-axis magneticsensor and a three-axis accelerometer toavoid this effect in a given range (sor t ofan electronic version of the gimbals usedon shipboard compasses), but they aremore expensive. The compass is affected

Photo 8—This is a prototype of the sound boar d onperfboard.

www.keil.com 1-800-348-8051

Leading Embedded Development Tools...

Easy to use, from concept to final productMDK-ARM is an Integrated Development Environment forARM and Cortex™-M microcontrollersRL-ARM is a Library Collection designed to solve real-time

and communication challenges ULINKpro is a high-speed Debug and Trace unit for detailed

analysis of software quality

2103017_Ottaviani.qxp 2/11/2010 10:41 AM Page 21

Page 10: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

22 CIRCUIT CELLAR® • www.circuitcellar.com

Mar

ch 2

010 –

Issue

236

by surrounding magnetic fieldsthat are often much strongerthan the Earth’s magnetic field(e.g., iron objects, magnets, andelectricity).

SOFTWARE & SETTINGSThe software runs on an

Arduino Diecimila board. Allthe sensors except the bumpersare interfaced on the I2C busdirectly or through a MAX127converter. The battery voltage ismonitored with an A/D port todetermine when a power short-age is coming. Thanks to theWire libraries, the software is very sim-ple, and it’s just a matter of cyclicallypolling each sensor with the right timing .

Because the SRF08 sensors come withthe same address, the first setting mustassign a different I2C address to eachone. It is needed just once to change thedefault address E0. Thus, you must haveonly one sonar on the bus at a time.When powering up the SRF08 withoutsending any commands, it will flash itsaddress on the LED—one long flash fol-lowed by a number of shorter flashes,indicating its address from 0 to 15. Theflashing is terminated immediately bysending a command.

Other sensor settings are not perma-nent, so they must be applied at everystartup. Thus, before the main cyclestarts, the analog gain and measuringrange must be configured on the SRF08.The analog gain register sets the maxi-mum gain of the analog stages. To set it,just write the value to the gain registerat location 1.

During the ranging process, the ana-log gain starts off at its minimum valueof 94. This is increased in approximate-ly 70-µs intervals up to the maximumgain setting, set by register 1. The maxi-mum possible gain is reached afterabout 390 mm. Providing a maximumgain limit enables you to fire the sonarmore rapidly than 65 ms. Since the rang-ing process can be very short, a newranging process can be initiated as soonas the previous range data has been read.A potential hazard with this is that thesecond ranging process may pick up adistant echo from the previous “ping,”which could create a false result. Toreduce this possibility, the maximum

As I already mentioned, thedigital compass must be cali-brated for the local inclination.But this procedure is needed justonce, and it is not par t of therunning software.

CYCLINGA sensor cycle is performed in

sequence every 14 ms, whichgives enough time to stabilizemeasurement for each kind ofsensor. Sonars wait for echoesevery 14 ms, and the differentmodules must not be fired atthe same time. IR sensors

require 39 ms for each measure. Mostsensors of this kind require a settlingcommand followed by a reading com-mand after the time required to measureto be executed. The program acts as astate machine with a 14-ms clock, alter-nating sets, and reads cycles as describedin Table 1. The entire cycle completes inabout 100 ms to read three range finders,three IR distance sensors, three light sen-sors, the battery voltage, and gas sensors.The digital compass value can be read atany moment without any settling; there-fore, this measure is executed in the lastcycle.

A robot running at 50 cm/s travels for5 cm in 100 ms, which could be toomuch. In order to have the fastest possi-ble response when avoiding obstacles, acheck is performed at each cycle fordangerous distances. If the measureddistance on any side is less than thethreshold, or if any of the threebumpers is active, an immediate alar mis sent to navigation board. Instead ofwaiting the whole 100-ms cycle tocommunicate distance, the measuringpacket is sent immediately after themeasure during an emergency. In thisway, the robot travels a maximum of0.7 cm before braking, instead of 5 cmas in case of worst condition. Therefore,the robot is “blind” for only 0.7 cminstead of 5 cm.

READING & TRANSMISSIONThe SRF08 sensors can return the dis-

tance already converted in centimetersor inches. While reading the distancevalue, the light values from SRF08modules are also read. This can bedone within a single I2C reading cycle

gain can be reduced to limit the mod-ule’s sensitivity to the weaker distantecho, while still be able to detect near-by objects. The maximum gain setting isstored only in the module’s RAM and isinitialized to maximum at power-up, soif you only want to do a ranging every65 ms, or longer, you can ignore therange and gain registers. Note that therelationship between the gain registersetting and the actual gain is not a lin-ear one. Also, there is no magic for-mula to apply. It depends on theobject’s size, shape and material. Tryplaying with different settings untilyou get the result you want. If youappear to get false readings, it may beechoes from previous “pings.” Trygoing back to firing the SRF08 ever y65 ms or longer.

An internal timer sets the SRF08’smaximum range. By default, this is 65ms or the equivalent of 11 m of range.This is much farther than the 6 m theSRF08 is actually capable of. It is pos-sible to reduce the time the SRF08listens for an echo, and hence therange, by writing to the range registerat location 2. The range can be set insteps of about 43 mm (0.043 m or1.68″) up to 11 m. The range is ((RangeRegister × 43 mm) + 43 mm), so settingthe Range Register to 0 (0x00) gives amaximum range of 43 mm. Setting 255(0xFF) gives the original 11 m (i.e., 255 ×43 + 43 = 11,008 mm). For this purpose,I chose a value of 57 to obtain a 2.5-mrange (57 × 43 + 43 = 2,494-mm range).Considering a sound speed of 340 m/s, Ican apply a ping time of about 14 ms:(54,988 mm)/340 m/s = 14.67 ms. Othersensors require no initialization.

Table 1—Here you see a description of the actions performedto read sensor values in every state machine cycle. Alternat-ing set and read actions for a dif ferent kind of sensor in anycycle, it follows the timing required by the specifications. Afull cycle requires 98 ms. After that, the values are sent tothe navigation board 10 times per second.

Sequence Time (ms) First action Second action0 0 Left US set Gas set1 14 Gas read Left IR set2 28 Left US read Center US set3 42 Left IR read Center IR set4 56 Center IR read Center US read5 70 Right US set Right IR set6 84 Right IR read Vbatt set7 98 Vbatt read Right US read

2103017_Ottaviani.qxp 2/11/2010 10:28 AM Page 22

Page 11: Build and Program a “Minirobot,” p. 38 • Write Your Own Puzzle … · 2014. 12. 30. · 14 CIRCUIT CELLAR® • March 2010 – Issue 236 hoto 1—My upgraded robotics platform

www.circuitcellar.com • CIRCUIT CELLAR® 23

Mar

ch 2

010 –

Issue

236

Guido Ottaviani ([email protected]) has experience working as an analog and digitaldesigner for a communications company in Italy . He also has worked as a systemintegrator and a technical manager for a lar ge Italian publishing group. In his sparetime, Guido enjoys working with his scope and soldering iron on autonomous robot-ics projects. He’s an active member in Italian robotics groups.

on registers 1 and 2. Sharp IR sensorsinstead return an analog valueinversely proportional to the distanceof the object. According to the docu-mentation, the response curve can beapproximated with a 1/x trend. Asimple conversion can be obtainedwith the following formula:

K and offset constants can be comput-ed by just reading two values in thequasi-linear portion of the responsecurve. I chose values of 4 cm for Dis-tance 1 and 40 cm for Distance 2(still within the measurable range).In my configuration, this retur ns:ADCVAL1 = 2,492 and ADCVAL2 = 278.Therefore:

Of course, using centimeters whencalculating constants returns cen-timeters for “Dist” in the for mula.Using inches returns inches.

When you compare the conver tedreading from the Sharp sensors withdirect readings from the SRF08 sonar ,the differences are within 1 cm fromflat and mat objects. Under regularconditions, the actual distance fromthe object is considered the shor testdistance between the three sensorson the same side (bumper = onmeans Dist = 0). This scenario is bestfor safe obstacle avoidance. The max-imum distance is 255 cm, whichallows a 1-byte transmission packet.

When the voltage of the batter yfalls below a given threshold, analert sounds and a light illuminateson the sensor board. Reading the dig-ital compass is simple. The bearingvalue is transmitted as is (splittingthe 2-byte variable) to the navigationboard.

A simple protocol is used to trans-mit the data from the sensor board to

K = ADC Dist1

Dist 1

= 9,

VAL1ADC

DistDist

VAL2

22

−( ) × ×

−8840

Offset =

Dist2 ADC Dist1 ADC Di

VAL2 VAL1× − ×( )−Dist2 sst 1

= 32

Distance = value offset

KADC −

the navigation board. This protocol isthe same that’s used for telemetry onthe navigation board I described inmy previous articles (Circuit Cellar224 and 225, 2009).

DESIGN SUCCESSDo you need your robot to be able

to navigate safely in an obstacle-rid-den environment? This project is for

you. If you follow my lead, you canbuild a similar system withoutbreaking the bank. But this project isjust a starting point. Of course, youcan use many other sensors toachieve your goals—such as locatingstairs for a cleaning robot or enablingyour robot to follow a line. Thisboard has enough I/O and computa-tion power to get the job done. I

PROJECT FILESTo download the code, go to ftp://ftp.circuitcellar .com/pub/Circuit_Cellar/2010/236.

REFERENCES[1] Arduino, Shields, www.arduino.cc/en/Main/ArduinoShields.

[2] Arduino, Libraries, www.arduino.cc/en/Reference/Libraries.

[3] J. Borenstein and L. Feng, “Gyrodometr y: A New Method for CombiningData from Gyros and Odometry in Mobile Robots,” The University of Michi-gan, 1996, www-personal.umich.edu/~johannb/Papers/paper63.pdf.

RESOURCESCaptain’s Universe, “Active Filter Calculator: Band-pass with Op-AmpDesigner in Javascript,” www.captain.at/electronics/active-filter/.

B. Carter, “A Single Supply Op Amp Circuit Collection”, SLOA058, T exasInstruments, 2000, www.ti.com/sc/docs/psheets/abstract/apps/sloa058.htm.

NXP Semiconductors, “Tone Decoder/Phase-Locked Loop,” NE567/SE567,2002, www.nxp.com/acrobat_download/datasheets/NE567_SE567_2.pdf.

Sharp Corp, “GP2D120 Optoelectronic Device,” SMA06008, 2006,www.sharpsma.com/Page.aspx/americas/en/part/GP2D120/.

SOURCESDiecimila boardArduino | www.arduino.cc

TGS822 Gas sensorFigaro USA, Inc. | www.figarosensor.com

CMPS03 Electronic compass and SRF08 ultrasonic rangefinderDevantech Ltd | www.robot-electronics.co.uk

Philips NE567 tone decoder/PLLNXP Semiconductors | www.nxp.com

GP2D120 Infrared module Sharp Microelectronics of the Americas | www.sharpsma.com

OPA4244 Op-ampTexas Instruments, Inc. | www.ti.com

2103017_Ottaviani.qxp 2/11/2010 10:28 AM Page 23