title: Controlling Relay Module with Ultrasonic Ranging Module on Raspberry Pi
body: <p>I'm trying to use Raspberry Pi Model B+ to create a program that uses an ultrasonic ranging module to control a relay module. I will use this thing I create to detect when a conveyor belt stops moving.  </p>
  
  <p>My program will rely on the ultrasonic ranging module to continuously measure the distance. Since there are objects on the conveyor belt, the distance will change continuously as objects move past the ultrasonic ranging module. So if the conveyor belt stops moving, the distance measured by the ultrasonic ranging module will stay the same. When this happens for 5 seconds, my program will turn off the relay module. </p>
  
  <p>My code isn't working right now. What is the problem? Here's what I have so far. (Also note I'm using a GPIO extension board for the ultrasonic ranging module and relay module.) </p>
  
  <pre><code>#!/usr/bin/env python
  
  import RPi.GPIO as GPIO
  import time
  
  TRIG = 11
  ECHO = 12
  RelayPin = 11    # pin11 
  
  def setup():
  
  GPIO.setmode(GPIO.BOARD)
  GPIO.setup(TRIG, GPIO.OUT)
  GPIO.setup(ECHO, GPIO.IN)
  
  GPIO.setup(RelayPin, GPIO.OUT)
  GPIO.output(RelayPin, GPIO.HIGH)  
  
  def distance():
  
      GPIO.output(TRIG, 0) 
  time.sleep(0.000002)
  
  GPIO.output(TRIG, 1)
  time.sleep(0.00001)
  GPIO.output(TRIG, 0)
  
  
  while GPIO.input(ECHO) == 0:
      a = 0
  time1 = time.time()
  while GPIO.input(ECHO) == 1:
      a = 1
  time2 = time.time()
  
  during = time2 - time1
  return during * 340 / 2 * 100
  
  def loop():
  
  while True:
      dis = distance()
  
      print dis, 'cm'
      print ''
      time.sleep(5)
      dis12 = distance() 
      if dis = dis2 
          GPIO.output(RelayPin, GPIO.LOW);    
  
  def destroy():
  
  GPIO.output(RelayPin, GPIO.HIGH)
  GPIO.cleanup()                     # Release resource
  
  if __name__ == '__main__':     # Program start from here
  setup()
  try:
      loop()
      except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
      destroy()
  </code></pre>