# Example 37: Rotary Encoder

## Experiment Overview

A rotary encoder generates two quadrature pulse signals (A/B phases) when rotated, enabling detection of rotation direction and angle. FastBee includes the built-in `ENCODER` peripheral type (type: 43) for rotary encoder support.

## Hardware Wiring

| Board Label | GPIO Pin | Connected Device |
|-------------|----------|------------------|
| CLK (A) | GPIO34 | Encoder A phase |
| DT (B) | GPIO35 | Encoder B phase |
| SW | GPIO4 | Encoder button (optional) |

## JSON Configuration Example

```json
{
  "peripherals": [
    {
      "id": "encoder_01",
      "name": "Rotary Encoder",
      "type": 43,
      "enabled": false,
      "pins": [34, 35],
      "params": {}
    }
  ]
}
```

## Peripheral Execution Linkage

### Scenario: Encoder-Controlled LED Brightness (Polling Trigger + Script)

**Feature**: Rotate encoder to adjust LED brightness (PWM duty cycle)

#### Web UI Configuration Steps

**Step 1: Ensure PWM LED Peripheral is Configured**

* Peripheral ID: `pwm_breath`
* Type: GPIO PWM Output

**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**: `Encoder Dimming`
   * **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** | Detect changes |
   | **Target Peripheral** | Select `encoder_01` | Rotary encoder |
   | **Polling Interval** | `50` | 50ms (fast response) |
   | **Condition Expression** | `changed == true` | When value changes |

**Step 4: Configure Action (Script Conversion)**

1. Click **Add Action** button

2. Fill in:
   * **Action Type**: Select **Command Script**
   * **Action Parameter**:
   ```
   var pos=encoderRead('encoder_01');
   var duty=Math.min(255,Math.max(0,pos*5));
   pwmWrite('pwm_breath',duty);
   ```

3. Click **Save** button

### Rotary Encoder Value Reference

| Rotation Direction | Count Value | Description |
|-------------------|-------------|-------------|
| Forward (Clockwise) | Increment | A phase leads B phase |
| Reverse (Counter-clockwise) | Decrement | B phase leads A phase |
| Button Press | Separate detection | SW pin (GPIO4) |

## Notes

1. **Interrupt-Driven**: FastBee uses interrupts to detect encoder pulses, no steps lost
2. **Direction Detection**: A phase leading B phase = forward; B phase leading A phase = reverse
3. **Debouncing**: Mechanical encoders bounce; add 100nF capacitor in hardware or debounce in software
4. **Count Range**: Internal counter is int32, supports positive/negative counting
5. **Pin Selection**: Use interrupt-capable pins recommended
