I want to share the code for a project I recently got working based around HubDuino.
My goal was to detect the presence or absence of my car in my garage. I'll probably add to the project in the future to detect whether the garage door is open or not, control the garage door, and possibly add a light sensor (to detect whether I left the fluorescent tube lights on in the garage), but for now it just detects whether my car is in my garage or not.
For the software I forked the main HubDuino project and wrote a custom subclass of the
st::Sensor class called
You can find the code in my fork on GitHub. There are three main files:
I'm new to Hubitat (and smart home automation in general), so I welcome any feedback or suggestions, but I'm mostly sharing in case anybody else would benefit from the code.
You can view the example sketch in
ST_Anything_Ultrasonic_Threshold_ESP32WiFi to get started.
As described in
S_UltrasonicPresence takes as input:
String &name- the name of the object - must start with "presence".
byte digitalTriggerPin- the pin to be used as a digital output to trigger the sensor
byte digitalEchoPin- the pin to be used as a digital input to read the echo
bool initalState- the initial state of the presence detector (true == present)
bool longIsPresent- the method to convert from distance to presence
unsigned long longThreshold- the threshold in microseconds considered a "long distance"
unsigned long shortThreshold- the threshold in microseconds considered a "short distance"
longIsPresent dictates whether a long or a short distance is considered "present".
longIsPresent = truemeans that a long distance is considered "present".
longIsPresent = falsemeans that a short distance is considered "present".
To switch from long to short, the short threshold must be crossed. To switch from short to long the long threshold must be crossed. This is to prevent the signal bouncing back and forth for a distance near the threshold.
The threshold is based on the amount of time it takes for the ultrasonic signal to leave the transmitter, bounce off the target, and return to the receiver, which is based on the speed of sound. From the HC-SR04 documentation, to convert from centimeters or inches to microseconds, use these equations:
- time (μS) = distance from sensor (cm) * 58 μS/cm
- time (μS) = distance from sensor (inches) * 148 μS/inch