# Example 20: HC-SR04 Distance

## Experiment Overview

HC-SR04 ultrasonic sensor measures distance by transmitting and receiving ultrasonic waves, measurement range 2~400cm, precision ~3mm. FastBee has a built-in `SENSOR_GENERIC` generic sensor type (type: 38), combined with `category: ultrasonic` to support ultrasonic distance measurement.

```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 time us / 58"]
  D --> E["Field Verification\nMin distance 2cm\nFlat target surface\nDon't sample too fast"]
  B --> F["Level Protection\nEcho 5V module recommend voltage division or level shifting"]
```

This experiment first verifies stable readings at a fixed distance, then connects to alarm rules. If fixed distance readings are unstable, first check power supply, level shifting, reflection surface and Trig/Echo wiring before adjusting rule thresholds.

## Hardware Wiring

| Board Label | GPIO Pin | Connected Device |
|-------------|----------|-----------------|
| TRIG | GPIO14 | HC-SR04 trigger pin |
| ECHO | GPIO27 | HC-SR04 echo pin |

> TRIG sends a 10μs HIGH pulse to trigger measurement, ECHO returns HIGH level duration representing distance.

## JSON Configuration Example

```json
{
  "peripherals": [
    {
      "id": "ultrasonic_01",
      "name": "Ultrasonic Distance",
      "type": 38,
      "enabled": false,
      "pins": [14, 27],
      "params": {
        "category": "ultrasonic"
      }
    }
  ]
}
```

## Peripheral Execution Linkage

### Scenario 1: Periodic Distance Measurement (Timer Trigger)

**Function**: Read ultrasonic distance every 1 second

#### Web Interface Configuration Steps

**Step 1: Create Rule**

1. Click **Peripheral Execution** in the left menu
2. Click **<i class="fas fa-plus"></i> New Rule** button
3. Fill in basic configuration:
   * **Rule Name**: `Ultrasonic Periodic Measurement`
   * **Report Data**: ✅ Enable
   * **Enabled**: ✅ Enable

**Step 2: Configure Trigger**

1. Click **Add Trigger** button
2. Fill in trigger configuration:

   | Field | Value | Description |
   |-------|-------|-------------|
   | **Trigger Type** | Select **Timer Trigger** | Periodic acquisition |
   | **Timer Mode** | Select **Fixed Interval** | By millisecond interval |
   | **Interval Time** | `1000` | 1 second |

**Step 3: Configure Action**

1. Click **Add Action** button

2. Fill in:
   * **Action Type**: Select **Read Sensor**
   * **Target Peripheral**: Select `ultrasonic_01`
   * **Data Field**: `distance`

3. Click **Save** button

***

### Scenario 2: Proximity Alarm (Poll Trigger)

**Function**: Check distance every 0.5 seconds, trigger buzzer short beep when distance < 20cm

#### Web Interface Configuration Steps

**Step 1: Ensure buzzer peripheral is configured**

* Peripheral ID: `buzzer_gpio`
* Type: GPIO Output

**Step 2: Create Rule**

1. Click **<i class="fas fa-plus"></i> New Rule**
2. Fill in basic configuration:
   * **Rule Name**: `Proximity Alarm`
   * **Report Data**: ✅ Enable
   * **Enabled**: ✅ Enable

**Step 3: Configure Trigger (Poll Trigger)**

1. Click **Add Trigger** button
2. Fill in trigger configuration:

   | Field | Value | Description |
   |-------|-------|-------------|
   | **Trigger Type** | Select **Poll Trigger** | Periodically detect condition |
   | **Target Peripheral** | Select `ultrasonic_01` | Ultrasonic sensor |
   | **Poll Interval** | `500` | 0.5 seconds |
   | **Condition Expression** | `distance < 20` | Distance less than 20cm |

**Step 4: Configure Actions (3 actions needed)**

**Action 1: Buzzer ON**

1. Click **Add Action** button
2. Fill in:
   * **Action Type**: Select **HIGH Level**
   * **Target Peripheral**: Select `buzzer_gpio`

**Action 2: Delay 200ms**

1. Click **Add Action** button again
2. Fill in:
   * **Action Type**: Select **Delay**
   * **Action Params**: `200`

**Action 3: Buzzer OFF**

1. Click **Add Action** button a third time

2. Fill in:
   * **Action Type**: Select **LOW Level**
   * **Target Peripheral**: Select `buzzer_gpio`

3. Click **Save** button

### HC-SR04 Features

| Feature | Parameter | Description |
|---------|-----------|-------------|
| Measurement Range | 2cm ~ 400cm | Effective measurement distance |
| Precision | ±3mm | High precision |
| Blind Zone | 2cm | Minimum measurement distance |
| Measurement Angle | 15° | Sound wave cone emission angle |
| Sampling Interval | ≥60ms | Avoid echo interference |

## Notes

1. **Power**: HC-SR04 needs 5V power, ECHO outputs 5V, needs voltage division to 3.3V before connecting to ESP32
2. **Blind Zone**: Minimum measurement distance 2cm, unreliable below this
3. **Measurement Angle**: Sound wave cone emission angle ~15°, narrow spaces may have reflection interference
4. **Temperature Compensation**: Sound speed varies with temperature (~343m/s at 20°C), compensation needed for precise measurement
5. **Sampling Frequency**: Recommend at least 60ms interval to avoid front/back echo interference
6. **Pin Order**: First pin in array is TRIG, second is ECHO
