In my quest to improve presence and occupancy detection, I was thinking about a sensor device that can detect which direction a person is moving. Basically it’s two photoresistors spaced about 8cm apart on one side of a doorway, with either lasers or bright LEDs or something pointed directly at them from the other side.
When a person walks through the doorway, they break the beams in a particular order that indicates if they are entering or leaving the room. This would be super useful, because you can assume a room is occupied if someone walked into it but hasn’t left, even if there’s no motion (eg they sat down and read a book).
Now, I’ve mocked up a prototype on a breadboard, and it works quite well. To pass WAF I will need to 3D print a nice acetone-smoothed case and somehow come up with a method of mounting it in the doorframe that is not ugly.
However, I’m struggling with the code.
I can think of how I might code it up in the Arduino IDE. Far easier, I can think of how I’d do it in Node-RED. But I can’t for the life of me think how I’d do it in ESPHome, because to my knowledge, ESPHome doesn’t have the equivalent of a loop method.
The logic is something like this.
Wait for one of the sensors to change from ON to OFF. On state change, check to see if the other sensors changes state too, within about a second. If it does, report direction of travel. If it doesn’t, it’s either a false alarm or someone lurking in the doorway without actually going through, and we don’t need to report anything.
In the IDE I’d probably do it by having two methods called checkSensorOne() and checkSensorTwo(), basically identical but for the sensor names, and call the methods one after the other on loop. I could probably do the checking in a lambda, but I can’t think how I’d loop it.
Is there a way to do this in ESPhome? I really like the API integration, and otherwise I’ll have to do this with MQTT, which I have mostly forgotten. Can you point me at any code examples, even if they are for doing other things, that have a loop-style functionality in ESPHome?