didzislauva

Untitled

Nov 19th, 2018
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. import RPi.GPIO as GPIO
  2. import time
  3.  
  4. trigPin = 16
  5. echoPin = 18
  6. MAX_DISTANCE = 220          #define the maximum measured distance
  7. timeOut = MAX_DISTANCE*60   #calculate timeout according to the maximum measured distance
  8.  
  9. def pulseIn(pin,level,timeOut): # function pulseIn: obtain pulse time of a pin
  10.     t0 = time.time()
  11.     while(GPIO.input(pin) != level):
  12.         if((time.time() - t0) > timeOut*0.000001):
  13.             return 0;
  14.     t0 = time.time()
  15.     while(GPIO.input(pin) == level):
  16.         if((time.time() - t0) > timeOut*0.000001):
  17.             return 0;
  18.     pulseTime = (time.time() - t0)*1000000
  19.     return pulseTime
  20.    
  21. def getSonar():     #get the measurement results of ultrasonic module,with unit: cm
  22.     GPIO.output(trigPin,GPIO.HIGH)      #make trigPin send 10us high level
  23.     time.sleep(0.00001)     #10us
  24.     GPIO.output(trigPin,GPIO.LOW)
  25.     pingTime = pulseIn(echoPin,GPIO.HIGH,timeOut)   #read plus time of echoPin
  26.     distance = pingTime * 340.0 / 2.0 / 10000.0     # the sound speed is 340m/s, and calculate distance
  27.     return distance
  28.    
  29. def setup():
  30.     print 'Program is starting...'
  31.     GPIO.setmode(GPIO.BOARD)       #numbers GPIOs by physical location
  32.     GPIO.setup(trigPin, GPIO.OUT)   #
  33.     GPIO.setup(echoPin, GPIO.IN)    #
  34.  
  35. def loop():
  36.     GPIO.setup(11,GPIO.IN)
  37.     while(True):
  38.         distance = getSonar()
  39.         print "The distance is : %.2f cm"%(distance)
  40.         time.sleep(1)
  41.        
  42. if __name__ == '__main__':     #program start from here
  43.     setup()
  44.     try:
  45.         loop()
  46.     except KeyboardInterrupt:  #when 'Ctrl+C' is pressed, the program will exit
  47.         GPIO.cleanup()         #release resource
Advertisement
Add Comment
Please, Sign In to add comment