6
www.circuitcellar.com CIRCUIT CELLAR ® Issue 150 January 2003 1 ticular surface and return. Then, the device calculates the distance based on the estimated speed of sound. In this article, I’ll explain how I built this simple ultrasonic distance meter. Photo 1a is a picture of my PSoC RangeFinder with an LCD. The display is optional, and I removed it for Photo 1b. For this particular applica- tion, the only required components are a PSoC microcontroller, two 40-kHz ultrasonic transducers, two resistors, and two capacitors. Similar circuits are typically complicated and expensive, consisting of a large number of inte- grated circuit and passive components. Take a look at the RangeFinder’s system block diagram in Figure 1. As you can see, it’s divisible into three parts: the transmitting section, receiv- ing section, and output section. Each section contains several PSoC blocks. Using the PSoC chip family, all of the digital and analog devices are on-board with the microcontroller. The RangeFinder has numerous applications. You can use it for the positioning of robots as well as meas- uring generic distances, liquid levels in tanks, and the depth of snow banks. The device can also serve as a motion detector in production lines where sur- faces must not be damaged, or you can use it for educational purposes. A restricted target angle (it requires a near-perpendicular surface) and large beam, which can create poor resolu- tion, seem to be the RangeFinder’s only limitations. Despite these draw- backs, you’ll find the device’s main features to be extremely useful. The RangeFinder has a 40-kHz oper- ating frequency, a range of 25 to 200 cm, and 1-cm resolution. In addition, it here are several ways to measure distance without con- tact. Some products have infrared light emitters and receivers that determine an object’s distance by implementing the optical triangulation method. Other devices have laser-based systems that increase accuracy and precision. For electrical- ly conductive metal objects, the eddy current method is an option, and capacitive sensors that are independ- ent of the metal used in the measured objects can be used. I decided to use ultrasonic waves. My ultrasonic PSoC RangeFinder measures the amount of time it takes for a pulse of sound to travel to a par- The PSoC RangeFinder t Some distances are more difficult to meas- ure than others. Therefore, Fabio built his own ultrasonic rangefinder, which won First Prize in the Cypress PSoC design contest. It can be used for measuring liquid levels, generic distances, and even the depth of snow. Fabio Piana FEATURE ARTICLE Photo 1a—There are several things to consider when building your own ultrasonic rangefinder, including whether or not to incorporate an LCD. b—Take a look at the PSoC RangeFinder without the LCD. A Simple Ultrasonic Distance Meter a) CONTEST WINNER b) Circuit Cellar, the Magazine for Computer Applications. Reprinted by permission. For subscription information, call (860) 875-2199, or www.circuitcellar.com. Entire contents copyright ©2001 Circuit Cellar Inc. All rights reserved.

Lcdli Park Sonar

Embed Size (px)

DESCRIPTION

Lcdli Park Sonar

Citation preview

Page 1: Lcdli Park Sonar

www.circuitcellar.com CIRCUIT CELLAR® Issue 150 January 2003 1

ticular surface and return. Then, thedevice calculates the distance basedon the estimated speed of sound. Inthis article, I’ll explain how I builtthis simple ultrasonic distance meter.

Photo 1a is a picture of my PSoCRangeFinder with an LCD. The displayis optional, and I removed it forPhoto 1b. For this particular applica-tion, the only required components area PSoC microcontroller, two 40-kHzultrasonic transducers, two resistors,and two capacitors. Similar circuits aretypically complicated and expensive,consisting of a large number of inte-grated circuit and passive components.

Take a look at the RangeFinder’ssystem block diagram in Figure 1. Asyou can see, it’s divisible into threeparts: the transmitting section, receiv-ing section, and output section. Eachsection contains several PSoC blocks.Using the PSoC chip family, all of thedigital and analog devices are on-boardwith the microcontroller.

The RangeFinder has numerousapplications. You can use it for thepositioning of robots as well as meas-uring generic distances, liquid levelsin tanks, and the depth of snow banks.The device can also serve as a motiondetector in production lines where sur-faces must not be damaged, or you canuse it for educational purposes.

A restricted target angle (it requiresa near-perpendicular surface) and largebeam, which can create poor resolu-tion, seem to be the RangeFinder’sonly limitations. Despite these draw-backs, you’ll find the device’s mainfeatures to be extremely useful.

The RangeFinder has a 40-kHz oper-ating frequency, a range of 25 to 200 cm,and 1-cm resolution. In addition, it

here are severalways to measure

distance without con-tact. Some products

have infrared light emitters andreceivers that determine an object’sdistance by implementing the opticaltriangulation method. Other deviceshave laser-based systems that increaseaccuracy and precision. For electrical-ly conductive metal objects, the eddycurrent method is an option, andcapacitive sensors that are independ-ent of the metal used in the measuredobjects can be used.

I decided to use ultrasonic waves.My ultrasonic PSoC RangeFindermeasures the amount of time it takesfor a pulse of sound to travel to a par-

The PSoC RangeFinder

tSome distances aremore difficult to meas-ure than others.Therefore, Fabio builthis own ultrasonicrangefinder, whichwon First Prize in theCypress PSoC designcontest. It can beused for measuringliquid levels, genericdistances, and eventhe depth of snow.

Fabio Piana

FEATUREARTICLE

Photo 1a—There are several things to consider when building your own ultrasonic rangefinder, including whetheror not to incorporate an LCD. b—Take a look at the PSoC RangeFinder without the LCD.

A Simple Ultrasonic Distance Meter

a)

CONTEST WINNER

b)

Circuit Cellar, the Magazine for Computer Applications. Reprintedby permission. For subscription information, call (860) 875-2199, orwww.circuitcellar.com. Entire contents copyright ©2001 CircuitCellar Inc. All rights reserved.

Page 2: Lcdli Park Sonar

2 Issue 150 January 2003 CIRCUIT CELLAR® www.circuitcellar.com

where T is equal to the air tempera-ture (°C). So, for a middle value of22°C:

For a round-trip ping, you have:

And with a 24-MHz MCU clock:

An 8-bit counter (F40kHz) drives theultrasonic transmitter and a digitalinverter (F40kHz_inv). The phase ofthe voltage applied to the positive andnegative terminals of the sensor hasbeen shifted 180°, so two times thesupply voltage is applied to the sensor.

The 40-kHz transmission enables an8-bit counter (called “Meter”) thatincrements one step per centimeter.The Meter clock input is TimeBase(17,240 Hz).

The ultrasonic receiver’s negative ter-minal is connected to the analog groundreference (AGND—pin 25, P02) provid-ed by RefMux_1, a reference multiplex-er allocated in the ACA03 block. Theultrasonic receiver’s positive terminal isconnected to an amplification chainbased on a programmable gain amplifi-er (PGA_1) and two two-pole passbandfilters (BPF2_1 and BPF2_2). The firstpassband filter is designed for a 40-kHzcenter frequency and a correspondentgain of 33 dB. The second filter is alsodesigned for a 40-kHz center frequency,

but it has a 10-dB pass-band gain. Because of thediscrete value of thecapacitors integrated in theswitched-capacitor analogblocks, the real frequencyresponse is different fromthe nominal one.

Figure 2 shows theBPF2_1 and BPF2_2 fre-quency responses. TheBPF_2 output is sent tothe programmable thresh-old comparator (CMP-PRG_1). When a 40-kHz

fTimeBase =

24 MHz

116= 2 MHz

116=17. 24 kHz12

fTimeBase = VSOUND IN AIR

2= 17. 23kHz

VSOUND IN AIR = 331.4+ (0.6 × 22) =344 .6 m/s = 34,460cm/s

VSOUND IN AIR= 331.4+ (0.6 × T)

requires only a single 5-VDC power sup-ply and draws just 25 mA (23 mA with-out the LCD). The device has one PWMoutput and one TTL-level serial output(9600 bps, 8 bits, 1 stop bit, and no pari-ty). Finally, don’t forget the optional2 × 16 LCD, software calibration, anddynamic receiver stage gain increment.

MICRO CONFIGURATIONSeveral PSoC microcontroller

resources were used in this project. Iapplied the following PSoC digitalresources: five 8-bit counters, an 8-bitserial transmitter, two 8-bit PWMs,and a digital inverter. I implementedthe following analog resources: oneprogrammable gain amplifier (PGA),two two-pole passband filters, a pro-grammable threshold comparator, anda reference multiplexer. Inaddition, I used the EEP-ROM and LCD toolboxsoftware modules.

Photo 2 is a screen shotof the PSoC Designerwith the Device Editorshowing the placement ofthe PSoC’s digital andanalog resources. As youcan see, a large number ofresources are required.All of the digital blocksand several analog blocksare employed.

The software modules include theLCD toolbox user module and a com-plete set of library routines that allowsyou to write numbers and strings to atwo-line LCD using standard HitachiHD44780 commands. An EEPROMemulation library allows you to storeimportant data in flash memory spaceas if it were a physical EEPROM.

PRINCIPLESThe transmission section is based

on four digital blocks allocated in theDBA00, DBA01, DBA02, and DBA03blocks. An 8-bit counter (called“TimeBase”) provides a 17,240-Hztime base frequency. Sound velocitydepends on ambient air temperature,which is calculated for an air tempera-ture value of 22°C:

Figure 1—There are three distinct sections in my PSoC RangeFinder project: digitalblocks, analog blocks, and transducers.

Listing 1—The time base interrupt routine is the heart of the measuring process. Remember, the PGA_1gain is dynamically reconfigured from one to 16.

TimeBaseINT://Interrupt rate = 58 µs

push ainc [time1]cmp [time1],26 ;25 //35 × 58 ms = 2-ms blankjc timebase1 //Jump if time 1 < 35

//Test comparatortst reg[CMP_CR],0b01000000 //Test if comparator = 1jz timebase1 //If comparator = 0, then jump

//gest comparator = 1 (pong) mov A,[time1]mov [range],A //Distance in range call TimeBase_DisableInt //Disable time base interrupt

timebase1://Set PGA_1 gain

mov A,[time1]cpl Aor A,0b00001111 //Add X8hcall PGA_1_SetGain //Set pga_1 gain in 16 stepspop Areti

TimeBase CNTR8

Meter CNTR8

F40kHzCNTR8 F40kHz_inv

US TX

TX Section

BPF2_1 _^BPF2 BPF2_2 _^_BPF2

RX Section

PWM_Output PWM Baud9600 CNTR8 Serial TX TX8PWM out Serial out

Output section

RefMux_1 REFMUX

US RX

AGND

PGA_1

+

An_Clock CNTR81, 5 MHz

+

–VREF

CMPRG_1

Page 3: Lcdli Park Sonar

www.circuitcellar.com CIRCUIT CELLAR® Issue 150 January 2003 3

selected this value for a good contrastin the LCDs used in prototypes. It canbe changed to adjust the contrastusing different LCD modules. In addi-tion, a 10-kΩ trimmer with the wiperto the contrast input and other pinsconnected to 5 V and GND canreplace it. This allows for decent LCDcontrast regulation.

Without an LCD, the circuit drawsapproximately 23 mA from a 5-V powersupply. If you use an LCD, the currentconsumption is 25 mA. The optionalLCD is a standard 2 × 16 model.

THE SOFTWAREFigure 4 is a flowchart depicting the

microcontroller’s software. The mainprogram sets up the analog and digitalblocks before testing JP1 to determine

signal is received, the CMPPRG_1output is high logic level, so the soft-ware can read it.

There are two different output devicesin the output section: an 8-bit pulsewidth modulator and an 8-bit serialtransmitter. In the former, the frequencyof the rectangular signal that’s availableon the PWM output (P2.7, pin 5) isapproximately 780 Hz; its pulse widthis proportional to a measured distancevalue (5 µs per centimeter). The latter isa standard TTL logic-level serial output.Transmission parameters are 9600 bps,8 data bits, 1 stop bit, and no parity bit.An 8-bit counter, Baud9600, provides a9600-Hz time base for the serial trans-mitter block, SerialTX, with its outputon P2.4 (pin 22). If you need RS-232interfacing, you can use an external TTL-level RS-232 converter (e.g., thecommon, inexpensive MAX232).This means that you can alsointerface the RangeFinder to a PCor microcontroller-based systemwith a standard RS-232 port.

THE HARDWAREThe RangeFinder’s circuitry is

quite simple (see Figure 3). Themost important part is U1,which is a CY8C26443 PSoCmicrocontroller. U1 does all ofthe work with its internal analogand digital blocks.

Two capacitors, C1 and C2,suppress high- and low-frequencynoise on the 5-V supply line. R1is a 100-kΩ resistor that holdsthe DC input voltage of thereceiving stage to AGND (2, 5 V).R2 regulates the LCD contrast. I

Normal or Calibration mode. If JP1 isshorted, the control program runs theNormal mode procedure. Otherwise,the calibration routine is executed.

In Normal mode, the software con-tinuously runs the transmitted ultra-sonic burst (ping). After a blankingtime, it waits for the returned ultra-sonic signal (pong). The time betweenthe start of a transmitted burst andthe start of a received burst is propor-tional to the distance between theRangeFinder and the obstacle. Bypolling the comparator bus register, thesoftware measures this time and storesit in a RAM location. Finally, the rangevalue is written to the LCD (if present),sent to the serial interface, and thePWM duty cycle is set to a valuethat’s proportional to the distance.

Figure 3—Building the circuitry for the PSoC RangeFinder isn’t complicated . All of the functions are concentrated in theC48C26443 PSoC microcontroller, which is clearly the most important part of the design.

Nominal

Expected

Frequency (Hz)

40

35

30

25

20

15

10

Gai

n (d

B)

20,000 25,000 30,000 35,000 40,000 45,000 50,000

5

0

0 20,000 40,000 60,000 80,000

Frequency (Hz)

15

10

5

0

–5

–10

–15

Gai

n (d

B)

Nominal

Expected

Figure 2a—This is the BPF2_1 frequency response graph. b—The BSF2_2 frequency response graph is a little different. For the filter design, I used the appropriate Cypressfilter design folder in Excel.

a) b)

Page 4: Lcdli Park Sonar

4 Issue 150 January 2003 CIRCUIT CELLAR® www.circuitcellar.com

The software in Calibration mode issimilar to that in Normal mode; how-ever, the measured value is comparedwith the constant value 50, and theresultant offset is stored in nonvolatileEEPROM and used to calculate themeasured range in Normal mode.TimeBase_int is the interrupt sub-

routine for the TimeBase 8-bit counter.This is the most important portion ofcode (see Listing 1). When time1 isgreater than the value of blank time(blank time prevents false echoescaused by the lateralreceiving of transmitted40-kHz bursts), the soft-ware tests the logicalvalue of the comparator.If a pong is received, thecomparator output logiclevel is one, the time1value is stored in RAMlocation range, and theTimeBase interrupt is dis-abled. As a result, thevalue stored in the rangelocation represents themeasured distance.

If the comparator logiclevel output is equal tozero, then the PGA_1gain is dynamicallyincremented in 16 stepsfrom one to 16 by modi-fying the correspondinggain register; therefore,the far echoes are muchmore amplified.

As you can see in Table 1, the PGA_1gain increment is not linear. This is nota problem, because more amplificationis required for long distances. As youcan see in Listing 1, the PGA_1_SetGainroutine is called to change the amplifiergain and the value stored in the relativeconfiguration register.

PRACTICAL CONSTRUCTIONConstructing the circuit isn’t diffi-

cult. It will take you just a few min-utes. You may download the single-sided PCB design from the CircuitCellar ftp site. The correspondingcomponent layout is available on theftp site, as well.

First, you have to mount the twowire links. The links are followed bythe microcontroller socket, two resis-tors (mounted vertically), and twocapacitors. Pay attention to the polari-ty of C2, which is a tantalum elec-trolytic capacitor. Follow with the twoheaders and jumper. J1 is a four-pinmale header for the power supply andoutput connections. J2 is a 14-pinfemale header for the LCD connection.

The two ultrasonic transducers aresoldered directly to the copper-sidedpadstacks. These common 40-kHzultrasonic transducers are the kindused in car alarms. Make sure you

Main Calibration TimeBase_int

Initialize and start blocks

JP1?

Send 40-kHz ping

Wait for blank time

Wait for 40-kHz pong

Calculate and send range to

LCD, PWM, and serial

CalibrationN

Y

Send 40-kHz ping

Wait for blank time

Wait for 40-kHz pong

Calculate offset

and store inEEPROM

Ret

Time>= blank?

Inc time1

Compare = 1?

Disable TimeBase_int

save time1

Increment PGA_1 gain

Ret

N

N

Y

Y

Figure 4—A flowchart will help you understand the software associated withthis project. Note that there are three relevant routines: the main program, thecalibration routine, and the TimeBase 8-bit counter interrupt subroutine.

Gain Value

PGA_A_G16_0 08hPGA_A_G8_00 18hPGA_A_G5_33 28hPGA_A_G4_00 38hPGA_A_G3_20 48hPGA_A_G2_67 58hPGA_A_G2_27 68hPGA_A_G2_00 78hPGA_A_G1_78 88hPGA_A_G1_60 98hPGA_A_G1_46 A8hPGA_A_G1_33 B8hPGA_A_G1_23 C8hPGA_A_G1_14 D8hPGA_A_G1_06 E8hPGA_A_G1_00 F8h

Table 1—The PSoC’s PGA gain values are used to setthe PGA_1 gain during the measuring routine. Formore information, study the PGA_A module datasheetfrom Cypress.

Page 5: Lcdli Park Sonar

www.circuitcellar.com CIRCUIT CELLAR® Issue 150 January 2003 5

position the two ultrasonictransducers correctly. Usually,the negative terminal is solderedto the case for good noise immu-nity. You can make the connec-tion to the LCD by soldering a14-pin male connection to theLCD module with a flat ribboncable or a set of individual flexi-ble wires. After a final inspec-tion of the populated board, youcan insert a programmed PSoCmicrocontroller into its 28-pin socket.

POWER AND CALIBRATIONThis circuit needs a 5-V regulated and

filtered power supply. Because of thereduced circuit size, the voltage regu-lator is not included. If an external 5-Vpower source isn’t available and all youhave is an unregulated 8-V supply, youcan use a three-legged voltage regulator(i.e., 78L05 at 5 V–100 mA maximum)and some capacitors to increase ripplerejection and transient behavior.

You must calibrate the unit beforeit’s installed. The calibration proce-dure is simple. First, place the

rangefinder 50 cm in front of a perpen-dicular, flat obstacle (e.g., a wall orwood panel). Second, remove jumperJP1 and power up the circuit by con-necting the 5-V regulated power sup-ply. Finally, insert jumper JP1 andpower down the circuit. At this pointthe circuit is calibrated and the offsetvalue is stored in EEPROM. The valuewill be read from the software at eachcircuit power-up and used in the dis-tance calculating operation.

Figure 5 shows the text displayed onthe LCD in Normal and Calibrationmodes. This text is easy to change,because it’s stored as ASCII strings.

You may download the stringsfrom the main.asm file on theCircuit Cellar ftp site.

THINGS TO CONSIDER I used the 28-pin CY8C26443

microcontroller because of itsavailability; however, you can usethe eight- (if you don’t use theLCD) or 20-pin versions for asmaller PCB. With the LCD con-nected, you can display useful

information while setting up and cali-brating your own PSoC RangeFinder.

It’s easy to change the program ifyou’re thinking about modifying thedevice’s behavior. Because any one ofseveral obstacles can surface at anytime, the ultrasonic distance metercan make mistakes during the meas-urement process. However, if youwant to prevent measurement errors,you can modify the software to calcu-late the average value of several meas-urements and discard the measuredvalues that are out of range.

The measurement process is basedon a typical air temperature of 22°C.

P S o C r a gn e f I n d e r

Normal mode

D i s t n c e N N N c ma

5 0 c m c a il b r a t i o n

Calibration mode

P l a c J 1P j u m e re p

Figure 5—The LCD text that appears in Normal and Calibration modeis fairly easy to change. Note that NNN represents the measured value.

Page 6: Lcdli Park Sonar

6 Issue 150 January 2003 CIRCUIT CELLAR® www.circuitcellar.com

This can be limiting when the specif-ic application involves a wide operat-ing temperature range.

If you use a 28- or 20-pin integrat-ed circuit, there will be a lot of freepins in the PSoC microcontroller. Itwould be an improvement to imple-ment an external integrated tempera-

ture sensor to measure the air tem-perature. Because of its low accuracy(± 20°C), the internal FlashTempmodule isn’t suitable for the job. But,if you want to increase the precision,you can calculate and compensatefor the different sound velocities atdifferent air temperatures. I

PROJECT FILESTo download the code, go toftp.circuitcellar.com/pub/Circuit_Cellar/2003/150/.

Fabio Piana has been teaching elec-tronics and systems automation forthe last 15 years in several technicalschools in Italy. In addition, he’s anelectronics design consultant. Youmay reach him at [email protected].

RESOURCESCypress MicroSystems,“CY8C25122, CY8C26233,CY8C26443, CY8C26643 DeviceData Sheet,” CMS10002A-R3.15,2002.

———, “PSoC Designer, PGA_AModule Data Sheet,” 2002.

SOURCECY8C26443 PSoC MicrocontrollerCypress MicroSystems, Inc.(877) 751-6100www.cypressmicro.com

Photo 2—Note the placement of the PSoC’s resources. For this application, all of the digital blocks are required.