# Example 6: Button Control

## Experiment Overview

Read button state via GPIO digital input (pull-up), triggering LED, buzzer and other peripheral actions. The Puzhong development board has 4 buttons (KEY1-KEY4), which read LOW when pressed.

## Hardware Wiring

| Board Label | GPIO Pin | Connected Device |
|-------------|----------|-----------------|
| KEY1 | GPIO14 | Button (LOW when pressed) |
| KEY2 | GPIO27 | Button (LOW when pressed) |
| KEY3 | GPIO26 | Button (LOW when pressed) |
| KEY4 | GPIO25 | Button (LOW when pressed) |

> One side of the button connects to GPIO, the other to GND, using internal pull-up resistors, GPIO reads LOW when pressed.

## JSON Configuration Example

```json
{
  "peripherals": [
    {
      "id": "key1",
      "name": "Button 1",
      "type": 13,
      "enabled": false,
      "pins": [14],
      "params": {}
    },
    {
      "id": "key2",
      "name": "Button 2",
      "type": 13,
      "enabled": false,
      "pins": [27],
      "params": {}
    },
    {
      "id": "key3",
      "name": "Button 3",
      "type": 13,
      "enabled": false,
      "pins": [26],
      "params": {}
    },
    {
      "id": "key4",
      "name": "Button 4",
      "type": 13,
      "enabled": false,
      "pins": [25],
      "params": {}
    }
  ]
}
```

## Peripheral Execution Linkage

### Scenario 1: Button Controls LED (Poll Trigger)

**Function**: Press Button 1 to toggle LED-D1 on/off state

#### 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**: `Button Control LED`
   * **Report Data**: ❌ Disable
   * **Enabled**: ✅ Enable

**Step 2: Configure Trigger**

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

   | Field | Value | Description |
   |-------|-------|-------------|
   | **Trigger Type** | Select **Poll Trigger** | Periodically detect button state |
   | **Target Peripheral** | Select `key1` | Button peripheral to poll |
   | **Poll Interval** | `50` ms | Detection frequency, 50ms avoids missed presses |
   | **Response Timeout** | `1000` ms | Default is fine |
   | **Retry Count** | `2` | Default is fine |
   | **Poll Delay** | `100` ms | Default is fine |
   | **Comparison Operator** | Select **Equals** | Exact match |
   | **Comparison Value** | `0` | LOW level (0) when pressed |

**Step 3: Configure Action**

1. Click **Add Action** button

2. Fill in action configuration:

   | Field | Value | Description |
   |-------|-------|-------------|
   | **Action Type** | Select **Toggle Level** | Flip GPIO state |
   | **Target Peripheral** | Select `led_d1` | LED to control |

3. Click **Save** button

**Execution Flow**:

```
Detect every 50ms
  ↓
Read key1 state
  ↓
Check: key1 == 0 ? (pressed)
  ↓ Yes
Toggle led_d1 state (on→off or off→on)
```

> ⚠️ **Note**: Poll interval recommended at 50ms, too fast wastes CPU, too slow may miss short presses

***

### Scenario 2: Button Event Trigger (Click/Double-click/Long Press)

**Function**: Use the built-in button state machine to detect click, double-click, and long-press events without writing a polling rule.

#### Prerequisites

Keep the button configured as **Digital Input (Pull-up)** (type: 13) or **Digital Input (Pull-down)** (type: 14). The firmware automatically emits these events for digital-input buttons:

| Event ID | Trigger condition |
|----------|-------------------|
| `button_press` | Debounced button press |
| `button_release` | Button release |
| `button_click` | A quick press and release |
| `button_double_click` | Two clicks within 300 ms |
| `button_long_press_2s` | Held for more than 2 seconds |
| `button_long_press_5s` | Held for more than 5 seconds |

#### Web Interface Configuration Steps

**Step 1: Create Rule**

1. Click **<i class="fas fa-plus"></i> New Rule**
2. Fill in basic configuration:
   * **Rule Name**: `Button Interrupt Control`
   * **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 **Event Trigger** | Respond to system events |
   | **Event Category** | Select **Button Event** | Select from dropdown |
   | **Specific Event** | Select `button_click` | Single-click event |
   | **Trigger Peripheral** | Select `key1` | Restrict the event to Button 1; leave empty to match any button |

**Step 3: Configure Action**

1. Click **Add Action** button

2. Fill in action configuration:

   | Field | Value | Description |
   |-------|-------|-------------|
   | **Action Type** | Select **HIGH Level** | GPIO output HIGH |
   | **Target Peripheral** | Select `relay_01` | Control relay |

3. Click **Save** button

**Execution Flow**:

```
Button state machine checks key1
  ↓
Detect a click (press and quick release)
  ↓
Emit button_click with triggerPeriphId=key1
  ↓
Match eventId=button_click and triggerPeriphId=key1
  ↓
Execute action: relay energizes
```

> 💡 **Advantage**: The built-in state machine applies 50 ms debouncing and distinguishes click, double-click, and long-press events automatically.

**Event mode** (recommended):

```json
{
  "name": "Button Event Control",
  "enabled": true,
  "reportAfterExec": true,
  "triggers": [
    {
      "triggerType": 4,
      "triggerPeriphId": "key1",
      "eventId": "button_click"
    }
  ],
  "actions": [
    { "actionType": 0, "targetPeriphId": "relay_01" }
  ]
}
```

**Timer mode** (toggle the LED every 5 seconds):

```json
{
  "name": "Button Control LED",
  "enabled": true,
  "triggers": [
    {
      "triggerType": 1,
      "timerMode": 0,
      "intervalSec": 5
    }
  ],
  "actions": [
    { "actionType": 30, "targetPeriphId": "led_d1" }
  ]
}
```

> ℹ️ Poll and timer triggers have a minimum interval of 5 seconds. Use an event trigger for button response.

## Notes

1. **Debouncing**: FastBee internally applies 50ms software debouncing to GPIO input
2. **Pull-up/Pull-down**: Buttons to GND use pull-up (type: 13), buttons to VCC use pull-down (type: 14)
3. **Button Events**: Prefer `button_click` with `triggerPeriphId` instead of creating a fast polling rule
4. **GPIO25 Conflict**: If using both relay and Button 4, pins need to be changed
5. **Long Press Detection**: Can distinguish long/short press by recording press duration in scripts
