Python Forum
need help with ultrasonic sensor code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
need help with ultrasonic sensor code
#7
The best way is to use the @DeaD_EyE class.

To use your code, you can do something like:
#!/usr/bin/env python

import time
import RPi.GPIO as GPIO
import os

US1_GPIOTrigger = 23
US1_GPIOEcho = 24

# Change 0 to the GPIO of the US2
US2_GPIOTrigger = 0
US2_GPIOEcho = 0


def MesseDistanz(GPIOTrigger, GPIOEcho):

    GPIO.output(GPIOTrigger, True)

    time.sleep(0.00001)

    GPIO.output(GPIOTrigger, False)

    StartZeit = time.time()
    StopZeit = StartZeit

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

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

    SignalLaufzeit = StopZeit - StartZeit
    Distanz = (SignalLaufzeit / 2) * 34350

    return [Distanz, (SignalLaufzeit * 1000 / 2)]


def check_distance(distance, run_script):

    if distance < 10 and run_script:
        os.system('/home/pi/test.sh')
        run_script = False
    if distance >= 10:
        run_script = True

    return run_script


def main():

    try:
        US1_run_script = True
        US2_run_script = True
        while True:
            Ergebnis = MesseDistanz(US1_GPIOTrigger, US1_GPIOEcho)
            print("Gemessene Entfernung 1: %.1f cm (Signallaufzeit: %.4fms)" % (Ergebnis[0], Ergebnis[1]))
            US1_run_script = check_distance(Ergebnis[0], US1_run_script)

            Ergebnis = MesseDistanz(US2_GPIOTrigger, US2_GPIOEcho)
            print("Gemessene Entfernung 2: %.1f cm (Signallaufzeit: %.4fms)" % (Ergebnis[0], Ergebnis[1]))
            US2_run_script = check_distance(Ergebnis[0], US2_run_script)

            time.sleep(1)

    except KeyboardInterrupt:
        print("Messung abgebrochen")
        GPIO.cleanup()


if __name__ == '__main__':

    GPIO.setmode(GPIO.BCM)

    # UltraSonic 1
    GPIO.setup(US1_GPIOTrigger, GPIO.OUT)
    GPIO.setup(US1_GPIOEcho, GPIO.IN)
    GPIO.output(US1_GPIOTrigger, False)

    # UltraSonic 2
    GPIO.setup(US2_GPIOTrigger, GPIO.OUT)
    GPIO.setup(US2_GPIOEcho, GPIO.IN)
    GPIO.output(US2_GPIOTrigger, False)

    main()
Reply


Messages In This Thread
need help with ultrasonic sensor code - by mpmm366 - Jun-28-2018, 01:34 PM
RE: need help with ultrasonic sensor code - by gontajones - Jun-28-2018, 08:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  sensor code that starts heater chano 3 3,151 Jun-05-2019, 10:54 AM
Last Post: michalmonday
  Code Wireless Temperature sensor and send sensor readings to google sheet jenkins43 0 2,203 Nov-29-2018, 12:44 PM
Last Post: jenkins43
  RPi with IR Sensor pimlicosnail 1 2,208 Jun-24-2018, 08:53 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020