"""
Using a Raspberry Pi distance sensor (ultrasonic sensor HC-SR04)
https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/
    
"""

import RPi.GPIO as GPIO
import time
import socket

# create a socket and bind socket to the host
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('192.168.1.100', 8002))
 
GPIO.setwarnings(False) 
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
 
#set GPIO Pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24
 
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
 
def distance():
    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)
 
    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)
 
    StartTime = time.time()
    StopTime = time.time()
 
    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()
 
    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()
 
    # time difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34300) / 2
 
    return distance
 
try:
    while True:
        dist = distance()
        print ("Measured Distance = %.1f cm" % dist)
        client_socket.send(str(dist))
        time.sleep(0.5)
 
finally:
    client_socket.close()
    GPIO.cleanup()