0
0
Power-electronicsHow-ToBeginner · 4 min read

How to Interface Ultrasonic Sensor HC-SR04 in Embedded C

To interface the HC-SR04 ultrasonic sensor in Embedded C, trigger the sensor by sending a 10µs pulse on the TRIG pin, then measure the duration of the echo pulse on the ECHO pin using a timer. Calculate distance by multiplying the pulse duration by the speed of sound divided by two.
📐

Syntax

The basic steps to interface the HC-SR04 sensor are:

  • Set TRIG pin as output to send a trigger pulse.
  • Set ECHO pin as input to read the echo pulse duration.
  • Send a 10 microsecond pulse on TRIG to start measurement.
  • Measure the time ECHO pin stays high using a timer.
  • Calculate distance using the formula: distance = (time * speed_of_sound) / 2.
embedded_c
void triggerSensor() {
    TRIG_PIN = 1;          // Set TRIG pin HIGH
    delayMicroseconds(10); // Wait 10 microseconds
    TRIG_PIN = 0;          // Set TRIG pin LOW
}

unsigned int readEcho() {
    while(!ECHO_PIN);      // Wait for ECHO pin to go HIGH
    startTimer();          // Start timer
    while(ECHO_PIN);       // Wait for ECHO pin to go LOW
    stopTimer();           // Stop timer
    return getTimerValue(); // Return pulse duration
}
💻

Example

This example shows how to trigger the HC-SR04 sensor, measure the echo pulse duration, and calculate the distance in centimeters.

embedded_c
#include <xc.h>
#define TRIG_PIN LATBbits.LATB0
#define ECHO_PIN PORTBbits.RB1

void delayMicroseconds(unsigned int us) {
    while(us--) {
        __delay_us(1); // Built-in delay function for 1 microsecond
    }
}

unsigned int readEchoPulse() {
    unsigned int count = 0;
    while(!ECHO_PIN); // Wait for ECHO to go HIGH
    while(ECHO_PIN) {
        __delay_us(1);
        count++;
        if(count > 30000) break; // Timeout to avoid infinite loop
    }
    return count;
}

int main() {
    unsigned int pulse_duration;
    float distance_cm;

    TRISBbits.TRISB0 = 0; // TRIG as output
    TRISBbits.TRISB1 = 1; // ECHO as input

    while(1) {
        TRIG_PIN = 0;
        delayMicroseconds(2);
        TRIG_PIN = 1;
        delayMicroseconds(10);
        TRIG_PIN = 0;

        pulse_duration = readEchoPulse();

        // Speed of sound = 34300 cm/s
        // Distance = (pulse_duration * 0.0343) / 2
        distance_cm = (pulse_duration * 0.0343f) / 2.0f;

        // Use distance_cm as needed
        __delay_ms(500);
    }
    return 0;
}
⚠️

Common Pitfalls

  • Not setting TRIG pin LOW before sending pulse: This can cause false triggers.
  • Ignoring timer overflow or timeout: The echo pulse might never come, causing infinite loops.
  • Incorrect pin direction setup: TRIG must be output, ECHO must be input.
  • Not accounting for speed of sound variations: Temperature affects accuracy but can be ignored for basic use.
embedded_c
/* Wrong way: No timeout, may hang if no echo */
while(ECHO_PIN); // waits forever if no echo

/* Right way: Add timeout counter */
unsigned int count = 0;
while(ECHO_PIN) {
    __delay_us(1);
    count++;
    if(count > 30000) break; // timeout
}
📊

Quick Reference

Key points to remember when using HC-SR04 with Embedded C:

  • Trigger pulse: 10 microseconds HIGH on TRIG pin.
  • Measure echo pulse width on ECHO pin.
  • Distance (cm) = (pulse duration in microseconds * 0.0343) / 2.
  • Use timer or delay loops to measure pulse width accurately.
  • Set TRIG as output and ECHO as input pins.

Key Takeaways

Send a 10µs pulse on TRIG pin to start measurement.
Measure the duration of the HIGH pulse on ECHO pin using a timer or delay loop.
Calculate distance using the formula: distance = (time * speed_of_sound) / 2.
Always set TRIG as output and ECHO as input pins correctly.
Implement timeout to avoid infinite waiting if no echo is received.