pythonraspberry-piintel-galileoarduino-ultra-sonic

Galileo and ultrasonic error when distance less than 4cm


Below is the code i ran on the Intel Galileo Gen2. I'm just wondering why when the object come really close to the ultrasonic sensor the program stops and complain about that the variable sig "local variable 'sig' referenced before assignment"?

import mraa
import time

trig = mraa.Gpio(0)
echo = mraa.Gpio(1)

trig.dir(mraa.DIR_OUT)
echo.dir(mraa.DIR_IN)


def distance(measure='cm'):
    trig.write(0)
    time.sleep(0.2)

    trig.write(1)
    time.sleep(0.00001)
    trig.write(0)

    while echo.read() == 0:
            nosig = time.time()

    while echo.read() == 1:
            sig = time.time()

    # et = Elapsed Time
    et = sig - nosig

    if measure == 'cm':
            distance =  et * 17150
    elif measure == 'in':
            distance = et / 0.000148
    else:   
            print('improper choice of measurement!!')
            distance = None

    return distance


while True:
    print(distance('cm'))

Solution

  • Your problem is that the spike produced by your sensor is too short to be noticed, as the sampling-frequency of your while echo.read() is limited.

    This then never defines the variable sig.

    To overcome this, define sig = None when entering the function, and then later test for it being None - then you know you can't use your measurement.

    If you want to sample with higher frequency, you need to use a language that is faster than Python, e.g. C++.