The HC-SR04 Ultrasonic Sensor is fixed inside the Rat-Bait-Station. The sensor is activated by the capacitive touch sensor. Upon activation, the data output from the sensor is a variable-width pulse that corresponds to the distance-to-target. The ultrasonic sensor produces more complex information that is grouped together compared to the capacitive touch sensor.

The ultrasonic sensor uses sonar to determine the distance to the rat inside the Rat-Bait-Station. The transmitter (trig pin) sends a signal data which is a high-frequency sound. When the signal data finds the rat, it is reflected and the transmitter (echo pin) receives the data. The data is calculated and converted to distance to be meaningful.
To program the Ultrasonic Sensor in the Arduino sketch for the ESP8266’s Meshquitto Node, open the meshquittoNode.ino file (the Meshquitto Node sketch) using the Arduino IDE.
Define the TRIGGER and ECHO pins for the ultrasonic sensor:
// Define GPIO pins
#define TOUCHPIN 16 // Pin for capacitive touch sensor
#define LED_PIN 0 // Pin for the pin for the Onboard red LED
#define LED_TOPIC "LED1"
#define TRIGGER 12 // GPIO pin for HC-SR04 Ultrasonic Sensor's Trig pin
#define ECHO 13 // GPIO pin for HC-SR04 Ultrasonic Sensor's Echo pin
#define DIST_TOPIC "RatBS001"
We need to program the ultrasonic sensor data to calculate the distance. Referring to the HC-SR04 Ultrasonic Sensor Source Code, I had integrated the code (highlighted in blue) with the Meshquitto Node sketch:
Under the void setup():
From the above program code, we can see the ultrasonic sensor’s data needs to be calculated and converted to distance to be meaningful.
The distance is sent (published) by the Meshquitto node (MQTT Client – Publish) to the Raspberry Pi (MQTT Client – Subscribe) using the MQTT protocol. Unlike the touch sensor’s data, the ultrasonic sensor’s data which is converted to distance, is sent to the Raspberry Pi for interpretation.