Sam
Sam

Reputation: 39

Python Raspeberry Pi Zero 2W: Ultrasonic input pin is always zero -

I have an issue with ultrasonic Sensor using my Raspberry Pi 2W. The input pin is always zero. I tried to change pins, but nothing changed.

Here it is my sample code:

import RPi.GPIO as gp
import time
import signal
import sys


def handler(signum, frame):
    print('\nPulizia gpio')
    time.sleep(0.5)
    gp.cleanup()
    sys.exit()

inputPin = 12 # connect to echo via 1K resistor
outputPin = 13 # connect to trig
led = 7

gp.setmode(gp.BOARD)
gp.setup(outputPin,gp.OUT)
gp.setup(inputPin,gp.IN)
gp.setup(led,gp.OUT)
signal.signal(signal.SIGTSTP, handler)
print(outputPin)
print(inputPin)

l = gp.output(led,True)

o = gp.output(outputPin,True)

time.sleep(0.001)
o2 = gp.output(outputPin,False)

time.sleep(0.5)
l = gp.output(led,False)
print("Inizio a calcolare l'echo...")
while gp.input(inputPin) == 0:
        start = time.time()
gp.output(led,True)
while gp.input(inputPin) == 1:
        stop = time.time()
gp.output(led,False)
currentTime = stop - start
distance = currentTime / 0.000058

print("Distance is " + str(distance) + " cm")

gp.cleanup() here

I don't know what to to, i also used different sensors. Pins should work because i also tried a led and it turns on and off.

Upvotes: -1

Views: 61

Answers (1)

greekman
greekman

Reputation: 91

You need to wrap everything in a while True loop. This iwll make your code run continuously. Right now, it only executes once which is why you're not seeing any output.

Something like this should work for you:

import RPi.GPIO as gp
import time
import signal
import sys


def handler(signum, frame):
    print('\nPulizia gpio')
    time.sleep(0.5)
    gp.cleanup()
    sys.exit()

inputPin = 12 # connect to echo via 1K resistor
outputPin = 13 # connect to trig
led = 7

gp.setmode(gp.BOARD)
gp.setup(outputPin,gp.OUT)
gp.setup(inputPin,gp.IN)
gp.setup(led,gp.OUT)
signal.signal(signal.SIGTSTP, handler)
print(outputPin)
print(inputPin)
while True:
    l = gp.output(led,True)

    o = gp.output(outputPin,True)

    time.sleep(0.001)
    o2 = gp.output(outputPin,False)

    time.sleep(0.5)
    l = gp.output(led,False)
    print("Inizio a calcolare l'echo...")
    while gp.input(inputPin) == 0:
        start = time.time()
    gp.output(led,True)
    while gp.input(inputPin) == 1:
        stop = time.time()
    gp.output(led,False)
    currentTime = stop - start
    distance = currentTime / 0.000058

    print("Distance is " + str(distance) + " cm")

gp.cleanup()

Here's a resource as well. https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/

Upvotes: -1

Related Questions