總網頁瀏覽量

2014年4月25日 星期五

樹莓派超音波測距 = Raspberry + Ultrasonic HC-SR04 + MotoPiduino


一. 使用材料:
       1. Raspberry Pi
       2. MotoPiduino
       3. 超音波 HC-SR04
       4. S4A IO Board (option)

二. 接線:
      1. 把 HC-SR04 接到 MotoPiduino D10 及 D11 位置, (樹莓派 GPIO8(TRIGGER) 和 GPIO10(ECHO) 位置)
       或
      直接接到 S4A IO Board 的 D10 D11孔位

三. 接線方式如圖:
     
      



4. 編寫程式:
# -----------------------

# Import required Python libraries
# -----------------------
import time
import RPi.GPIO as GPIO

# -----------------------
# Define some functions
# -----------------------

def measure():
  # This function measures a distance

  GPIO.output(GPIO_TRIGGER, True)
  time.sleep(0.00001)
  GPIO.output(GPIO_TRIGGER, False)
  start = time.time()
  
  while GPIO.input(GPIO_ECHO)==0:
    start = time.time()

  while GPIO.input(GPIO_ECHO)==1:
    stop = time.time()

  elapsed = stop-start
  distance = (elapsed * 34300)/2

  return distance

def measure_average():
  # This function takes 3 measurements and
  # returns the average.

  distance1=measure()
  time.sleep(0.1)
  distance2=measure()
  time.sleep(0.1)
  distance3=measure()
  distance = distance1 + distance2 + distance3
  distance = distance / 3
  return distance

# -----------------------
# Main Script
# -----------------------

# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)

# Define GPIO to use on Pi
GPIO_TRIGGER = 8
GPIO_ECHO    = 10

print "Ultrasonic Measurement"

# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)

try:

  while True:

    distance = measure_average()
    print "Distance : %.1f" % distance
    time.sleep(1)

except KeyboardInterrupt:
  # User pressed CTRL-C
  # Reset GPIO settings
  GPIO.cleanup()


五. 相關資訊:
相關資訊: http://motoduino.com


沒有留言:

張貼留言