Skip to content

Instantly share code, notes, and snippets.

@Bolukan
Last active July 7, 2024 18:17
Show Gist options
  • Save Bolukan/376181c5e0f1abd9b3105a20a7d64ad1 to your computer and use it in GitHub Desktop.
Save Bolukan/376181c5e0f1abd9b3105a20a7d64ad1 to your computer and use it in GitHub Desktop.
Python script to transfer AJ-SR04M Waterproof Ultrasonic Sensor to MQTT
# !/usr/bin/python
# encoding:utf-8
# Waterproof Ultrasonic Module AJ-SR04M
import RPi.GPIO as GPIO
import time
import paho.mqtt.client as mqtt
timeout = 1 # seconds wait for signal
TRIG = 27 # Associate pin 27 to TRIG
ECHO = 22 # Associate pin 22 to Echo
# MQTT setup
mqtt_broker = "YOUR_MQTT_SERVER"
mqtt_port = 1883
mqtt_topic_status = "devices/rainbarrel/status"
mqtt_topic_depth = "devices/rainbarrel/depth"
def on_publish(client, userdata, mid, reason_code, properties):
# reason_code and properties will only be present in MQTTv5. It's always unset in MQTTv3
try:
userdata.remove(mid)
except KeyError:
print("Error on_publish")
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, protocol=mqtt.MQTTProtocolVersion.MQTTv5)
mqttc.on_publish = on_publish
unacked_publish = set()
mqttc.user_data_set(unacked_publish) # Set the user data variable passed to callbacks. May be any data type.
mqttc.connect(host=mqtt_broker, port=mqtt_port)
mqttc.loop_start()
# PIN setup
GPIO.setmode(GPIO.BCM) # Set GPIO pin numbering
GPIO.setup(TRIG, GPIO.OUT) # Set pin as GPIO out
GPIO.setup(ECHO, GPIO.IN) # Set pin as GPIO in
GPIO.output(TRIG, False) # Set TRIG as LOW
# settle
time.sleep(1)
print("Distance measurement in progress")
try:
while True:
GPIO.output(TRIG, True) # Set TRIG as HIGH
time.sleep(0.00001) # Delay of 0.00001 seconds
GPIO.output(TRIG, False) # Set TRIG as LOW
pulse_start = time.time()
timeout_start = pulse_start
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
if pulse_start - timeout_start > timeout:
break
pulse_end = time.time()
timeout_end = pulse_end
if GPIO.input(ECHO) == 1:
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
if pulse_end - timeout_end > timeout:
break
pulse_duration = pulse_end - pulse_start # Pulse duration to a variable
distance = pulse_duration * 17150 # Calculate distance
distance = round(distance, 2) # Round to two decimal points
print("distance known, now processing")
if 20 < distance < 400: # Is distance within range
msg_info = mqttc.publish(mqtt_topic_depth, distance, qos=1)
unacked_publish.add(msg_info.mid)
print("Distance:", distance, "cm")
else:
msg_info_status = mqttc.publish(mqtt_topic_status, f"Failed, pulse_start: {pulse_start}", qos=1)
unacked_publish.add(msg_info_status.mid)
print("Out Of Range: ", distance, "cm")
while len(unacked_publish):
time.sleep(0.1)
time.sleep(10)
except KeyboardInterrupt:
mqttc.disconnect()
mqttc.loop_stop()
print("Measurement stopped by User")
GPIO.cleanup()
# chmod +x /home/pi/rainbarrel.py
# sudo chmod 644 /lib/systemd/system/rainbarrel.service
[Unit]
Description=Rainbarrel sensor
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/bin/python /home/pi/rainbarrel.py
Restart=on-abort
User=pi
WorkingDirectory=/home/pi
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment