ESPHome - Global Variables: Can't seem to get them to work AT ALL

I’m trying to use global variables for a binary template sensor.

The declaration throws the error:

[globals] is an invalid option for [binary_sensor.template]. Please check the indentation.

When I try to set a value, I get the following error:

Unable to find action with the name 'globals.set'.

Here is the relevant code:

binary_sensor:
  - platform: template
    id: "${button_id}_action"
    lambda: |-
      return id(${button_id}).state;
    globals:
      - id: red
        type: float
    on_click:
      - globals.set:
          - id: red
            value: '1.0'
      - min_length: 50ms
        max_length: 350ms
        then:
          - if:
              condition:
                light.is_on: "${light_id}"
              then:
                light.turn_off: "${light_id}"
              else:

I followed the documentation https://esphome.io/guides/automations.html#bonus-2-global-variables and https://esphome.io/guides/automations.html#globals-set-action

What am I missing?

Right after posting this, I gave another try, and defined the golbals outsinde of an entity, like a true variable should, and thi eliminated the first error.

The globals.set no throws

 expected a dictionary.
      globals.set:  [source /config/esphome/_common/binary_sensor_rgbw_test.yaml:17]
        - id: red
          value: 1.0

I’ll try some more, but am always thankful for hints :wink:

I know, I’m talking to myself but maybe someone else will profit :wink:
Believe me, I already tried several hours before my first post.

This is, how I finally got this working.
I think this is not necessarily clear from the documentation:

globals:
  - id: red
    type: float
  - id: green
    type: float
  - id: blue
    type: float

binary_sensor:
  - platform: template
    id: "${button_id}_action"
    lambda: |-
      return id(${button_id}).state;
    on_click:
      - min_length: 50ms
        max_length: 350ms
        then:
          - globals.set:
              id: red
              value: '1.0'
          - globals.set:
              id: green
              value: '1.0'
          - globals.set:
              id: blue
              value: '1.0'
          - if:
              condition:
                light.is_on: "${light_id}"
              then:
                light.turn_off: "${light_id}"
              else:
                light.turn_on:
                  id: ${light_id}

4 Likes