forked from hamuchiwa/AutoRCCar
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
""" | ||
Reference: | ||
Ultrasonic Distance Measurement Using Python – Part 2 | ||
http://www.raspberrypi-spy.co.uk/2013/01/ultrasonic-distance-measurement-using-python-part-2/ | ||
""" | ||
|
||
from socket import * | ||
import time | ||
import RPi.GPIO as GPIO | ||
|
||
|
||
GPIO.setwarnings(False) | ||
|
||
# create a socket and bind socket to the host | ||
client_socket = socket(AF_INET, SOCK_STREAM) | ||
client_socket.connect(('192.168.1.100', 8002)) | ||
|
||
def measure(): | ||
""" | ||
measure 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 | ||
|
||
# referring to the pins by GPIO numbers | ||
GPIO.setmode(GPIO.BCM) | ||
|
||
# define pi GPIO | ||
GPIO_TRIGGER = 23 | ||
GPIO_ECHO = 24 | ||
|
||
# output pin: Trigger | ||
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) | ||
# input pin: Echo | ||
GPIO.setup(GPIO_ECHO,GPIO.IN) | ||
# initialize trigger pin to low | ||
GPIO.output(GPIO_TRIGGER, False) | ||
|
||
try: | ||
while True: | ||
distance = measure() | ||
print "Distance : %.1f cm" % distance | ||
# send data to the host every 0.5 sec | ||
client_socket.send(str(distance)) | ||
time.sleep(0.5) | ||
finally: | ||
client_socket.close() | ||
GPIO.cleanup() |