Facebook
From Kaan Oztuzun, 9 Months ago, written in Python.
Embed
Download Paste or View Raw
Hits: 170
  1. import RPi.GPIO as GPIO
  2. import time
  3.  
  4. # GPIO ayarları
  5. GPIO.setmode(GPIO.BCM)
  6. TRIG = 23
  7. ECHO = 24
  8.  
  9. GPIO.setup(TRIG, GPIO.OUT)
  10. GPIO.setup(ECHO, GPIO.IN)
  11.  
  12. def measure_distance():
  13.     # Trig pinini düşük yap ve bekle
  14.     GPIO.output(TRIG, False)
  15.     time.sleep(2)
  16.  
  17.     # Trig pinini yüksek yap ve kısa bir süre sonra tekrar düşük yap
  18.     GPIO.output(TRIG, True)
  19.     time.sleep(0.00001)
  20.     GPIO.output(TRIG, False)
  21.  
  22.     # Echo pininden gelen sinyali ölç
  23.     while GPIO.input(ECHO) == 0:
  24.         pulse_start = time.time()
  25.  
  26.     while GPIO.input(ECHO) == 1:
  27.         pulse_end = time.time()
  28.  
  29.     pulse_duration = pulse_end - pulse_start
  30.  
  31.     # Mesafeyi hesapla
  32.     distance = pulse_duration * 17150
  33.     distance = round(distance, 2)
  34.     return distance
  35.  
  36. try:
  37.     while True:
  38.         dist = measure_distance()
  39.         print("Distance: {} cm".format(dist))
  40.         time.sleep(1)
  41.  
  42. except KeyboardInterrupt:
  43.     GPIO.cleanup()
  44.