Dimming lights with rotary encoder on ESP8266 and ESPHome

I ran into an issue. Both the light (in HA) and the ESP were maintaining the absolute dimmer position. I had to keep them in sync which was a pain; updates were bouncing back and forth.

I have now changed the ESP to only issue an incremental value, generated within the debounce time frame. It creates a number in HA.

There is a global variable which stores the previous encoder position and it is subtracted from the current encoder position.

I hope this helps someone :slight_smile:

globals:
  - id: aanrechtoldvalue
    type: int
    restore_value: no
    initial_value: '0'
  

number:
  - platform: template
    name: Aanrecht Increment
    id: aanrechtincrement
    min_value: -20
    max_value: 20
    step: 1
    optimistic: true
    initial_value: 0
  
sensor:
  - platform: rotary_encoder
    name: "Aanrecht dimmer knop"
    id: aanrecht_rotary_encoder
    resolution: 1
    pin_a:
      number: GPIO26
      mode:
        input: true
        pullup: true
    pin_b:
      number: GPIO27
      mode:
        input: true
        pullup: true
    filters:
      debounce: 0.25s
    on_value:
      then:
        - number.set:
            id: aanrechtincrement
            value: !lambda 'return id(aanrecht_rotary_encoder).state - id(aanrechtoldvalue);'
        - globals.set:
            id: aanrechtoldvalue
            value: !lambda 'return id(aanrecht_rotary_encoder).state;'

The automation in HA picks up the new number value and issues a brightness_step command with that increment. I have 20 steps for a brightness resolution of 255, so multiplied by 13. There is also a pir sensor looking at the dimmer knob, so I have to disable that for a short while. The automation is queued so multiple number changes are being picked up correctly.

alias: 'Keuken aanrecht: rotary dim kitchen light (increment)'
description: ''
trigger:
  - platform: state
    entity_id: number.aanrecht_increment
condition: []
action:
  - service: light.turn_on
    target:
      entity_id: light.keuken_aanrecht_groep
    data:
      brightness_step: '{{ (((trigger.to_state.state | float(0)) * 13)) | round(0) }}'
  - service: input_boolean.turn_on
    target:
      entity_id: input_boolean.aanrecht_override_pir
  - delay:
      hours: 0
      minutes: 0
      seconds: 30
      milliseconds: 0
  - service: input_boolean.turn_off
    target:
      entity_id: input_boolean.aanrecht_override_pir
mode: queued
max: 10

and

alias: 'Keuken Aanrecht: Reset Override PIR'
description: ''
trigger:
  - platform: state
    entity_id: input_boolean.aanrecht_override_pir
    to: 'on'
condition: []
action:
  - delay:
      hours: 0
      minutes: 0
      seconds: 30
      milliseconds: 0
  - service: input_boolean.turn_off
    target:
      entity_id: input_boolean.aanrecht_override_pir
mode: restart

6 Likes