Problem importing python output with command_line

Im trying to import distance from a hc-sr04 (ultrasonic sensor) with a python script by using command_line platform but i only get “Command failed: python3 /home/pi/rpi-examples/HC-SR04/python/distance.py” in my logs… the script works if i run it in the terminal.

this is from my config file.

  • platform: command_line
    name: pellets
    scan_interval: 5
    command: “python3 /home/pi/rpi-examples/HC- SR04/python/distance.py”
    unit_of_measurement: “C”

and this is from my python script
import RPi.GPIO as GPIO
import time
import signal
import sys

# use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BCM)

# set GPIO Pins
pinTrigger = 18
pinEcho = 24

def close(signal, frame):
    print("\nTurning off ultrasonic distance detection...\n")
    GPIO.cleanup() 
    sys.exit(0)

signal.signal(signal.SIGINT, close)

# set GPIO input and output channels
GPIO.setup(pinTrigger, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)

while True:
    # set Trigger to HIGH
    GPIO.output(pinTrigger, True)
    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(pinTrigger, False)

    startTime = time.time()
    stopTime = time.time()

    # save start time
    while 0 == GPIO.input(pinEcho):
        startTime = time.time()

    # save time of arrival
    while 1 == GPIO.input(pinEcho):
        stopTime = time.time()

    # time difference between start and arrival
    TimeElapsed = stopTime - startTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34300) / 2

    print ("%.1f " % distance)
    time.sleep(1)
    GPIO.cleanup() 
    quit()

maby im thinking this all wrong? shouldnt ha be able to extract the printed value? im noob at both ha and python :stuck_out_tongue:

if i do this it works like a charm

print(“35”)

You need to check it works when using the same user as HA. So for hassbian, make sure the script runs as expected as homeassistant user.

Thanks gpbenton!
the script didnt run as expected.

i logged in as homeassistant venv user and noticed that the rpi.gpio wasnt installed in the venv, i installed it and now it works :slight_smile:

so i did:

$ sudo -u homeassistant -H -s
$ source /srv/homeassistant/bin/activate

ran:

python3 /home/pi/rpi-examples/HC-SR04/python/distance1.py

got:

Traceback (most recent call last):
File “/home/pi/rpi-examples/HC-SR04/python/distance1.py”, line 2, in module import RPi.GPIO as GPIO

ran:

pip3 install RPi.GPIO

and it works :slight_smile:

1 Like