Hi guys. I’ve spent an hour or so searching for an example or clue on how one creates an ESPhome ‘if’ condition statement that contains a second ‘if’ condition inside it, and found nothing obvious.
Has anyone done it and got an example ?
I’ve tried hacking at my code but get validation errors of one type or another.
In my action code a want to check a binary sensor (switch) on the ESP32 is true/on, and check a LED on another gpio for state false/off before moving a servo. Can paste code, but there must be a nested ‘if condition’ around someplace ?
Sorted it myself with when I found the right info.
I need to stop thinking in C++ nesting terms and switch to HA YAML coding (I find this flipping between coding styles very hard to do (C, C++, JSON, YAML, etc)).
I remember when it was just assembler (and machine code) !
For anyone else, this was what I couldn’t find earlier, just did not fluke the right google string till late last night. The states to be checked are stacked (not nested) under the and: modifier.
This sounds like a ‘case’ statement in Arduino coding. A port of that concept would be good.
A lot of us have trouble with the lambda syntax… https://www.arduino.cc/en/Reference.SwitchCase
I use something similar, maybe something like this ?
make sure you set the voltage sensor to the id below
text_sensor:
- platform: template
name: "Wind Direction"
lambda: !lambda |-
if (id(voltage).state)>=0.000 and (id(voltage).state)<0.250 {
return N;
if (id(voltage).state)>=0.250 and (id(voltage).state)<0.500 {
return NE;
if (id(voltage).state)>=0.500 and (id(voltage).state)<0.750 {
return E;
if (id(voltage).state)>=0.750 and (id(voltage).state)<1.000 {
return SE;
if (id(voltage).state)>=1.000 and (id(voltage).state)<1.250 {
return S;
if (id(voltage).state)>=1.250 and (id(voltage).state)<1.500 {
return SW;
if (id(voltage).state)>=1.500 and (id(voltage).state)<1.750 {
return W;
if (id(voltage).state)>=1.750 and (id(voltage).state)<=2.000 {
return NW;
} else {
return NaN;
}
update_interval: 60s
Excellent! Thank you. I’ll give that a try tonight.
EDIT: Couldn’t wait so gave it a try. I’m getting this compilation error:
src/main.cpp: In lambda function:
src/main.cpp:322:33: error: expected primary-expression before '>=' token
if (wind_direction->state)>=0.000 and (wind_direction->state)<0.250 {
^
src/main.cpp:322:75: error: expected ';' before '{' token
if (wind_direction->state)>=0.000 and (wind_direction->state)<0.250 {
^
src/main.cpp:349:1: error: expected '}' at end of input
}
^
src/main.cpp:349:1: warning: no return statement in function returning non-void [-Wreturn-type]
src/main.cpp: In function 'void setup()':
src/main.cpp:349:1: error: expected ')' at end of input
What am I missing after the (wind_direction->state)?