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

1. Trig pin sends a ≥10μs high-level trigger pulse
2. The module automatically emits 8 cycles of 40KHz ultrasonic pulses
3. Echo pin outputs high level, duration = sound wave round-trip time
4. Distance calculation: `distance(cm) = duration(μs) × 0.034 / 2`

```mermaid
%%{init: {"flowchart": {"htmlLabels": false}}}%%
flowchart LR
  A["ESP32\nTrig GPIO\nEcho GPIO"] --> B["HC-SR04\nTrig / Echo / VCC 5V / GND"]
  B --> C["Target Object\nSound wave round-trip path"]
  C --> D["Distance Calculation\nDistance cm = Echo high duration us / 58"]
  D --> E["Field Verification\nMinimum distance 2cm\nFlat target surface\nSampling period not too short"]
  B --> F["Level Protection\nEcho 5V module recommends voltage divider or level shifter"]
```

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 pin
```

**Recommended 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

1. Open a browser and access the ESP32 IP address
2. After logging in, click **Peripheral Configuration** in the left menu

#### Step 2: Add Ultrasonic Sensor Peripheral

1. Click the **<i class="fas fa-plus"></i> Add Peripheral** button

2. Fill in the configuration:

   | Field | Value | Description |
   |------|---------|------|
   | **Peripheral ID** | `ultrasonic_01` | Unique identifier |
   | **Name** | `Ultrasonic Distance` | Display name |
   | **Peripheral Type** | **Generic Sensor** (type: 38) | Ultrasonic driver |
   | **Trig Pin** | `4` | Trigger pin (output) |
   | **Echo Pin** | `27` | Echo pin (input) |

3. Click **Save**

#### Step 3: Verify Configuration

1. Find the newly added peripheral in the peripheral list
2. Click the **Enable** toggle
3. 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.

```json
{
  "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**

1. Click **Peripheral Execution** in the left menu
2. Click the **<i class="fas fa-plus"></i> Add Rule** button
3. Configure the timer trigger:
   * Trigger Type: **Timer Trigger**
   * Execution Interval: **5** seconds
4. Add action:
   * Action Type: **Sensor Read**
   * Target Peripheral: **ultrasonic\_01**
   * Data Field: **distance**
5. Enable **Report Data After Execution**
6. Click **Save**

**Create Too-Close Alarm Rule**

1. Create a new rule
2. Configure event trigger:
   * Trigger Type: **Event Trigger**
   * Event ID: **ds:ultrasonic\_01\_distance**
   * Comparison Operation: **Less Than**
   * Comparison Value: **20** (cm)
3. 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**
4. Click **Save**

> 💡 **Tip**: Event ID format is `ds:{peripheralId}_{fieldName}`

***

### JSON Configuration Examples

### Distance Timed Collection Rule

```json
{
  "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

```json
{
  "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)

```json
{
  "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

1. **Measurement Blind Zone**: HC-SR04 cannot measure within 2cm; ensure target distance > 2cm
2. **Reflection Surface Requirements**: Target surface should be relatively flat; rough surfaces or excessive angles may cause echo loss
3. **Temperature Compensation**: Sound speed varies with temperature (approximately 343m/s at 20°C, 331m/s at 0°C); precise measurement requires compensation
4. **Level Matching**: 5V Echo outputs 5V; use a voltage divider or select a 3.3V module
5. **Crosstalk Prevention**: Multiple ultrasonic modules must be triggered alternately to avoid mutual interference (interval ≥60ms)
6. **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
