Controlling DC motor with Raspberry Pi & Python

First attempt to control DC motor using my Raspberry Pi B+ .the motor spin freely till the measured distance is less than 8 cm.
the ultrasonic sensor is responsible for measuring the distance. I have written the code that control the motor and measure the distance using Python .

import time
import RPi.GPIO as GPIO
trigger_pin =12
echo_pin = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
GPIO.setup(trigger_pin,GPIO.OUT)
GPIO.setup(trigger_pin,GPIO.IN)
def send_trigger():
GPIO.output(trigger_pin ,True)
time.sleep(0.0001)
GPIO.output(trigger_pin ,False)
def wait_echo(value,timeout):
count = timeout
while GPIO.input(echo_pin) != value and count > 0 :
count = count -1
def get_distance()
send_trigger()
wait_echo(True,10000)
start = time.time()
wait_echo(True,10000)
finish= time.time()
pulse_len = finish – start
dis_cm = pulse_len / 0.000058
return dis_cm
while True:
dis = get_distance()
GPIO.output(13,Flase)
GPIO.output(15,True)
time.sleep(1)
if dis < 8 :
break
GPIO.cleanup()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s