import RPi.GPIO as a
import time 
import requests

Thingspesk_Url="https://api.thingspeak.com/update"

Api_key=""

trig=17
echo=18

a.setmode(a.BCM)
a.setwarnings(False)
a.setup(trig, a.OUT)
a.setup(echo, a.IN)

def get_distance():
    a.output(trig, True)
    time.sleep(0.00001)
    a.output(trig, False)

    while a.input(echo)==0:
        pulse_start=time.time()

    while a.input(echo)==1:
        pulse_end=time.time()

    pulse_duration=pulse_end-pulse_start
    distance=pulse_duration*17150

    return round(distance, 2)

try:
    while True:
        distance=get_distance()
        print(f"Distance: {distance}cm")

        params={"api_key":api_key, "field1":distance}
        
        response = requests.post(Thingspesk_Url, params=params)

        print(f"Thingspeak Response:{response.status_code}")

        time.sleep(10)
except KeyboardInterrupt:
    a.cleanup()