0

I am working on an obstacle avoiding robot using Raspberry pi 3 and an HC-S404 ultrasonic sensor. The distance measurement is perfect when trigger and echo are the only pins declared. Whenever, I declare another GPIO pin for motor/anything else, it stops reading.

import RPi.GPIO as GPIO
import time
 
#GPIO Mode (BOARD / BCM)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
 
#set GPIO Pins
GPIO_TRIGGER = 23
GPIO_ECHO = 24
Motor1A = 4
Motor1B = 17
Motor2A = 13
Motor2B = 26
#set GPIO direction (N / OUT)

GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
# GPIO.setup(Motor1A, GPIO.OUT)
# GPIO.setup(Motor1B, GPIO.OUT)
# GPIO.setup(Motor2A, GPIO.OUT)
# GPIO.setup(Motor2B, GPIO.OUT)

def distance():
    global GPIO_TRIGGER, GPIO_ECHO
    if GPIO.input(GPIO_ECHO):
        return (100)
    distance = 0
    GPIO.output(GPIO_TRIGGER, False)
    
    
    
    time.sleep(0.05)
    GPIO.output(GPIO_TRIGGER, True)
    dummy_variable = 0
    dummy_variable = 0
    GPIO.output(GPIO_TRIGGER, False)
    
    start_time, stop_time = time.time(), time.time()
    while not GPIO.input(GPIO_ECHO):
        stop_time = time.time()
        if (stop_time - start_time) > 0.02:
            distance = 100
            break
        
    if distance == 100:
        return (distance)
    while GPIO.input(GPIO_ECHO):
        stop_time = time.time()
        if (stop_time - start_time) > 0.02:
            distance = 100
            break
    if distance == 100:
        return (distance)
    TimeElapsed = stop_time - start_time
    distance = (TimeElapsed * 343) / 2
    return (distance)


if __name__ == '__main__':
    try:
        while True:
            dist = distance()
            print ("Measured Distance = %.1f m" % dist)
            time.sleep(1)
    except KeyboardInterrupt:
        print("Interrupted")
    except:
        print("other error")
    finally:
        GPIO.cleanup()

The above code prints the distance correctly. If the Motor pin declarations are uncommented, it prints distance as 100, the value that breaks out of the infinite loop. Any hint would be appreciated! Thanks in advance.

1
  • 1
    Solved, rookie mistake, didn't connect raspberry pi's ground to common.
    – Sri
    Jun 7 at 5:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.