Microchip | The Embedded Control Solutions Company Register Login
Browse All
Microchip Technology
 368 Code Snippets

Ultrasonic Range & Proximity Detection

Microchip Technology

Check out this project's MPLAB Xpress Webpage to view the complete code example along with a detailed step by step write-up and description, or visit the PIC16F1769 Device Product Page for more information.

About this Code Example










This Xpress Code Example shows the use of PIC® microcontroller Core Independent Peripherals (CIP) in ultrasonic range and proximity detection applications. The flexibility of the featured peripherals of Microchip’s PIC16F176X family of 8-bit microcontrollers enable the ultrasonic range detection circuit to calculate the distance traveled by the ultrasonic signal with minimum intervention from its CPU. It also allows ultrasonic proximity detection of a person or an obstruction in an area with minimal software overhead.

Related Application Notes

  • AN1536 - Ultrasonic Range Detection
  • AN2281 - Ultrasonic Proximity Detection

Functions and Peripherals

Transmission and reception of ultrasonic frequencies is made possible by using multiple Core Independent Peripherals (CIPs) that include:

  • Configurable Logic Cells (CLCs)
  • Hardware Limit Timers (HLTs)
  • Data Signal Modulator (DSM)
  • Timers (TMR)
  • Pulse Width Modulator (PWM)
  • Analog-to-Digital Converter (ADC)
  • Digital-to-Analog Converter (DAC)
  • Op Amps (OPAs)

Application Highlights

  • Timers, CLC, and DSM peripherals are used to generate 40kHz waveform for ultrasonic transducer.
  • ADC, DAC, timers, CLCs, and op amp peripherals are used in reception of reflected signal, automatic gain control, and distance measurement.
  • Core is utilized only in starting a measurement, conversion to inch value, and display of range in inches or to determine the proximity of an obstacle.

Block Diagram

MPLAB Code Configurator (MCC) Setup

This project uses MPLAB Code Configurator (MCC) to set up the various CIPs required for this project.

Timer 0 Setup

To set up Timer 0 using MCC, in the TMR0 config window, select FOSC/4 as the clock source with 1:4 prescaler and 724 us period.

Timer 1 Setup

For Timer 1, simply enable the timer and the timer interrupt in the TMR1 window.

Timer 2 Setup

For Timer 2, select FOSC/4 as the clock source and set the timer period to 25 us.

Timer 3 Setup

Enable the timer and timer interrupt. With FOSC/4 as the clock source and 1:8 prescaler, set the timer period to 100 ms.

Timer 4 Setup

Select FOSC/4 as the clock source and 1:4 prescaler. Enable clock sync and timer interrupt. Set timer period to 220 us. Set the External Reset Source to CLC1 output (LC1_out). Select the appropriate options as shown to operate the timer in "One shot" mode where the timer "Starts at falling edge and resets on TMR4_ers=1".

Timer 6 Setup

Select FOSC/4 as the clock source and 1:8 prescaler. Set timer period to 1.8 ms. Set the External Reset Source to CLC2 output (LC2_out). Select the appropriate options as shown to operate the timer in "Monostable" mode where the timer "Starts on rising edge on TMR6_ers".

ADC Setup

Enable ADC and select FOSC/4 as the clock source. Select TMR1_overflow as the Auto-conversion trigger and ensure that the ADC result is right aligned.

CLC1 Setup

Enable the CLC in "SR Latch" mode and set the CLC1 in the configuration shown in the diagram below.

CLC2 Setup

Enable the CLC in "SR Latch" mode. Enable the CLC Interrupt with Rising Interrupt enabled. Set the CLC2 in the configuration shown in the diagram below.

CLC3 Setup

Enable the CLC in "SR Latch" mode and set the CLC3 in the configuration shown in the diagram below.

CMP1 Setup

Enable the comparator in Synchronous Mode. Enable the Comparator Hysteresis. Set the positive and negative inputs to C1IN1+ and CIN1- respectively.

DSM1 Setup

Enable the Modulator with CLC1 output (LC1_out) as the Modulation Source. Select PWM3_out as the High Carrier (synchronized) and LC1_out as the Low Carrier.

FVR Setup

Enable the FVR with 1x as the FVR_buffer2 Gain.

OPA1 Setup

Enable OPAMP. Ensure that the positive and negative channel are set to OPA1IN0+ and OPA1IN0- respectively.

OPA2 Setup

In order to set up OPA2, select the "Registers" view mode tab. Enable the OPA2 by setting the OPA2EN bit. Select OPA_Output setting for bit OPA2UG. Select PRG1_OUT as the setting for PCH bits.

PRG1 Setup

Enable the PRG1 module with FVR_buffer1 as the voltage input source. Select PRG1R as the ramp rising timing source and PRG1F as the ramp falling timing source. Set the Falling event polarity to active_low.

PWM3 Setup

Enable the PWM3 with Timer 2 as the timer source. Ensure that the duty cycle is 50%.

MSSP Setup

Enable MSSP in SPI Master mode. Select the clock polarity to "Idle:High, Active:Low".

Pin Manager Setup

Assign the appropriate pins using the Pin Module and Pin Manager as shown below.

Hardware Used

A custom board is used to demonstrate this application. The schematics and layout of this board can be downloaded from Circuit Maker.

Running the Demo

Programming the Device

  1. Generate the code for CIPs using MCC with the settings shown above.
  2. After the MCC is done generating the code for the CIPs, include the following files in your project as shown. These files are already included in the current project.


display.h display.c

Proximity.h Proximity.c

Range.h Range.c

  1. In ccp1.c file generated by MCC, include the define.h file (#include "../define.h") and add the following lines of code to the CCP1_CaptureISR() function:
    //detection found, set flag to display result in rangeDetection() function
    display_result = true;
    CM1PSEL = 0x0F;
  1. In clc2.c file generated by MCC, include the tmr1.h file (#include "tmr1.h") and add the following lines of code to the CLC2_ISR() function:
    CM1PSEL = 0x01; //CxVP connects to pin
  1. Edit the main.c file generated by MCC to include the following code:
#include "mcc_generated_files/mcc.h"
#include "display.h"
#include "Range.h"
#include "Proximity.h"

//isRange flag used to determine demo mode
//isRange = true -> Range Demo
//isRange = false -> Proximity Demo
bool isRange = true;

void RB7_ISR(void)
    if (PORTBbits.RB7 == 0)
        isRange = true;
        isRange = false;

void main(void) {
    // initialize the device

    oled_putString("Ultrasonic Demo", 0, 0);
    while (1) {
        // Add your application code
        if (isRange)
  1. Connect the board to the computer using an appropriate dev tool like PICkit 4 or Snap.
  2. Click on "Make and Program Device" button to program the demo board.


  1. Make sure 9V power supply is connected.
  2. Turn power on at switch on PCB.
  3. The display will show a range to an object or “No Detection” if it did not get a range.
  4. Point the sensors at an object within a few feet of the demo and a range should be shown on the display.
  5. If the demo cannot get a range do to object size/range from sensor or its sound absorption properties of the object then the display will show “No Detection”.


  1. If the demo does not display any information check power is plugged in.
  2. If the demo still does not show any information make sure it is turned on, otherwise cycle power.
  3. An object can be too close or too far to sense so move the object towards and away from demo until a range is shown.
  4. An object could also be angled away from the demo to cause a “No Detection” condition.
  5. Currently, clothing absorbs most of the ultrasonic energy so many times the demo will read “No Detection”.


This Xpress Example shows how easy it is to set up and program a device using MCC and also the complex capabilities of various CIPs available on Microchip's 8-bit PIC16F/PIC18F microcontrollers.



Release History

  • Nov 8, 2018

    Version: 1.0.0

    Initial Release

Download Contact the Developer

*Required Fields

  • Current Version:1.0.0
  • Created:Nov 8, 2018
  • Updated:Nov 29, 2018
  • Downloads:1223
  • C Compiler:XC8 (v1.45)
  • Development Tools:Curiosity High Pin Count (HPC) Development Board
  • Supported Devices:PIC16F1769

Corporate News


Stay Connected

Stay up to date with the latest news from Microchip Technology.