1

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'))
0andriy
  • 4,183
  • 1
  • 24
  • 37
Jedani
  • 83
  • 1
  • 2
  • 9

2 Answers2

2

The problem is:

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

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

if the first condition is met and has not returned to 1 by the time the next line is read then sig will never get a value.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
  • I agree Steve .. this is the ultrasonic sensor datasheet http://www.micropik.com/PDF/HCSR04.pdf it says the min distance is 2 cm!! – Jedani Aug 30 '15 at 18:58
  • @Jedan see my answer - your sample-rate is too low. – deets Aug 30 '15 at 19:00
2

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++.

deets
  • 6,285
  • 29
  • 28