14
2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This application note describes the use of PIC ® microcontroller Core Independent Peripherals (CIP) in ultrasonic range detection applications. The featured peripherals of Microchip’s PIC16F176X family enable the described example ultrasonic range detection circuit to calculate the distance traveled by the ultrasonic signal with minimum intervention from its Central Processing Unit (CPU). BLOCK DIAGRAM Figure 1 shows the block diagram of an ultrasonic range detection system based on the PIC16F1769 microcontroller. The CIPs and on-chip peripherals used in the design are the following: Data Signal Modulator (DSM) Configurable Logic Cell (CLC) Hardware Limit Timer (HLT) Comparator (CMP) Operational Amplifier (OPA) Pulse-Width Modulation (PWM) Capture Compare PWM (CCP) • Timers The interconnection of these peripherals significantly reduces the component count needed to implement an ultrasonic range detection application. Refer to Appendix B: “Ultrasonic Proximity and Range Finder” for the detailed schematic diagram. FIGURE 1: BLOCK DIAGRAM Author: Kristine Angelica Sumague Heather Savage Keith Curtis Anthony Stram Microchip Technology Inc. PWM3 DSM TMR0 CLC1 TMR1 HLT/ TMR4 CCP Logic Controlled Driver CLC2 TMR3 PRG C PIC16F1769 Microcontroller Resistors for Difference Amplifier Peak Detector Burst Signal Transmitter Received Signal Receiver OPA2 CMP1 OPA1 Ultrasonic Range Detection

AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

Embed Size (px)

Citation preview

Page 1: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536Ultrasonic Range Detection

INTRODUCTION

This application note describes the use of PIC®

microcontroller Core Independent Peripherals (CIP) inultrasonic range detection applications. The featuredperipherals of Microchip’s PIC16F176X family enablethe described example ultrasonic range detectioncircuit to calculate the distance traveled by theultrasonic signal with minimum intervention from itsCentral Processing Unit (CPU).

BLOCK DIAGRAM

Figure 1 shows the block diagram of an ultrasonicrange detection system based on the PIC16F1769microcontroller. The CIPs and on-chip peripherals usedin the design are the following:

• Data Signal Modulator (DSM)• Configurable Logic Cell (CLC)• Hardware Limit Timer (HLT)• Comparator (CMP)• Operational Amplifier (OPA)• Pulse-Width Modulation (PWM)• Capture Compare PWM (CCP) • Timers

The interconnection of these peripherals significantlyreduces the component count needed to implement anultrasonic range detection application. Refer toAppendix B: “Ultrasonic Proximity and RangeFinder” for the detailed schematic diagram.

FIGURE 1: BLOCK DIAGRAM

Author: Kristine Angelica Sumague Heather Savage

Keith CurtisAnthony StramMicrochip Technology Inc.

PWM3DSM

TMR0CLC1

TMR1

HLT/TMR4

CCP

Logic Controlled

Driver

CLC2

TMR3

PRG

C

PIC16F1769 Microcontroller

Resistors for

Difference Amplifier

Peak Detector

Burst SignalTransmitter

Received Signal

Receiver

OPA2

CMP1OPA1

2013-2017 Microchip Technology Inc. DS00001536C-page 1

Page 2: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

ULTRASONIC RANGE DETECTION OVERVIEW

Ultrasonic Transducer Background

Figure 2 shows the equivalent circuit of an ultrasonictransducer. The transducer is predominantly acapacitive load, but the inductance in the transducerforms a resonant circuit at around 40 kHz. Thetransmitter is tuned for maximum output while thereceiver is tuned for maximum voltage output at anincoming 40 kHz signal. This has an attenuatingfiltering effect on all other frequencies and is useful ineliminating noise when amplifying the received signal.

FIGURE 2: THE EQUIVALENT CIRCUIT OF AN ULTRASONIC DEVICE

One issue with ultrasonic transducers is that they willcontinue to oscillate or ring after the removal of thedrive signal. This ringing is due to the resonantmechanical behavior of the transducer. The transduceris tuned to ring like a bell at its specified ultrasonicfrequency when driven, and it takes a short period oftime for the ring to damp out after the drive is removed.While the transmitter is ringing, the signal will couplethrough the PCB or travel through the air between thetransmitter and receiver, and look like a receivedsignal, as shown in Figure 3. Therefore, a delay isrequired before the receiver is activated to ensure thatthe ringing has damped out, and any signal, other thanthat of a reflected pulse, is received. The amount oftime required for the ringing to damp out determinesthe minimum detectable distance of the receiver.

FIGURE 3: ULTRASONIC DEVICER1

C1

L1C0

F0 : Resonant FrequencyC0 : Parallel CapacitanceR1 : Series ResistanceL1 : Series InductanceC1 : Series Capacitance

Input

Output

Output

Ringing time

Ringing time

Short Ringing

Long Ringing

DS00001536C-page 2 2013-2017 Microchip Technology Inc.

Page 3: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

THEORY OF OPERATION

FIGURE 4: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION

The whole circuit is controlled by the PIC16F1769microcontroller, using its on-chip peripherals, as shownin Figure 4. The microcontroller generates a high-frequency drive, sets the duration of the drive andmeasures the time delay until the ultrasonic signal isreceived. The high-frequency drive produced by themicrocontroller allows the ultrasonic transmitter tobroadcast a 40 kHz pulse or several oscillations at thatfrequency. The PWM peripheral generates thespecified frequency to drive the ultrasonic transmitter.This PWM is tied to the carrier input while a CLC1peripheral is tied to the modulator input of the DSMperipheral. The CLC1 is configured to operate as anSR flip-flop with its set and reset inputs connected toTimer3 and Timer0, respectively. The SR flip-flop fromthe CLC1 connects and disconnects the PWM to theoutput pin through the DSM to generate a pulse ofultrasonic sound. The CLC1 output is also connected tothe HLT peripheral and to the reset input of the CLC2SR flip-flop. The HLT operates as a one-shot timer tocreate a time delay between the transmitter andreceiver. The time delay ensures that any ringing hasbeen dampened out. The HLT is tied to the CLC2 setinput, to allow the receiver circuit to operate after thedelay time.

When the signal is received and amplified by the OPA1,the peak detector will be compared to a receiver refer-ence voltage. This receiver reference voltage is gener-ated by the PRG connected to a unity gain OPA2. Thepeak detector and the unity gain OPA2 output are tiedto the positive and negative inputs of the CMP1,respectively. The CMP1 output is tied to the CCP togenerate a capture event, when the peak detector volt-age is greater than the reference voltage. The capturedtime by the CCP will be the part of the round trip timetraveled by the ultrasonic pulse.

PWM3

DSMTMR0

CLC1

TMR1

HLT/TMR4

CCP

CLC2

TMR3

PIC16F1769 Microcontroller

OPA2

C9

OPA1

CMP1

CH

MOD

OUT

R

S

Q

R

S

Q

-

+

-

+

-

+

R6 C5D1

Logic-controlledLoad driver

Data input

OUT

OUT

Enable

Transmitter

R4

R5

R7R9

ReceiverDifference Amplifier

Receiver Reference

Transmitter signal

Receive Signal Timer

Peak Detector

VREF

PRGRS

FS

C10

2013-2017 Microchip Technology Inc. DS00001536C-page 3

Page 4: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

FIGURE 5: ULTRASONIC RANGE DETECTION OPERATION

Figure 5 depicts how this ultrasonic range detectionsystem transmits and receives the ultrasonic pulse.The ultrasonic pulse train, which contains multiplepulses, is generated during the transmit period. Thispulse train is reflected by an object of greater densitythan air, and some of the energy from the emitted pulsereturns to the receiver. Before detecting the reflectedpulse, a delay between transmit and receive is neces-sary to damp out the ringing produced during the trans-mission of ultrasonic pulse. Upon transmitting theultrasonic pulse, the microcontroller starts its timerperipheral and captures the timer value when thereflected pulse is detected. When the signal has beendetected, the round trip travel time is measured andconverted to distance via the speed of sound.

CLC1

DSM

CLC2CAPTUREINDICATOR

HLT PERIOD CCP CAPTURED VALUE

PEAK DETECTOROUTPUT

VOLTAGE REFERENCE

OPA1 OUTPUT

DS00001536C-page 4 2013-2017 Microchip Technology Inc.

Page 5: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

PRODUCING 40 kHz WITH A PIC® MCU

Ultrasonic devices should be driven as close aspossible to their specified frequency to maximize theoutput power. The 40 kHz drive signal of the ultrasonicdevices can be easily created in a PIC microcontrollerby dividing down its internal oscillator or by using Timerperipherals. Two I/O pins of a PIC MCU can be used togenerate two differential 40 kHz signals that drive the

ultrasonic transmitter while a Timer0 peripheralinterrupt-on-overflow can be used to create the timebase for the output signal. (See Appendix C: “TimerFlowchart Implementation for Ultrasonic RangeDetection” for more details on how this isaccomplished). However, this type of control willrequire a lot of firmware coding compared to theinterconnection of CIPs that have no softwareoverhead.

FIGURE 6: 40 kHz ULTRASONIC TRANSMITTER CONFIGURATION

Figure 6 shows the connection of peripherals toproduce an ultrasonic pulse. The PWM output andCLC1 output are connected to DSM, whereas Timer0and Timer3 are connected to the CLC1 inputs. TheCLC1 sets the period of the ultrasonic pulse. Thismeans that the duration of time that PWM pulses areoutput through the DSM output pin depends on theCLC1 state. This implies that the DSM effectivelymodulates the PWM pulses with CLC1 output. TheCLC1 is periodically set by the Timer3 and reset by theTimer0 when the specified number of PWM pulses hasbeen reached.

DEAD TIME BEFORE RECEIVING ULTRASONIC PULSE

After an ultrasonic signal is created and output from theultrasonic transmitter, the next task is to create somedead time between transmitter and receiver. The deadtime is necessary so that residual oscillations on thesending element do not generate a false signal on thereceiving element. This is made possible by adding anHLT, configured as a one-shot timer, and by connectingand disconnecting the CMP1 positive input to ground(GND). The HLT one-shot timer period is the corre-sponding count of the minimum detectable distancetraveled by the ultrasonic signal.

As shown in Figure 7, when the CLC1 is set, the CLC2resets and the CMP1 positive input connects to GND.As the CLC1 transitions from high-to-low, the HLT istriggered. When the HLT one-shot times out, the CLC2is set and the CMP1 positive input connects to theoutput pin. This output pin connects the CMP1 to thereceiver circuit. By connecting and disconnecting theCMP1 positive input to GND, intermittent signaldetection during the transmission of ultrasonic pulses isavoided.

FIGURE 7: DEAD TIME BETWEEN TRANSMITTER AND RECEIVER

PWM

CLC1

40 kHz

TMR3 interrupt

TMR0 interrupt

DSMOUTPUT

PWM3

DSMTMR0

CH

MOD

CLC1

R

S

Q

TMR3

PIC16F1769

CLC1

HLT

CLC2

HLT period

COMP1+ input connects to GND

COMP1+ input connects to output pin

2013-2017 Microchip Technology Inc. DS00001536C-page 5

Page 6: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

RECEIVING AN ULTRASONIC PULSE

As the ultrasonic signal propagates in the air during thetransmission, the intensity of the signal decreases withdistance due to air absorption and beam spreading.Thus, the returning sound wave obtained by thereceiver is significantly attenuated. To alleviate thisproblem, signal amplification is necessary to detect thereturned signal. This amplification can be implementedusing a single OPA inside the PIC microcontroller,configured to operate as a difference amplifier.

An example circuit for the difference amplifier is shownin Figure 8. This OPA circuit amplifies the voltageacross the ultrasonic receiver connected between thetwo input pins. The common-mode noise at thedifference amplifier output can be minimized bymatching the input bias current through resistors R5and R7 and resistors R4 and R9. The ultrasonicreceiver acts like a tuned high Q filter, thus, thedifference amplifier effectively amplifies the filteringeffect of the receiver.

FIGURE 8: CIRCUIT FOR A DIFFERENCE AMPLIFIER

The output of the difference amplifier is tied to the peakdetector to measure the maximum magnitude of asignal over a period of time. This peak detector issimply a diode D1 connected between the output of thedifference amplifier (VAMP) and positive input of theCMP1 (VCMP+) with a parallel capacitor C5 and resistorR5, as shown in Figure 9. When the input signal on thepeak detector is rising, D1 is forward-biased and C5

charges rapidly to the difference of VAMP and D1voltage drop. When the input signal is falling, D1becomes reverse-biased and C5 stored chargereleases slowly through R6. The discharging of C5continues until the VAMP becomes greater than the C5charge. When VAMP is greater than the C5 voltage, D1conducts again and the process is repeated.

FIGURE 9: PEAK DETECTOR

R4

R5

R7

VOUT

VR IN-

VR IN+

R9

R5 = R7

R4 = R9

VOUT = (R4 / R5) x (VIN+ - VIN-)

OPA1

PIC16F1769

VREF

R6C5

D1

VAMP VCOMP

+

VCOMP+VAMP

DS00001536C-page 6 2013-2017 Microchip Technology Inc.

Page 7: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

The output of the peak detector is compared to thereceiver reference voltage using a comparator. Thereceiver reference voltage provides a falling rampvoltage so that the received signal reflected from longdistances can be detected. This ramping voltage wasproduced by the PRG which is coupled to a unity gainOPA2 for its physical output. The PRG is configured torun as a falling ramp generator with its timingdependent on the CLC2 peripheral and its referencevoltage input tied to the FVR peripheral. When theCLC2 output is reset, the PRG goes up to the FVRvoltage, and when the CLC2 is set, the PRG outputs afalling ramp voltage. However, the falling ramp voltageproduced by the PRG lasts for a very short period oftime compared to the period needed for long distancedetection. Due to this, external capacitors C9 and C10are coupled to the OPA2 output. The combination valueof C9 and C10 must be large enough to have asufficient falling ramp voltage for better receiversensitivity.

When the peak detector output reaches the receiverreference voltage, the CMP1 output will be set. Thisevent triggers the capture mode of the CCP. The 16-bitCCP High Byte and Low Byte register pair (CCPRxHand CCPRxL) captures and stores the 16-bit value ofthe Timer1 Counter register pair (TMR1H and TMR1L),

respectively. This captured value will be part of theround trip time in the form of counts traveled by theultrasonic pulse.

CONVERTING COUNTS TO DISTANCE

After detecting the returning ultrasonic pulse, the valuecaptured by the CCP and the HLT period will beconverted to distance. This is made possible bydividing the CCP captured value by two, since theultrasonic pulse travels back and forth, and then addingthe HLT period. The resulting value is multiplied by thespeed of sound and the inverse of the Timer clock inputas described in Equation 1.

Example 1 shows the code snippet on how distance iscalculated. The SpeedOfSound_at_TimerInc is aresulting constant from the product of the speed ofsound and the time it takes for the Timer peripheral toincrement. The variables used in the code are detailedin Appendix A: “Variables Used in the Firmware”.

EQUATION 1: DISTANCE FORMULA

EXAMPLE 1: CODE EXAMPLE FOR DISTANCE COMPUTATION

Dis cetanCCP captured value

2------------------------------------------------------- HLT period+ speed of sound 4

FOSC---------------=

Distance_in_Counts = (CCP1Capture - Timer1ReloadVal) >> 1) + HLTPeriod;Distance = (Distance_in_Counts * SpeedOfSound_at_TimerInc);

2013-2017 Microchip Technology Inc. DS00001536C-page 7

Page 8: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

ULTRASONIC RANGING DETECTION FIRMWARE

FIGURE 10: FIRMWARE FLOWCHART

Figure 10 shows the flowchart of the ultrasonic rangedetection firmware. During system start-up, thefirmware initializes the peripherals and the connectionsbetween them. After the peripherals are initialized, thePRG ramp output is enabled and the interrupts areenabled. The firmware waits until a signal is detected orTimer3 times out. When a signal is detected,display_result is set and the distance traveled bythe returned signal is calculated and displayed on theLCD. When Timer3 times out, if no signal has beendetected, “No Detection” is displayed on the LCD.

Additionally, the firmware executes several InterruptService Routines (ISRs) that are automaticallyexecuted when certain peripheral criteria have beenmet.

1. Timer3 Interrupt – Executed periodically anddictates the maximum range detection of theultrasonic pulse. When the Timer3 interruptoccurs, it reloads Timer0 and starts Timer4.Once Timer0 times out, CLC1 output will be sethigh, enabling Timer4 HLT. If no_detectionflag is set during the Timer3 interrupt, “NoDetection” will be displayed on the LCD

2. CLC2 Interrupt – The rising interrupt of theCLC2 occurs when Timer4 HLT one-shot timesout. CLC2 Interrupt will connect the CMP1 posi-tive input to C1IN1+ output pin to enable thedetection of the received signal. The interruptwill also reload Timer1, which keeps count of thereceived signal’s travel time.

3. CCP Interrupt – When the ultrasonic pulse isreceived, the CCP1 interrupts. When this hap-pens, the CMP1 positive input is connected toGND to disable the detection. Thedisplay_result variable is set so that themain loop will calculate and display the mea-sured distance on the LCD.

START

Initialize peripherals, start PRG ramp output and enable

interrupts

Wait for interrupt to occur

Is CLC2

Interrupts?

Is TMR3

Interrupts?

Is CCP1

Interrupts?

1.Connect COMP1 positive input to C1IN1+2. clear interrupt flag3. Reload TMR1

1. Reload Timer0 value2. clear interrupt timer3. Start TMR4

1. Connect COMP1 positive input to GND2. display_result = 13. save captured value to CCPCapturedValue4. clear interrupt flag

Calculate and display distance on the LCD

1. clear display_result2. clear no_detection

Is no_detection

set?

Display “No Detection” on the LCD

Set no_detection

A A

A

YESYES YES

YES

NONO NO

NO

DS00001536C-page 8 2013-2017 Microchip Technology Inc.

Page 9: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

Notice that after the initialization, the calculation of thedistance traveled by the returned ultrasonic pulse isdependent on the ISRs. This happens due to the CIPs,which, integrated to control the operation of the ultra-sonic range detection, perform their tasks inde-pendently. As a result, the complexity of the firmware isreduced and the core is only required during the ISRs.

All peripherals used in the firmware are configured andinitialized using the MPLAB® Code Configurator(MCC). For the complete source code, refer to the codeappended to the electronic version of this applicationnote.

MAXIMUM DETECTABLE DISTANCE

There are two ways of increasing the maximumdetectable distance in this application: increasedtransmission power and increased receiver sensitivity.Increasing the transmission power is made possible byconnecting the DSM output to a Logic-Controlled Loaddriver. This logic-controlled load driver, which is oneapplication use of a MOSFET driver, boosts the currentand voltage supplied to the transmitter transducer. As aresult, the ultrasonic pulse can travel longer distancesand still be detectable by the receiver.

Another method of increasing the maximum detectabledistance is by increasing the receiver sensitivity. In thisapplication, the sensitivity of the receiver can beincreased by changing the gain to a much higher value.Also, carefully controlling the offset value of thedifference amplifier ensures that the smallest returnpulse is positively detected.

LAYOUT CONSIDERATIONS

If a separate transmitter and receiver are used, theyshould both be aligned in the same direction. Thetransmitted signal and any subsequent ringing will leakthrough the PCB to the receiver circuitry. Placing morespace or a cut-out between the devices on the boardwill help to minimize this leakage. Ultrasonictransducers are often mounted using rubber or siliconto limit the amount of leaked ultrasonic signal to/fromthe surrounding material.

PERFORMANCE

Table 1 summarizes the performance of the ultrasonicrange detection. It can be observed that as the inputvoltage of the range finder increases, the measuredrange also increases.

CONCLUSION

This application note describes a PIC microcontroller-based solution for measuring the distance to an objectultrasonically with fewer external components. Byutilizing the flexibility of the PIC16F176X familymicrocontroller, with its core independent peripherals,the traveled distance by the ultrasonic pulse is acquiredwith less firmware overhead.

TABLE 1: ULTRASONIC RANGE DETECTION PERFORMANCE

Input Voltage (V)Maximum Range Measured

(in)

9V 207

12V 246

15V 260

18V 273

2013-2017 Microchip Technology Inc. DS00001536C-page 9

Page 10: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN1536

APPENDIX A: VARIABLES USED IN THE FIRMWARE

The variables used in the firmware are defined in thedefine.h file. Below is the summary of these variables.

TABLE A-1: FIRMWARE VARIABLES

Variable Description Value

display_result This variable toggles for the distance result display 0 or 1

SpeedOfSound_at_TimerInc Speed of sound multiplied by the inverse of clock input (i.e., 4/FOSC)

0.0135612 (in inches)

HLTPeriod Set HLT period value 0xD8

no_detection This variable toggles when no receive signal is detected after a cer-tain period of time, determined by Timer3 period

0 or 1

DS00001536C-page 10 2013-2017 Microchip Technology Inc.

Page 11: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

2

01

3-2

01

7 M

icroch

ip T

ech

no

log

y Inc.

DS

00

00

15

36

C-p

ag

e 1

1

AN

1536

AP

FIG

��!�!&'#

��

!)2)�

��

!)2)�

��&�

��

&�

�������

�����

���

��-

�2�1+��

���

���� ���

����

��,�

���3����3�

��,�

���

���,� �

���

���,�

����!�&���#�

��

�� �%

!�*:

%����

�� �%

!�*:

�����

PENDIX B: ULTRASONIC PROXIMITY AND RANGE FINDER

URE B-1: SCHEMATIC

���

���

����

����

���� ��

����

���� ���� ������������������

��

��

��� !�

��

�"�#���������

��

���! $

��#�

��"���������������%

��

����&

�� ����(�����(��#�#����"������#��������#����"(�� �)��!���������#�#����#����"��#����"(��� �������$�(���#����*���"����� �

�� ����+����+����(������ ���!����������������"���� �����������������,����������������-�����!�������������������� ���"���� !

��$���&����������##

������)��������- $

���������-��!���-��( ���$������-������-�#�"�#�( &�� �������������-��% )��!���������������#���#�� ��

������$�������������������������-���������������������������� �������� �����!������!�(���"���� ��������!������-��!���-�� �(� ��

��������.������(������������� �!�����������+-�������!��+-�����!�������#��"( � ���������/�0��������!��+��������!����������-������-���#���� �$

�##��

������

����$+��$)����"

���

���

��

��� !

� �

��1+���

� ��2�1+ ��

� �

���

�2�1+��

�1+���

!���

���

�������

���

�2�1+ ��

��

���

���

���

���#�

#�(��#

�##�$

��# �)

��� ���� &

��� )

��� ��

��! ��

�� ��

��$�#�" ��

����#� �!

������

����-�&

������)

����-��

����-��

�������

����

���!��� �!�$� ��

�&$ �&

�� �

��# �

���# �

�� !

��'3�'�

���3� $

����

�� ��

(��� �-��

�����&$!+#��

"���

"��,�����&$!+#��

�1+�$�

��

���

��'��,�2 44

5�

���

�2�1+���

��

�2�1+

�"��

�"���#�

�#�

����

����

�����6+��

�����

�����6+��

���(

���

���

��#�

#�(

�#���

����

�����-��-

�������

2���

!�1+�$�

��!�1+�$�

���

��

��

��

� ���(

��-

-)������

���

���� ���

�������

�1+ �$�

���

�1+�$�

��

�1+�$�

���

�1+�$�

���

�1+�$�

���

�1+�$�

���

�1+�$�

���

�1+�$�

���

�1+�$�

���

#�,#������

�,7#�"��8

�,7��#*��8

+�������

���%����

�����

��#�����

5#������#�9�

$

!

��

��

��,)�,����,��#

$�$

�-

��,)�,����,���

$�

��

������ ����

��

�&

!

$

Page 12: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

AN

1536

DS

00

00

15

36

C-p

ag

e 1

2

20

13

-20

17

Micro

chip

Te

chn

olo

gy In

c.

e()

to variable ‘i’output pulses

with 0xF1 high one lowpt Flag(T0IF)

Enable (T0IE)

t?

pulse

to ground

ISR

Load TMR0 with 0xF3

Toggle USdrive pins

Decrement ‘i’

‘i’ = 0?

Clear T0IE

Return From Interrupt

NO

YES

APPENDIX C: TIMER FLOWCHART IMPLEMENTATION FOR ULTRASONIC RANGE DETECTION

FIGURE C-1: ULTRASONIC FLOWCHART FOR TIMER IMPLEMENTATION

Power On

US_Init()LCD_Init()Math_Init()

Enable Global Interrupts

Clear TMR1H:LTurn on TMR1

SendPulse()SendDelay()

DetectReturnPulse()

TMR1Overflowed 8

times?

CountDistance()AverageDistance()WriteOutToLCD()

Increase number of output pulses to a max. of 16

DetectReturnPulse()

Turn on ComparatorClear Comparator

Interrupt(C2IF)

C2IF set?

C2IF set?

Minimum distance detected

‘numPulses’ set to 0x01

TMR1IF set?

-Increment Overflow Count

-Clear TMR1IF

8 Overflows?

-Turn off Timer1-Store Timer1 count-Turnoff Comparator

Return

YES

YES

YESYES

YES

NO

NONO

NONO

SendPuls

-Copy ‘numPulses’-Double number of

-Preload Timer0 -Initialize USdrive pin-Clear Timer0 Interru

-Set Timer0 Interrupt

TOIE se

Output last

Set output pins

Return

YES

NO

Page 13: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

Note the following details of the code protection feature on Microchip devices:

• Microchip products meet the specification contained in their particular Microchip Data Sheet.

• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions.

• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.

• Microchip is willing to work with the customer who is concerned about the integrity of their code.

• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”

Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.

Information contained in this publication regarding deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS FOR PURPOSE. Microchip disclaims all liabilityarising from this information and its use. Use of Microchipdevices in life support and/or safety applications is entirely atthe buyer’s risk, and the buyer agrees to defend, indemnify andhold harmless Microchip from any and all damages, claims,suits, or expenses resulting from such use. No licenses areconveyed, implicitly or otherwise, under any Microchipintellectual property rights unless otherwise stated.

2013-2017 Microchip Technology Inc.

Microchip received ISO/TS-16949:2009 certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California and India. The Company’s quality system processes and procedures are for its PIC® MCUs and dsPIC® DSCs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.

QUALITY MANAGEMENT SYSTEM CERTIFIED BY DNV

== ISO/TS 16949 ==

Trademarks

The Microchip name and logo, the Microchip logo, AnyRate, AVR, AVR logo, AVR Freaks, BeaconThings, BitCloud, chipKIT, chipKIT logo, CryptoMemory, CryptoRF, dsPIC, FlashFlex, flexPWR, Heldo, JukeBlox, KEELOQ, KEELOQ logo, Kleer, LANCheck, LINK MD, maXStylus, maXTouch, MediaLB, megaAVR, MOST, MOST logo, MPLAB, OptoLyzer, PIC, picoPower, PICSTART, PIC32 logo, Prochip Designer, QTouch, RightTouch, SAM-BA, SpyNIC, SST, SST Logo, SuperFlash, tinyAVR, UNI/O, and XMEGA are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

ClockWorks, The Embedded Control Solutions Company, EtherSynch, Hyper Speed Control, HyperLight Load, IntelliMOS, mTouch, Precision Edge, and Quiet-Wire are registered trademarks of Microchip Technology Incorporated in the U.S.A.

Adjacent Key Suppression, AKS, Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BodyCom, CodeGuard, CryptoAuthentication, CryptoCompanion, CryptoController, dsPICDEM, dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial Programming, ICSP, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, Mindi, MiWi, motorBench, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, PureSilicon, QMatrix, RightTouch logo, REAL ICE, Ripple Blocker, SAM-ICE, Serial Quad I/O, SMART-I.S., SQI, SuperSwitcher, SuperSwitcher II, Total Endurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.

Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries.

GestIC is a registered trademark of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of Microchip Technology Inc., in other countries.

All other trademarks mentioned herein are property of their respective companies.

© 2013-2017, Microchip Technology Incorporated, All Rights Reserved.

ISBN: 978-1-5224-1880-1

DS00001536C-page 13

Page 14: AN1536 - Ultrasonic Range Detection - Microchip …ww1.microchip.com/downloads/en/AppNotes/00001536C.pdf2013-2017 Microchip Technology Inc. DS00001536C-page 1 AN1536 INTRODUCTION This

DS00001536C-page 14 2013-2017 Microchip Technology Inc.

AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support: http://www.microchip.com/supportWeb Address: www.microchip.com

AtlantaDuluth, GA Tel: 678-957-9614 Fax: 678-957-1455

Austin, TXTel: 512-257-3370

BostonWestborough, MA Tel: 774-760-0087 Fax: 774-760-0088

ChicagoItasca, IL Tel: 630-285-0071 Fax: 630-285-0075

DallasAddison, TX Tel: 972-818-7423 Fax: 972-818-2924

DetroitNovi, MI Tel: 248-848-4000

Houston, TX Tel: 281-894-5983

IndianapolisNoblesville, IN Tel: 317-773-8323Fax: 317-773-5453Tel: 317-536-2380

Los AngelesMission Viejo, CA Tel: 949-462-9523Fax: 949-462-9608Tel: 951-273-7800

Raleigh, NC Tel: 919-844-7510

New York, NY Tel: 631-435-6000

San Jose, CA Tel: 408-735-9110Tel: 408-436-4270

Canada - TorontoTel: 905-695-1980 Fax: 905-695-2078

ASIA/PACIFICAsia Pacific OfficeSuites 3707-14, 37th FloorTower 6, The GatewayHarbour City, Kowloon

Hong KongTel: 852-2943-5100Fax: 852-2401-3431

Australia - SydneyTel: 61-2-9868-6733Fax: 61-2-9868-6755

China - BeijingTel: 86-10-8569-7000 Fax: 86-10-8528-2104

China - ChengduTel: 86-28-8665-5511Fax: 86-28-8665-7889

China - ChongqingTel: 86-23-8980-9588Fax: 86-23-8980-9500

China - DongguanTel: 86-769-8702-9880

China - GuangzhouTel: 86-20-8755-8029

China - HangzhouTel: 86-571-8792-8115 Fax: 86-571-8792-8116

China - Hong Kong SARTel: 852-2943-5100 Fax: 852-2401-3431

China - NanjingTel: 86-25-8473-2460Fax: 86-25-8473-2470

China - QingdaoTel: 86-532-8502-7355Fax: 86-532-8502-7205

China - ShanghaiTel: 86-21-3326-8000 Fax: 86-21-3326-8021

China - ShenyangTel: 86-24-2334-2829Fax: 86-24-2334-2393

China - ShenzhenTel: 86-755-8864-2200 Fax: 86-755-8203-1760

China - WuhanTel: 86-27-5980-5300Fax: 86-27-5980-5118

China - XianTel: 86-29-8833-7252Fax: 86-29-8833-7256

ASIA/PACIFICChina - XiamenTel: 86-592-2388138 Fax: 86-592-2388130

China - ZhuhaiTel: 86-756-3210040 Fax: 86-756-3210049

India - BangaloreTel: 91-80-3090-4444 Fax: 91-80-3090-4123

India - New DelhiTel: 91-11-4160-8631Fax: 91-11-4160-8632

India - PuneTel: 91-20-3019-1500

Japan - OsakaTel: 81-6-6152-7160 Fax: 81-6-6152-9310

Japan - TokyoTel: 81-3-6880- 3770 Fax: 81-3-6880-3771

Korea - DaeguTel: 82-53-744-4301Fax: 82-53-744-4302

Korea - SeoulTel: 82-2-554-7200Fax: 82-2-558-5932 or 82-2-558-5934

Malaysia - Kuala LumpurTel: 60-3-6201-9857Fax: 60-3-6201-9859

Malaysia - PenangTel: 60-4-227-8870Fax: 60-4-227-4068

Philippines - ManilaTel: 63-2-634-9065Fax: 63-2-634-9069

SingaporeTel: 65-6334-8870Fax: 65-6334-8850

Taiwan - Hsin ChuTel: 886-3-5778-366Fax: 886-3-5770-955

Taiwan - KaohsiungTel: 886-7-213-7830

Taiwan - TaipeiTel: 886-2-2508-8600 Fax: 886-2-2508-0102

Thailand - BangkokTel: 66-2-694-1351Fax: 66-2-694-1350

EUROPEAustria - WelsTel: 43-7242-2244-39Fax: 43-7242-2244-393

Denmark - CopenhagenTel: 45-4450-2828 Fax: 45-4485-2829

Finland - EspooTel: 358-9-4520-820

France - ParisTel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79

France - Saint CloudTel: 33-1-30-60-70-00

Germany - GarchingTel: 49-8931-9700Germany - HaanTel: 49-2129-3766400

Germany - HeilbronnTel: 49-7131-67-3636

Germany - KarlsruheTel: 49-721-625370

Germany - MunichTel: 49-89-627-144-0 Fax: 49-89-627-144-44

Germany - RosenheimTel: 49-8031-354-560

Israel - Ra’anana Tel: 972-9-744-7705

Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781

Italy - PadovaTel: 39-049-7625286

Netherlands - DrunenTel: 31-416-690399 Fax: 31-416-690340

Norway - TrondheimTel: 47-7289-7561

Poland - WarsawTel: 48-22-3325737

Romania - BucharestTel: 40-21-407-87-50

Spain - MadridTel: 34-91-708-08-90Fax: 34-91-708-08-91

Sweden - GothenbergTel: 46-31-704-60-40

Sweden - StockholmTel: 46-8-5090-4654

UK - WokinghamTel: 44-118-921-5800Fax: 44-118-921-5820

Worldwide Sales and Service

11/07/16