Python Forum
Controller Buzzer as Distance Decreases
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Controller Buzzer as Distance Decreases
#2
The first thing that jumps out at me is that there is a lot of duplication in the functions distance and distance2 of which the names also give it away.
The only things that differ between them are trigger and echo so these can be passed into a single function.
def get_distance(trigger, echo):
    # set Trigger to HIGH
    GPIO.output(trigger, True)
  
    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(trigger, False)
  
    StartTime = time.time()
    StopTime = time.time()
  
    # save StartTime
    while GPIO.input(echo) == 0:
        StartTime = time.time()
  
    # save time of arrival
    while GPIO.input(echo) == 1:
        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 * 17150)
  
    return distance
then call it as follows
distance1 = get_distance(GPIO_TRIGGER, GPIO_ECHO)
distance2 = get_distance(GPIO2_TRIGGER, GPIO2_ECHO)
Reply


Messages In This Thread
RE: Controller Buzzer as Distance Decreases - by Yoriz - Oct-29-2021, 02:17 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python and DMX (aka, light controller) ScottAF 4 2,782 Apr-06-2023, 07:09 PM
Last Post: ScottAF
  How can flask find the controller? 3lnyn0 3 1,415 Jul-08-2022, 10:05 AM
Last Post: Larz60+
  Auto re-pair / re-sync Controller via Script? User3000 2 2,398 Nov-30-2020, 11:42 AM
Last Post: User3000
  Tuning PID controller Sancho_Pansa 4 4,487 Nov-09-2020, 07:51 AM
Last Post: Sancho_Pansa
  Xbox Controller arki 0 1,744 Jun-30-2020, 10:32 AM
Last Post: arki
  Please help! Akai APC20 midi controller script versusliveact 0 2,177 Feb-14-2020, 05:37 AM
Last Post: versusliveact
  Visualize Geo Map/Calculate distance zarize 1 1,936 Dec-05-2019, 08:36 PM
Last Post: Larz60+
  managing command codes for external controller box Oolongtea 0 1,951 Sep-19-2019, 08:32 AM
Last Post: Oolongtea
  euclidean distance jenya56 3 2,899 Mar-29-2019, 02:56 AM
Last Post: scidam
  organizing by distance gonzo620 7 4,043 Oct-16-2018, 01:41 AM
Last Post: stullis

Forum Jump:

User Panel Messages

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