HC-SR04 with HA connected to RPI GPIO

I’m working on garage door simulation ,using ultrasonic sensor HC-SR04
,how to read data from it through GPIO to calculate distance ,and take action to open/close door
depending on the distance ,I’m new with HA ,so if any EX. code please

can any one help me

check here
2nd and 3rd link are exactly what you’re after.

Any child can do your steps which i already know , I just meant with HA

these look like questions about getting the data from the sensor, hence my response.
IF you’ve already got that data available, then can you share what language you’re using? We can then advise on way to send that data to HA.
Personally I use MQTT and mosquitto_pub commands

I’m using a python code to get data from sensor and and switch a LED on/off depending on the distance ,what i want here is to send the action token with LED to HA to switch on/off a motor ,the code is
[
from gpiozero import LED
from signal import pause
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

MY_LED1 = 14
PIN_TRIGGER1 = 23
PIN_ECHO1 = 24

GPIO.setup(MY_LED1,GPIO.OUT)
GPIO.setup(PIN_ECHO1, GPIO.IN)
GPIO.setup(PIN_TRIGGER1, GPIO.OUT)

print(“Waiting for sensor to settle”)

print(“Calculating distance”)

GPIO.output(PIN_TRIGGER1, GPIO.HIGH)

time.sleep(0.00001)

GPIO.output(PIN_TRIGGER1, GPIO.LOW)

while GPIO.input(PIN_ECHO1) == 0:
pulse_start_time = time.time()
while GPIO.input(PIN_ECHO1) == 1:
pulse_end_time = time.time()

pulse_duration = pulse_end_time - pulse_start_time
distance = round(pulse_duration * 17150, 2)
print((“Distance:”, distance, “cm”))

if distance < 5:
GPIO.output(MY_LED1,GPIO.HIGH)

else :
GPIO.output(MY_LED1,GPIO.LOW)

time.sleep(2)
]

I’ve already setup MQTT and mosquitto server on my Pi ,and add it in configuration.yaml
But don’t know how to connect that python code

I use this command:

import subprocess

MQTT_Host = "192.168.0.1"
MQTT_Port = "1883"
MQTT_User = "user"
MQTT_Password = "password"
MQTT_Command = ""


MQTT_Command = ["mosquitto_pub", "-h", MQTT_Host, "-p", MQTT_Port, "-u", MQTT_User, "-P", MQTT_Password, "-t", "RPi/PIRLivingRoomBack", "-r", "-m", "ON"]
ps = subprocess.Popen(MQTT_Command)

Sorry ,but I don’t get what exactly to do
How to use your code ,with my python code ?

this is where you get the distance in your script, so this is where you insert the code I provided to send the value to HA via MQTT

this is the modified code

[
from gpiozero import LED
from signal import pause
import RPi.GPIO as GPIO
import time
import subprocess

GPIO.setmode(GPIO.BCM)

MY_LED1 = 14
PIN_TRIGGER1 = 23
PIN_ECHO1 = 24

GPIO.setup(MY_LED1,GPIO.OUT)
GPIO.setup(PIN_ECHO1, GPIO.IN)
GPIO.setup(PIN_TRIGGER1, GPIO.OUT)

print(“Waiting for sensor to settle”)

print(“Calculating distance”)

GPIO.output(PIN_TRIGGER1, GPIO.HIGH)

time.sleep(0.00001)

GPIO.output(PIN_TRIGGER1, GPIO.LOW)

while GPIO.input(PIN_ECHO1) == 0:
pulse_start_time = time.time()
while GPIO.input(PIN_ECHO1) == 1:
pulse_end_time = time.time()

pulse_duration = pulse_end_time - pulse_start_time
distance = round(pulse_duration * 17150, 2)
print((“Distance:”, distance, “cm”))

MQTT_Host = “192.168.1.5”
MQTT_Port = “1883”
MQTT_User = “pi”
MQTT_Password = “*********”
MQTT_Command = “distance”
MQTT_Command = [“mosquitto_pub”, “-h”, MQTT_Host, “-p”, MQTT_Port, “-u”, MQTT_User, “-P”, MQTT_Password, “-t”, “RPi/PIRLivingRoomBack”, “-r”, “-m”, “ON”]
ps = subprocess.Popen(MQTT_Command)

if distance < 5:
GPIO.output(MY_LED1,GPIO.HIGH)

else :
GPIO.output(MY_LED1,GPIO.LOW)

time.sleep(2)
]

and I got this output

SR04_MQTT.py:13: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(MY_LED1,GPIO.OUT)
SR04_MQTT.py:15: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(PIN_TRIGGER1, GPIO.OUT)
Waiting for sensor to settle
Calculating distance
(‘Distance:’, 7.18, ‘cm’)

if you can see any thing wrong?

Does the mqtt topic get the message?

Actually I don’t know how to get that data shown in UI of HA ,I tried some codes in configuration.yaml under sensor ,some thing with platform: mqtt ,but still didn’t get any data in UI ,if anybody has an idea about what should be written in configuration.yaml to get that data shown in the UI
Also I don’t get that error any more ,about “This channel is already in use”

Home assistant is well documented. Try https://www.home-assistant.io/components/sensor.mqtt/

Anyway, you didn’t answer my last question. Try https://www.home-assistant.io/docs/mqtt/testing/

The connection is OK ,and working
but what should be change in the code to send the distance, that’s my code

from gpiozero import LED
from signal import pause
import RPi.GPIO as GPIO
import time
import subprocess

GPIO.setmode(GPIO.BCM)

MY_LED1 = 14
PIN_TRIGGER1 = 23
PIN_ECHO1 = 24

GPIO.setwarnings(False)
GPIO.setup(MY_LED1,GPIO.OUT)
GPIO.setup(PIN_ECHO1, GPIO.IN)
GPIO.setup(PIN_TRIGGER1, GPIO.OUT)

print("Waiting for sensor to settle")


print("Calculating distance")

GPIO.output(PIN_TRIGGER1, GPIO.HIGH)

time.sleep(0.00001)

GPIO.output(PIN_TRIGGER1, GPIO.LOW)

while GPIO.input(PIN_ECHO1) == 0:
    pulse_start_time = time.time()
while GPIO.input(PIN_ECHO1) == 1:
    pulse_end_time = time.time()

pulse_duration = pulse_end_time - pulse_start_time
distance = round(pulse_duration * 17150, 2)
print(("Distance:", distance, "cm"))

MQTT_Host = "192.168.1.2"
MQTT_Port = "1883"
MQTT_User = "pi"
MQTT_Password = "test1234"
MQTT_Command = distance
MQTT_Command = ["mosquitto_pub", "-h", MQTT_Host, "-p", MQTT_Port, "-u", MQTT_User, "-P", MQTT_Password, "-t", "RPi/PIRLivingRoomBack", "-r", "-m", "distance"]
ps = subprocess.Popen(MQTT_Command)

if distance < 5:    
	GPIO.output(MY_LED1,GPIO.HIGH)

else :
    GPIO.output(MY_LED1,GPIO.LOW)

time.sleep(2)

and the output in HA is

Capture

In
MQTT_Command = ["mosquitto_pub", "-h", MQTT_Host, "-p", MQTT_Port, "-u", MQTT_User, "-P", MQTT_Password, "-t", "RPi/PIRLivingRoomBack", "-r", "-m", "distance"]
the “distance” is what appear in HA, is the error in that line ,or in other lines

remove the quotes around distance else it’ll indeed send the string “distance” as opposed to the value of distance
PS. you may want to amend the topic from “RPi/PIRLivingRoomBack” to something that actually means something to you than my living room PI sensor :wink:

I tried what you say,
and that what I got

Waiting for sensor to settle
Calculating distance
('Distance:', 5.78, 'cm')
Traceback (most recent call last):
  File "SR04_MQTT.py", line 44, in <module>
    ps = subprocess.Popen(MQTT_Command)
  File "/usr/lib/python2.7/subprocess.py", line 390, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1024, in _execute_child
    raise child_exception
TypeError: execv() arg 2 must contain only strings

the error gives the the explanation.
distance is a number and the function expects a string (TypeError: execv() arg 2 must contain only strings)
Replace "distance" with str(distance)

1 Like

thanks a lot, it works :smiley:
you really helped me

1 Like