Need help with an error when compiling lambda

Further to my earlier post Tryng to repeat an action every "n" minutes where "n" is variable, I had all sorts or errors in my lambdas when compiling. I’ve spent all day on it and got it down to just a single error which is this:

/config/esphome/hydrotower1.yaml: In lambda function:
/config/esphome/hydrotower1.yaml:168:28: error: invalid operands of types 'esphome::globals::RestoringGlobalsComponent<int>*' and 'int' to binary 'operator*'
           return (pump_on_time)*1000;
              ~~~~~~~~~~~~~~^~~~~
*** [/data/hydrotower1/.pioenvs/hydrotower1/src/main.cpp.o] Error 1

The part of the code referenced by the error is in this script:

script:
  - id: cycle_pump
    then:
      - delay: !lambda |-
          return ((pump_interval) - (pump_on_time)) * 1000; 
      - switch.turn_on: pump_relay
      - delay: !lambda |-
          return ((pump_on_time)) * 1000;
      - switch.turn_off: pump_relay

What I can’t get my head around is that the first expression where I take one value from another and multiply by 1000 seems to work without any errors, but the much simpler expression simply multiplying one value by 1000 generates the error. I’ve tried various combinations of brackets (including no brackets) to no avail. And I can’t fathom why the error refers to restoring a global variable to a binary operator.

If it helps, here is how the global variables are defined:

globals:
  - id: pump_enabled
    type: bool
    restore_value: yes
    initial_value: 'true'

  - id: pump_interval
    type: int
    restore_value: yes
    initial_value: '360'  

  - id: pump_on_time
    type: int
    restore_value: yes
    initial_value: '60'

I know it’ll be something stupid that I’ve done (all the other dozen or so errors were) but this one has me stumped. So any help would be much appreciated.

If you want to access the value of a global you need to use:

id(global_name)

see Automations and Templates — ESPHome

So change your code to:

script:
  - id: cycle_pump
    then:
      - delay: !lambda |-
          return (id(pump_interval) - id(pump_on_time)) * 1000; 
      - switch.turn_on: pump_relay
      - delay: !lambda |-
          return id(pump_on_time) * 1000;
      - switch.turn_off: pump_relay

Very many thanks for that. I did have id(global_name) at one point but due to a plethora of other issues that I was trying to fix, I changed it. Indeed looking through the rest of the code, I can see that I’ve used id(global) everywhere else but not here. Anyway that looks like it’s fixed it and it compiles and uploads just fine. Looks like I created another problem when trying to fix something else.
Thanks again.

Please mark it as the solution. :slight_smile:

Done as requested :ok_hand:

1 Like