Advertisement
cymplecy

ultra

Apr 10th, 2018
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1.     def pinSonar(self, pin):
  2.         #print pin
  3.         #print self.pinUse[pin]        
  4.         self.pinUse[pin] = self.PSONAR
  5.         GPIO.setup(pin,GPIO.OUT)
  6.         ti = time.time()
  7.         # setup a list to hold 3 values and then do 3 distance calcs and store them
  8.         #print 'sonar started'
  9.         distlist = [0.0,0.0,0.0]
  10.         distance = 0
  11.         ts=time.time()
  12.         try:
  13.             for k in range(3):
  14.                 #print "sonar pulse" , k
  15.                 GPIO.output(pin, 0)
  16.                 time.sleep(0.05)#set pin low for 50ms as per spec
  17.                 GPIO.output(pin, 1)    # Send Pulse high
  18.                 time.sleep(0.00001)     #  wait
  19.                 GPIO.output(pin, 0)  #  bring it back low - pulse over.
  20.                 t0=time.time() # remember current time
  21.                 GPIO.setup(pin,GPIO.IN)
  22.                 #PIN_USE[i] = PINPUT don't bother telling system
  23.  
  24.                 t1=t0
  25.                 # This while loop waits for input pin (7) to be low but with a 0.04sec timeout
  26.                 while ((GPIO.input(pin)==0) and ((t1-t0) < 0.02)):
  27.                     #time.sleep(0.00001)
  28.                     t1=time.time()
  29.                 t1=time.time()
  30.                 #print 'low' , (t1-t0).microseconds
  31.                 t2=t1
  32.                 #  This while loops waits for input pin to go high to indicate pulse detection
  33.                 #  with 0.04 sec timeout
  34.                 while ((GPIO.input(pin)==1) and ((t2-t1) < 0.02)):
  35.                     #time.sleep(0.00001)
  36.                     t2=time.time()
  37.                 t2=time.time()
  38.                 #print 'high' , (t2-t1).microseconds
  39.                 t3=(t2-t1)  # t2 contains time taken for pulse to return
  40.                 #print "total time " , t3
  41.                 distance=t3*343/2*100  # calc distance in cm
  42.                 distlist[k]=distance
  43.                 #print distance
  44.                 GPIO.setup(pin,GPIO.OUT)
  45.             tf = time.time() - ts
  46.             distance = sorted(distlist)[1] # sort the list and pick middle value as best distance
  47.         except:
  48.             pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement