# Example 47: Modbus Relay Control

## Experiment Overview

Controls RS485 multi-channel relay modules via Modbus RTU protocol, enabling remote on/off switching. Suitable for smart home, industrial control, agricultural irrigation, and other scenarios requiring remote switching.

## Hardware Wiring

### RS485 Communication Wiring

| ESP32 Pin | TTL-to-RS485 Module | Description |
|-----------|--------------------|-------------|
| GPIO 16 | TXD | Serial transmit |
| GPIO 17 | RXD | Serial receive |
| GPIO 4 (optional) | DE/RE | Direction control |
| 3.3V | VCC | Power |
| GND | GND | Ground |

### RS485 to Relay Module

| RS485 Module | Relay Board | Description |
|-------------|------------|-------------|
| A+ | A | Differential signal positive |
| B- | B | Differential signal negative |

> Relay modules typically require 12V/24V DC power; contacts support AC 250V/10A or DC 30V/10A.

## JSON Configuration Example

### 4-Channel Relay Control

```json
{
  "id": "modbus_relay",
  "name": "4-CH Modbus Relay",
  "type": 1,
  "enabled": false,
  "pins": [16, 17],
  "params": {
    "baudRate": 9600,
    "dataBits": 8,
    "parity": "none",
    "stopBits": 1,
    "dePin": 4,
    "protocol": "modbus_rtu",
    "slaveId": 1,
    "function": 5,
    "startRegister": 0,
    "registerCount": 4,
    "interval": 0,
    "controlMap": [
      { "register": 0, "name": "ch1", "onValue": 65280, "offValue": 0 },
      { "register": 1, "name": "ch2", "onValue": 65280, "offValue": 0 },
      { "register": 2, "name": "ch3", "onValue": 65280, "offValue": 0 },
      { "register": 3, "name": "ch4", "onValue": 65280, "offValue": 0 }
    ]
  }
}
```

### Relay Status Readback

```json
{
  "id": "modbus_relay_status",
  "name": "Relay Status",
  "type": 1,
  "enabled": false,
  "pins": [16, 17],
  "params": {
    "protocol": "modbus_rtu",
    "slaveId": 1,
    "function": 1,
    "startRegister": 0,
    "registerCount": 4,
    "interval": 2000,
    "dataMap": [
      { "register": 0, "name": "ch1_state", "scale": 1 },
      { "register": 1, "name": "ch2_state", "scale": 1 },
      { "register": 2, "name": "ch3_state", "scale": 1 },
      { "register": 3, "name": "ch4_state", "scale": 1 }
    ]
  }
}
```

### Parameter Description

| Parameter | Description |
|-----------|-------------|
| function 5 | Write Single Coil |
| function 1 | Read Coils |
| onValue | Coil ON value: 0xFF00 = 65280 |
| offValue | Coil OFF value: 0x0000 = 0 |

## Control Commands

Control relays via MQTT:

```json
[{"id": "modbus_relay", "value": "ch1:1,ch2:0,ch3:1,ch4:0"}]
```

* `1` = Close (ON)
* `0` = Open (OFF)

## Peripheral Execution Linkage

### Scenario 1: Temperature-Controlled Fan (Polling Trigger)

**Feature**: Turn on fan (relay CH1) when temperature exceeds 30°C

#### Web UI Configuration Steps

**Step 1: Ensure Peripherals are Configured**

* Modbus temp/humidity: `modbus_th`
* Modbus relay: `modbus_relay`

**Step 2: 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**: `High Temp Fan ON`
   * **Report Data**: ✅ Enabled
   * **Enable**: ✅ Enabled

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

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

   | Field | Value | Description |
   |-------|-------|-------------|
   | **Trigger Type** | Select **Polling Trigger** | Periodic condition check |
   | **Target Peripheral** | Select `modbus_th` | Modbus temp/humidity |
   | **Data Field** | `temperature` | Temperature field |
   | **Operator** | `>` | Greater than |
   | **Threshold** | `30` | 30°C |
   | **Polling Interval** | `5000` | 5 seconds |

**Step 4: Configure Action (Modbus Write)**

1. Click **Add Action** button

2. Fill in:
   * **Action Type**: Select **Modbus Write**
   * **Target Peripheral**: Select `modbus_relay`
   * **Register**: `0` (CH1)
   * **Value**: `65280` (Close)

3. Click **Save** button

***

### Scenario 2: Scheduled Irrigation (Timer Trigger)

**Feature**: Open irrigation valve at 6:00 AM daily for 5 minutes

**Configuration Steps**:

1. Create rule, name: `Scheduled Irrigation`
2. Trigger configuration:
   * **Trigger Type**: Select **Timer Trigger**
   * **Timer Mode**: Select **Cron Expression**
   * **Cron**: `0 6 * * *` (daily at 6:00)
3. Action configuration (3 actions required):
   * **Action 1**: Select **Modbus Write**, register `1` (CH2), value `65280` (Open)
   * **Action 2**: Select **Delay**, time `300000` (5 minutes)
   * **Action 3**: Select **Modbus Write**, register `1` (CH2), value `0` (Close)
4. Click **Save**

## Typical Application Scenarios

| Scenario | Wiring | Description |
|----------|--------|-------------|
| Light Control | NO contact in series with light | Close = light ON |
| Fan Control | NO contact in series with fan | Automatic temperature control |
| Solenoid Valve | NO contact in series with valve | Irrigation/ventilation |
| Heater | NO contact in series with heater | Low-temperature heating |

## Notes

1. **Contact Rating**: Relay contacts have maximum current limits; high-power loads require a contactor
2. **Back-EMF**: When controlling inductive loads (motors/solenoids), add a flyback diode on the load side
3. **Power-off State**: Relay defaults to open after power loss; select latching type if state retention is needed
4. **Operating Frequency**: Mechanical relay lifespan is ~100,000 cycles; use solid-state relay for frequent switching
5. **Slave Address**: When multiple relay modules share the same bus, ensure addresses do not conflict
6. **Safety Distance**: Maintain safe distance between high voltage (220V AC) and low voltage (RS485) wiring
