ultrasonic range detection app. note · ds00001536b-page 4 2013-2016 microchip technology inc....

26
2013-2016 Microchip Technology Inc. DS00001536B-page 1 AN1536 INTRODUCTION This application note describes the use of PIC ® microcontroller Core Independent Peripherals (CIP) in ultrasonic range detection applications. The feature peripherals of Microchip’s PIC16F176X family enable the ultrasonic range detection 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 based on the PIC16F176X family microcontroller. The CIPs used in the design are as follows: Data Signal Modulator (DSM) Configurable Logic Cell (CLC) Hardware Limit Timer (HLT) Comparator (CMP) Operational Amplifier (OPA) Combining the CIPs with other on-chip peripherals, such as I/O ports, Timers, Pulse-Width Modulation (PWM), Capture Compare PWM (CCP) and Digital-to- Analog Converter (DAC), brings the intelligence to the whole system. The interconnection of these peripherals significantly reduces the component count needed to implement an ultrasonic range detection application. Refer to Appendix C: “Ultrasonic Range Detection Schematic” for the detailed schematic diagram. FIGURE 1: BLOCK DIAGRAM Author: Kristine Angelica Sumague Keith Curtis Anthony Stram Microchip Technology Inc. PWM3 DSM TMR0 CLC1 TMR1 HLT/ TMR4 CCP MOSFET DRIVER CLC2 TMR3 DAC PRG C PIC16F1769 Microcontroller Resistors for Difference Amplifier Peak Detector Burst Signal Transmitter Received Signal Receiver OPA2 OPA1 CMP1 Ultrasonic Range Detection

Upload: others

Post on 13-Jul-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536Ultrasonic Range Detection

INTRODUCTION

This application note describes the use of PIC®

microcontroller Core Independent Peripherals (CIP) inultrasonic range detection applications. The featureperipherals of Microchip’s PIC16F176X family enablethe ultrasonic range detection to calculate the distancetraveled by the ultrasonic signal with minimumintervention from its Central Processing Unit (CPU).

BLOCK DIAGRAM

Figure 1 shows the block diagram of an ultrasonicrange detection based on the PIC16F176X familymicrocontroller. The CIPs used in the design are asfollows:

• Data Signal Modulator (DSM)• Configurable Logic Cell (CLC)• Hardware Limit Timer (HLT)• Comparator (CMP)• Operational Amplifier (OPA)

Combining the CIPs with other on-chip peripherals,such as I/O ports, Timers, Pulse-Width Modulation(PWM), Capture Compare PWM (CCP) and Digital-to-Analog Converter (DAC), brings the intelligence to thewhole system.

The interconnection of these peripherals significantlyreduces the component count needed to implement anultrasonic range detection application. Refer toAppendix C: “Ultrasonic Range DetectionSchematic” for the detailed schematic diagram.

FIGURE 1: BLOCK DIAGRAM

Author: Kristine Angelica SumagueKeith CurtisAnthony StramMicrochip Technology Inc.

PWM3DSM

TMR0CLC1

TMR1

HLT/TMR4

CCP

MOSFET DRIVER

CLC2

TMR3

DAC

PRG

C

PIC16F1769 Microcontroller

Resistors for

Difference Amplifier

Peak Detector

Burst SignalTransmitter

Received Signal

Receiver

OPA2

OPA1CMP1

2013-2016 Microchip Technology Inc. DS00001536B-page 1

Page 2: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

ULTRASONIC RANGE DETECTION OVERVIEW

FIGURE 2: ULTRASONIC RANGE DETECTION OPERATION

Figure 2 depicts how the ultrasonic range detectiontransmits and receives the ultrasonic pulse. The ultra-sonic pulse train which contains multiple pulses thatrun in ultrasonic frequency is generated during transmitperiod. Before detecting the reflected pulse, a delaybetween transmit and receive is necessary to damp outthe ringing produced during the transmission of ultra-sonic pulse. Upon transmitting the ultrasonic pulse, themicrocontroller starts its timer peripheral and capturesthe timer value when the reflected pulse is detected.This captured timer value is equivalent to the traveleddistance of the ultrasonic pulse.

ULTRASONIC TRANSDUCER BACKGROUND

Figure 3 shows the equivalent circuit of an ultrasonictransducer. It acts as a capacitive load, but because ofinductive and capacitive aspects, it is tuned to a 40 kHzresonant frequency. The transmitter is tuned formaximum output while the receiver is tuned formaximum voltage output at an incoming 40 kHz signal.This has an attenuating filtering effect on all otherfrequencies and is useful in eliminating noise whenamplifying the received signal.

FIGURE 3: THE EQUIVALENT CIRCUIT OF AN ULTRASONIC DEVICE

CLC1

DSM

CLC2CAPTUREINDICATOR

HLT PERIOD CCP CAPTURED VALUE

PEAK DETECTOROUTPUT

VOLTAGE REFERENCE

OPA1 OUTPUT

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

DS00001536B-page 2 2013-2016 Microchip Technology Inc.

Page 3: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

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 4. Therefore, a delay beforethe receiver is needed to ensure that the ringing hasdamped out, and any signal received is that of areflected pulse. The amount of time required for theringing to damp out determines the minimumdetectable distance of the receiver.

FIGURE 4: ULTRASONIC DEVICE

THEORY OF OPERATION

FIGURE 5: ULTRASONIC RANGE DETECTION SCHEMATIC

Figure 5 shows the schematic of an ultrasonic rangedetection. The whole circuit is controlled by thePIC16F1769 microcontroller, using its on-chipperipherals. 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. This pulse is reflected by any object ofgreater density than air, and part of the emitted pulsereturns to the receiver. The received signal is amplified

for better detection. When the signal has beendetected, the round trip travel time is measured andconverted to distance via the speed of sound.

Input

Output

Output

Ringing time

Ringing timeShort Ringing

Long Ringing

Reflected signal

LM340MP-5.0

10 uF 0.1 uF

VIN VOUT

GN

D

1

2 3

0.1 uF

+ + +

132

VDCPWR SPLY

+

- PWR SPLY TERMINAL

VINPUTVDD

SLIDE SW

PIC16F1769Microcontroller

1

2

3

4

5

6

7

8

9

10 11

12

13

14

15

16

17

18

19

20

OPA2OUT

C1IN+

OPA1N+

OPA1N-

OPA1OUT

C1IN-

CLC1OUT

TX

Indicator

DACOUT

MD1OUT

CLC2OUT

39 uF39 uF

Logic-Controlled

Load Driver

1

2

3

4

8

7

6

5MD1OUT

CLC1OUT

VINPUT

TRANSMITTER

OPA1N+

OPA1N-

OPA1OUTRECEIVER

50

50

510K

510K

1N4148

0.1 uF 5.1K

MCLR

VDD

C1IN+

DACOUT

10 uF

+

LED

510K

MCLR

ICSPDAT

ICSPCLK

VDD

1

23

4

5

6

0.1 uF

VDD

1

23

4

5

6TX

PICKIT 3

2013-2016 Microchip Technology Inc. DS00001536B-page 3

Page 4: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION

The interconnection of the peripherals for ultrasonicrange detection application is shown in Figure 6. ThePWM peripheral generates the specified frequency todrive the ultrasonic transmitter. This PWM is tied to thecarrier input while a CLC1 peripheral is tied to the mod-ulator input of the DSM peripheral. The CLC1 is config-ured to operate as an SR flip-flop with its set and resetinputs connected to Timer3 and Timer0, respectively.The SR flip-flop from the CLC1 connects and discon-nects the PWM to the output pin through the DSM togenerate a pulse of ultrasonic sound. The CLC1 outputis also connected to the HLT peripheral and to the resetinput of the CLC2 SR flip-flop. The HLT operates as aone-shot timer and is tied to the CLC2 set input. TheCLC2 output is connected to the Timer1 gate to enablethe timer once the HLT one-shot times out. When thesignal is received and amplified by the OPA1, the peakdetector will be compared to a receiver reference volt-age. This receiver reference voltage is generated bythe PRG connected to a unity gain OPA2. The peakdetector and the unity gain OPA2 output are tied to thepositive and negative inputs of the CMP1, respectively.The CMP1 output is tied to the CCP to generate a cap-ture event. The captured time by the CCP will be thepart of the round trip time of the ultrasonic pulse.

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 theultrasonic transmitter while a Timer0 peripheralinterrupt-on-overflow can be used to create the timebase for the output signal. (See Appendix D: “TimerFlowchart Implementation for Ultrasonic RangeDetection” for more detail on how this isaccomplished). However, this type of control willrequire a lot of firmware coding compared to theinterconnection of CIPs that have no softwareoverhead.

PWM3DSM

TMR0CLC1

TMR1

HLT/TMR4

CCP

CLC2

TMR3

DAC

PRG

PIC16F1769 Microcontroller

OPA2

C2

OPA1

CMP1

CH

MOD CL

OUT

R

SQ

R

S

Q

RS

FS

-+

-+

-

+

R5 C1D1

Data input

OUT

OUT

Enable

Logic-ControlledLoad Driver

Transmitter

R1

R2

R4R3ReceiverDifference Amplifier

Receiver Reference

Transmitter signal

Receive Signal Timer

Peak Detector

DS00001536B-page 4 2013-2016 Microchip Technology Inc.

Page 5: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE 7: 40 kHz ULTRASONIC TRANSMITTER CONFIGURATION

Figure 7 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. When the CLC1 is low, the PWM isdisabled on the DSM output and when the CLC1 ishigh, the PWM is enabled on the DSM output. Thisimplies that the DSM effectively modulates the PWMpulses with CLC1 output. The CLC1 is periodically setby the Timer3 and being reset by the Timer0 when thespecified number of PWM pulses has been 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 distance ofthe ultrasonic ranging.

As shown in Figure 8, 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 pulse isavoided.

FIGURE 8: DEAD TIME BETWEEN TRANSMITTER AND RECEIVER

RECEIVING AN ULTRASONIC PULSE

As the ultrasonic signal propagates in the air during thetransmission, the intensity of the signal is decreasingwith distance due to air absorption and beamspreading. Thus, the returning sound wave obtained bythe receiver 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 9. 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 R2and R4 and resistors R1 and R3. The ultrasonicreceiver acts like a tuned high Q filter, thus, thedifference amplifier effectively amplifies the filteringeffect of the receiver.

PWM

CLC1

40 kHz

TMR3 interrupt

TMR0 interrupt

DSMOUTPUT

PWM3

DSMTMR0

CHMOD

CLCLC1

R

S

Q

TMR3

PIC16F1769

CLC1

HLT

CLC2

HLT period

COMP1+ input connects to GND

COMP1+ input connects to output pin

2013-2016 Microchip Technology Inc. DS00001536B-page 5

Page 6: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE 9: 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 C1 and resistorR5, as shown in Figure 10. When the input signal onthe peak detector is rising, D1 is forward-biased and C1charges rapidly to the difference of VAMP and D1voltage drop. When the input signal is falling, D1becomes reverse-biased and C1 stored chargereleases slowly through R5. The discharging of C1continues until the VAMP becomes greater than the C1charge. When VAMP is greater than the voltage acrossC1, D1 conducts again and the process is repeated.The values of C1 and R5 should be carefully chosen toavoid significant levels of ripple or too much attenuationon the peak detector output.

FIGURE 10: PEAK DETECTOR

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, an external capacitor C2 iscoupled to the OPA2 output. The value of C2 must belarge enough to have a sufficient falling ramp voltagefor better receiver sensitivity.

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 of

the Timer1 Counter register pair (TMR1H and TMR1L),respectively. This captured value will be part of theround trip time in the form of counts of the ultrasonicpulse.

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 B: “Variables Used in the Firmware”.

R1

R2

R4

VOUTVIN-

VIN+

R3

R1 = R3

R2 = R4

VOUT = (R1 / R2) x (VIN+ - VIN-)

OPA1

DAC

PIC16F1769

R5C1

D1

VAMP VCOMP+

VCOMP+

VAMP

too much attenuation

Significant level of ripple

DS00001536B-page 6 2013-2016 Microchip Technology Inc.

Page 7: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

EQUATION 1: DISTANCE FORMULA

EXAMPLE 1: CODE EXAMPLE FOR DISTANCE COMPUTATION

The calculated distance is displayed in the user’s com-puter through the Tera Term application. EUSARTperipheral is initialized to establish the communicationbetween the Tera Term and the microcontroller.Figure 11 shows the example of the distance calcu-lated by the ultrasonic range detection.

FIGURE 11: CALCULATED DISTANCE

Dis cetanCCP captured value

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

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

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

2013-2016 Microchip Technology Inc. DS00001536B-page 7

Page 8: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

ULTRASONIC RANGING DETECTION FIRMWARE

FIGURE 12: FIRMWARE FLOWCHART

Figure 12 shows the flowchart of the ultrasonic rangedetection firmware. During system start-up, thefirmware initializes the peripherals and the connectionamongst each other. After the peripherals areinitialized, the PRG ramp output is enabled, the DACvalue is set and the interrupts are enabled. Thefirmware waits until a signal is detected, which sets thedisplay_result variable. When thedisplay_result is set, the distance traveled by thereturned signal is calculated. The calculated result isdisplayed in the computer through EUSART interface.

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 sets the receiver indicator to low,enables the Timer4 HLT and reloads the Timer3value.

2. Timer0 Interrupt – Executed when the Timer0overflows. The Timer0 value increments everyPWM pulse detected at the Timer0 Clock Input(T0CKI) pin. When the Timer0 Interrupt occurs,it resets the display_result variable, startsthe Timer3 and reloads Timer0 and Timer1value.

3. CLC2 Interrupt – The rising interrupt of theCLC2 connects the CMP1 positive input toC1IN0+ output pin to enable the detection of thereceived signal. This interrupt occurs when theHLT one-shot times out.

4. CMP1 Interrupt – When the ultrasonic pulse isreceived, the CMP1 interrupts. When thishappens, the CMP1 positive input is connectedto GND to disable the detection. Thedisplay_result variable and receiverindicator are also set to calculate and display themeasured distance.

START

Initialization(Timers, CLCs, PWM, DSM, I/O, Comparator, EUSART,

OPA)

Is display_result

equalto 1?

Calculate distance

No

Yes

COMP1 Interrupt

1. Connect COMP1 positive input to GND2. display_result = 13. Set indicator to high4. Clear interrupt flag

TMR0 Interrupt

1. display_result = 02. Start Timer33. Reload Timer0 value4. Reload Timer1 value5. Clear interrupt flag

CLC1 Interrupt

1.Start Timer4 HLT2. Clear interrupt flag

TMR3 Interrupt

1. Set indicator to low2. Reload Timer3 value3. Clear interrupt timer

CLC2 Interrupt

1.Connect COMP1 positive input to C1IN0+2. Clear interrupt flag

main.c interrupts

Start PRG ramp outputSet DAC value

Enable Interrupt

DS00001536B-page 8 2013-2016 Microchip Technology Inc.

Page 9: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

Notice that after the initialization, the calculation of thereturned ultrasonic pulse is dependent on the ISRs. Itis because the CIPs, which are integrated to control theoperation of the ultrasonic range detection, perform thetasks independently. As a result, the complexity of thefirmware is reduced and the core is only requiredduring the ISRs.

All peripherals used in the firmware are configured andinitialized using the MPLAB® Code Configurator(MCC). Appendix A: “MPLAB® Code Configurator(MCC) Peripheral Initialization” provides the proce-dures on how the peripherals are initialized using 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, longer distances can be traveled by theultrasonic pulse that can still be detectable by thereceiver.

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 cutout between the devices on the board willhelp to minimize this leakage. Ultrasonic transducersare often mounted using rubber or silicon to limit theamount of leaked ultrasonic signal to/from thesurrounding material.

CONCLUSION

This application note describes a PIC microcontroller-based solution of getting the distance of 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.

2013-2016 Microchip Technology Inc. DS00001536B-page 9

Page 10: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

APPENDIX A: MPLAB® CODE CONFIGURATOR (MCC) PERIPHERAL INITIALIZATION

In this section, the MPLAB® Code Configurator (MCC)is utilized to easily configure the peripherals used inthis ultrasonic ranging detection application. The MCCis a user friendly plug-in tool for MPLAB®X IDE which

generates drivers for controlling and driving peripheralsof PIC® microcontrollers, based on the settings andselections made in its Graphical User Interface (GUI).Refer to the “MPLAB® Code Configurator User’sGuide” (DS40001725) for further information on how toinstall and set up the MCC in MPLAB® X IDE.

The following figures will provide a guide on how toconfigure the PIC16F176X family peripherals in thisapplication note using MCC.

FIGURE A-1: SYSTEM MODULE

FIGURE A-2: TIMER2 CONFIGURATION

DS00001536B-page 10 2013-2016 Microchip Technology Inc.

Page 11: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-3: PULSE-WIDTH MODULATION (PWM3) CONFIGURATION

FIGURE A-4: CONFIGURABLE LOGIC CELL (CLC1) CONFIGURATION

2013-2016 Microchip Technology Inc. DS00001536B-page 11

Page 12: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-5: DATA SIGNAL MODULATOR (DSM) CONFIGURATION

FIGURE A-6: TIMER0 CONFIGURATION

DS00001536B-page 12 2013-2016 Microchip Technology Inc.

Page 13: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-7: TIMER4 CONFIGURATION

FIGURE A-8: CONFIGURABLE LOGIC CELL (CLC2) CONFIGURATION

2013-2016 Microchip Technology Inc. DS00001536B-page 13

Page 14: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-9: COMPARATOR (CMP1) CONFIGURATION

FIGURE A-10: OPERATIONAL AMPLIFIER (OPA1) CONFIGURATION

DS00001536B-page 14 2013-2016 Microchip Technology Inc.

Page 15: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-11: FIXED VOLTAGE REFERENCE (FVR) CONFIGURATION

FIGURE A-12: TIMER3 CONFIGURATION

2013-2016 Microchip Technology Inc. DS00001536B-page 15

Page 16: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-13: TIMER1 CONFIGURATION

FIGURE A-14: PROGRAMMABLE RAMP GENERATOR (PRG) CONFIGURATION

DS00001536B-page 16 2013-2016 Microchip Technology Inc.

Page 17: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-15: OPERATIONAL AMPLIFIER (OPA2) CONFIGURATION

FIGURE A-16: CAPTURE COMPARE PWM (CCP1) CONFIGURATION

2013-2016 Microchip Technology Inc. DS00001536B-page 17

Page 18: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-17: DIGITAL-TO-ANALOG CONVERTER (DAC) CONFIGURATION

FIGURE A-18: ENHANCED UNIVERSAL SYNCHRONOUS ASYNCHRONOUS RECEIVER TRANSMITTER (EUSART) CONFIGURATION

DS00001536B-page 18 2013-2016 Microchip Technology Inc.

Page 19: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-19: PIN MANAGER

2013-2016 Microchip Technology Inc. DS00001536B-page 19

Page 20: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

FIGURE A-20: PIN MODULE

After configuring all the peripherals, click the GenerateCode button in the top left corner of the center panel.This will generate a main.c file to the projectautomatically. It will also initialize the module and leavean empty while loop for custom code entry.

DS00001536B-page 20 2013-2016 Microchip Technology Inc.

Page 21: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

APPENDIX B: 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 B-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

DACOffset This variable sets the offset value for the difference amplifier. 60

2013-2016 Microchip Technology Inc. DS00001536B-page 21

Page 22: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN

1536

DS

00

00

15

36

B-p

ag

e 2

2

20

13

-20

16

Micro

chip

Te

chn

olo

gy In

c.

P-5.0

0.1 uF

VOUT

GN

D

1

3

+

VDD

Logic-ontrolled

oad Driver

8

7

6

5

CLC1OUT

VINPUT

TRANSMITTER

OPA1N+

OPA1N-

RECEIVER50

50

510K

510K

8

DACOUT

10 uF

+

LED

510K

APPENDIX C: ULTRASONIC RANGE DETECTION SCHEMATIC

FIGURE C-1: SCHEMATIC

LM340M

10 uF

VIN2

0.1 uF

+ +

132

VDCPWR SPLY

+

- PWR SPLY TERMINAL

VINPUT

SLIDE SW

PIC16F1769Microcontroller

1

2

3

4

5

6

7

8

9

10 11

12

13

14

15

16

17

18

19

20

OPA2OUT

C1IN+

OPA1N+

OPA1N-

OPA1OUT

C1IN-

CLC1OUT

TX

Indicator

DACOUT

MD1OUT

CLC2OUT

39 uF39 uF

CL

1

2

3

4MD1OUT

OPA1OUT

1N414

0.1 uF 5.1K

MCLR

VDD

C1IN+

MCLR

ICSPDAT

ICSPCLK

VDD

1

23

4

5

6

0.1 uF

VDD

1

23

4

5

6TX

PICKIT 3

Page 23: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

2

01

3-2

01

6 M

icroch

ip T

ech

no

log

y Inc.

DS

00

00

15

36

B-p

ag

e 2

3

AN

1536

AP TECTION

FIG

ble ‘i’ulses

F1ne low(T0IF) (T0IE)

nd

ISR

Load TMR0 with 0xF3

Toggle USdrive pins

Decrement ‘i’

‘i’ = 0?

Clear T0IE

Return From Interrupt

NO

YES

PENDIX D: TIMER FLOWCHART IMPLEMENTATION FOR ULTRASONIC RANGE DE

URE D-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 OverflowCount

-Clear TMR1IF

8Overflows?

-Turn off Timer1-Store Timer1 count-Turnoff Comparator

Return

YES

YES

YESYES

YES

NO

NONO

NONO

SendPulse()

-Copy ‘numPulses’ to varia-Double number of output p

-Preload Timer0 with 0x-Initialize USdrive pin high o-Clear Timer0 Interrupt Flag

-Set Timer0 Interrupt Enable

TOIE set?

Output last pulse

Set output pins to grou

Return

YES

NO

Page 24: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

AN1536

NOTES:

DS00001536B-page 24 2013-2016 Microchip Technology Inc.

Page 25: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

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-2016 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, dsPIC, FlashFlex, flexPWR, Heldo, JukeBlox, KeeLoq, KeeLoq logo, Kleer, LANCheck, LINK MD, MediaLB, MOST, MOST logo, MPLAB, OptoLyzer, PIC, PICSTART, PIC32 logo, RightTouch, SpyNIC, SST, SST Logo, SuperFlash and UNI/O 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.

Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BodyCom, chipKIT, chipKIT logo, CodeGuard, dsPICDEM, dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial Programming, ICSP, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, MiWi, motorBench, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, PureSilicon, RightTouch logo, REAL ICE, Ripple Blocker, Serial Quad I/O, 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 trademarks 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-2016, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.

ISBN: 978-1-5224-0511-5

DS00001536B-page 25

Page 26: Ultrasonic Range Detection App. Note · DS00001536B-page 4 2013-2016 Microchip Technology Inc. FIGURE 6: CIP CONNECTION FOR ULTRASONIC RANGE APPLICATION The interconnection of the

DS00001536B-page 26 2013-2016 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

ClevelandIndependence, OH Tel: 216-447-0464 Fax: 216-447-0643

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-5453

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

New York, NY Tel: 631-435-6000

San Jose, CA Tel: 408-735-9110

Canada - TorontoTel: 905-673-0699 Fax: 905-673-6509

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 - 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-5407-5533 Fax: 86-21-5407-5066

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-7828

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

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

Germany - DusseldorfTel: 49-2129-3766400

Germany - KarlsruheTel: 49-721-625370

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

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

Italy - VeniceTel: 39-049-7625286

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

Poland - WarsawTel: 48-22-3325737

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

Sweden - StockholmTel: 46-8-5090-4654

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

Worldwide Sales and Service

07/14/15