Run python 3 Script for distance evaluation

Hey guys,

I have a Raspberry Pi Ultrasonic sensor, I want to measure the distance from the top of the cat-feeding-Automation-tank to the bottom, to find out how much food is still in it.

I saved it in /home/Sensor_Script.py

This is the Log error
[21:06:59] openhabian@openhab : /home $ python3 Sensor_Script.py

Traceback (most recent call last):

File “Sensor_Script.py”, line 52, in

abstand = distanz()

File “Sensor_Script.py”, line 22, in distanz

GPIO.output(GPIO_TRIGGER, True)

RuntimeError: Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM)

This is the Script

#Bibliotheken einbinden
import RPi.GPIO as GPIO
import time
import random
import statistics
from statistics import mean
##GPIO Modus (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.cleanup()
#GPIO Pins zuweisen
GPIO_TRIGGER = 6
GPIO_ECHO = 25
n=5

#Richtung der GPIO-Pins festlegen (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

def distanz():
# setze Trigger auf HIGH
GPIO.output(GPIO_TRIGGER, True)

# setze Trigger nach 0.01ms aus LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)

StartZeit = time.time()
StopZeit = time.time()

speichere Startzeit

while GPIO.input(GPIO_ECHO) == 0:
    StartZeit = time.time()

speichere Ankunftszeit

while GPIO.input(GPIO_ECHO) == 1:
    StopZeit = time.time()

Zeit Differenz zwischen Start und Ankunft

TimeElapsed = StopZeit - StartZeit

mit der Schallgeschwindigkeit (34300 cm/s) multiplizieren

und durch 2 teilen, da hin und zurueck

distanz = (TimeElapsed * 34300) / 2

return distanz

Messwerte = []

while True:
for i in range(n):
abstand = distanz()
Messwerte.append(abstand)

    time.sleep(1)
    GPIO.cleanup()

print(Messwerte)

print(statistics.stdev(Messwerte))

if statistics.stdev(Messwerte) <= 10:

print(“fertig”)

    avg = mean(Messwerte)
    print(round(avg,2))
    break
else:
    Messwerte.clear()

resets the GPIO pins that you defined as output to input mode again.
See e.g. RPi.GPIO basics 3 – How to Exit GPIO programs cleanly, avoid warnings and protect your Pi – RasPi.TV
GPIO.cleanup() should be used at the end of a program.

1 Like