HC-SR04 Ultrasonic Distance Sensor Configuration
HC-SR04 Ultrasonic Distance Sensor Configuration
1. Feature Overview
The HC-SR04 is a commonly used ultrasonic distance measuring module that measures target distance by emitting 40KHz ultrasonic pulses and receiving echoes. FastBee implements automatic initialization, pulse transmission/reception, and distance calculation through the SensorDriver::readUltrasonic() method.
Technical Specifications
| Parameter | Value |
|---|---|
| Operating Voltage | 5V (some modules support 3.3V) |
| Operating Frequency | 40KHz |
| Measurement Range | 2cm ~ 400cm |
| Measurement Accuracy | ยฑ3mm |
| Trigger Signal | 10ฮผs TTL pulse |
| Echo Signal | High-level duration proportional to distance |
| Minimum Read Interval | 100ms |
Working Principle
- Trig pin sends a โฅ10ฮผs high-level trigger pulse
- The module automatically emits 8 cycles of 40KHz ultrasonic pulses
- Echo pin outputs high level, duration = sound wave round-trip time
- Distance calculation:
distance(cm) = duration(ฮผs) ร 0.034 / 2
If readings consistently timeout or fluctuate, check physical conditions according to the diagram first: whether Trig/Echo are swapped, whether Echo level has been converted to 3.3V, whether target distance exceeds the 2cm blind zone, and whether the reflection surface is flat enough.
Features
- 100ms minimum read interval caching
- Timeout protection (30ms, approximately 510cm)
- Range validation (2~400cm effective)
- Returns old cached value within 10 seconds on read failure
2. Wiring Instructions
HC-SR04 Module ESP32
โโโโโโโโโโโโโโโ
โ VCC โโโโโโโโโโ 5V
โ Trig โโโโโโโโโโ GPIO4 (any output pin)
โ Echo โโโโโโโโโโ GPIO27 (any input pin)
โ GND โโโโโโโโโโ GND
โโโโโโโโโโโโโโโ
Notes:
- HC-SR04 requires 5V power, Echo output is 5V level
- ESP32 GPIO tolerates 3.3V; if using a 5V module, add a voltage divider on the Echo line:
Echo โโ 1Kฮฉ โโโฌโโ 2Kฮฉ โโ GND
โ
โโโ ESP32 GPIO (approximately 3.3V)
- Some newer HC-SR04 modules (e.g., HC-SR04P) support 3.3V power and 3.3V logic levels
- Trig and Echo cannot use the same pinRecommended Pins:
- Trig: GPIO4, GPIO5, GPIO16, GPIO17 (output pins)
- Echo: GPIO27, GPIO26, GPIO25, GPIO33 (input pins)
3. Configuration Methods
Method 1: Web Interface Configuration (Recommended)
Verify Trig/Echo pins before saving HC-SR04. The Echo return level must match ESP32 input voltage range.
Step 1: Navigate to Peripheral Management Page
- Open a browser and access the ESP32 IP address
- After logging in, click Peripheral Configuration in the left menu
Step 2: Add Ultrasonic Sensor Peripheral
Click the Add Peripheral button
Fill in the configuration:
Field Value Description Peripheral ID ultrasonic_01Unique identifier Name Ultrasonic DistanceDisplay name Peripheral Type Generic Sensor (type: 38) Ultrasonic driver Trig Pin 4Trigger pin (output) Echo Pin 27Echo pin (input) Click Save
Step 3: Verify Configuration
- Find the newly added peripheral in the peripheral list
- Click the Enable toggle
- View real-time distance data (cm)
โ ๏ธ Important: 5V module Echo pins require a voltage divider (5Vโ3.3V)
Method 2: JSON Configuration File Import
Add the following configuration to the peripherals array in data/config/peripherals.json:
The ultrasonic sensor uses SENSOR (type ID=38) type, pinCount=2, pins[0]=Trig, pins[1]=Echo.
{
"id": "ultrasonic_01",
"name": "Ultrasonic Distance",
"type": 38,
"enabled": false,
"pinCount": 2,
"pins": [4, 27, 255, 255, 255, 255, 255, 255],
"params": {}
}Field Description
| Field | Meaning | Values |
|---|---|---|
| type | Peripheral type | 38 (SENSOR) |
| pins[0] | Trig trigger pin | Valid output GPIO |
| pins[1] | Echo return pin | Valid input GPIO |
| params | No dedicated parameters currently required | Sampling interval controlled by peripheral execution rules, recommended โฅ100ms |
4. Peripheral Execution Linkage
Web Interface Configuration Steps
Create Timed Collection Rule
- Switch to the Peripheral Execution Management tab
- Click the Add Rule button
- Configure the timer trigger:
- Trigger Type: Timer Trigger
- Execution Interval: 5 seconds
- Add action:
- Action Type: Sensor Read
- Target Peripheral: ultrasonic_01
- Data Field: distance
- Enable Report Data After Execution
- Click Save
Create Too-Close Alarm Rule
- Create a new rule
- Configure event trigger:
- Trigger Type: Event Trigger
- Event ID: ds:ultrasonic_01_distance
- Comparison Operation: Less Than
- Comparison Value: 20 (cm)
- Add actions:
- Action 1: Buzzer alarm
- Action Type: High Level
- Target Peripheral: buzzer_01
- Action 2: Trigger device event
- Action Type: Trigger Event
- Event ID: obstacle_detected
- Action 1: Buzzer alarm
- Click Save
๐ก Tip: Event ID format is
ds:{peripheralId}_{fieldName}
JSON Configuration Examples
Distance Timed Collection Rule
{
"id": "exec_ultrasonic_read",
"name": "Ultrasonic Timed Collection",
"enabled": false,
"triggers": [
{
"triggerType": 1,
"timerMode": 0,
"intervalSec": 5
}
],
"actions": [
{
"targetPeriphId": "ultrasonic_01",
"actionType": 19,
"actionValue": "{\"periphId\":\"ultrasonic_01\",\"sensorCategory\":\"ultrasonic\",\"dataField\":\"distance\",\"sensorLabel\":\"Distance\",\"unit\":\"cm\",\"decimalPlaces\":1}"
}
],
"reportAfterExec": true
}Too-Close Alarm Rule
{
"id": "exec_distance_alarm",
"name": "Too-Close Distance Alarm",
"enabled": false,
"triggers": [
{
"triggerType": 4,
"eventId": "ds:ultrasonic_01_distance",
"operatorType": 3,
"compareValue": "20"
}
],
"actions": [
{
"targetPeriphId": "buzzer_01",
"actionType": 0,
"actionValue": ""
},
{
"targetPeriphId": "",
"actionType": 21,
"actionValue": "obstacle_detected"
}
],
"reportAfterExec": true
}Water Level Monitoring Scenario (Mounted on top of container facing down)
{
"id": "exec_water_level",
"name": "Water Level Over-limit Alarm",
"enabled": false,
"triggers": [
{
"triggerType": 4,
"eventId": "ds:ultrasonic_01_distance",
"operatorType": 3,
"compareValue": "10"
}
],
"actions": [
{
"targetPeriphId": "pump_relay",
"actionType": 0,
"actionValue": ""
}
],
"reportAfterExec": true
}5. Application Scenarios
| Scenario | Installation Method | Judgment Logic |
|---|---|---|
| Obstacle Detection | Horizontally facing forward | Distance < threshold โ Alarm |
| Water Level Monitoring | Vertically facing down on container top | Distance < threshold โ High water level |
| Material Level Detection | Vertically facing down on silo top | Distance > threshold โ Low material level |
| Parking Space Detection | Vertically facing down above parking space | Distance < threshold โ Occupied |
6. Precautions
- Measurement Blind Zone: HC-SR04 cannot measure within 2cm; ensure target distance > 2cm
- Reflection Surface Requirements: Target surface should be relatively flat; rough surfaces or excessive angles may cause echo loss
- Temperature Compensation: Sound speed varies with temperature (approximately 343m/s at 20ยฐC, 331m/s at 0ยฐC); precise measurement requires compensation
- Level Matching: 5V Echo outputs 5V; use a voltage divider or select a 3.3V module
- Crosstalk Prevention: Multiple ultrasonic modules must be triggered alternately to avoid mutual interference (interval โฅ60ms)
- Soft Objects: Cotton, fabric, and other soft objects absorb sound strongly and may not be detected
For vertical installation scenarios such as water level and material level, it is recommended to reserve mechanical margin: the distance from the sensor to the full-level liquid surface should not fall into the 2cm blind zone. Container edges and liquid surface foam may cause echo interference; use multiple sampling median or extend the sampling period when necessary.
7. FAQ
Q: Readings always return NAN (timeout)?
- Check if VCC is 5V (3.3V power may have insufficient drive capability)
- Confirm Trig/Echo pin wiring is not reversed
- Confirm target is within the 2~400cm effective range
- Echo pin requires a voltage divider (5Vโ3.3V)
Q: Readings fluctuate significantly?
- Ultrasonic measurements are greatly affected by environment (wind, temperature changes, reflection surface angle)
- Software median filtering is recommended
- Reducing sampling interval can improve data density
Q: How to use multiple ultrasonic modules simultaneously?
- Use different Trig/Echo pin pairs for different modules
- Configure different IDs (e.g., ultrasonic_01, ultrasonic_02)
- Stagger collection intervals to avoid ultrasonic mutual interference
