import machine
import time
import urequests
import network
import ujson
# ThingSpeak settings
THINGSPEAK_API_KEY = "NEJ4AU0GAQ1WBS8R"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# Wi-Fi settings
WIFI_SSID = "Kabix"
WIFI_PASSWORD = "Kabix_xii"
# Ultrasonic sensor pins
TRIG_PIN = machine.Pin(5, machine.Pin.OUT)
ECHO_PIN = machine.Pin(12, machine.Pin.IN)
# Function to read distance from ultrasonic sensor
def read_distance():
TRIG_PIN.value(1)
time.sleep_us(10)
TRIG_PIN.value(0)
while ECHO_PIN.value() == 0:
pulse_start = time.ticks_us()
while ECHO_PIN.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
distance = pulse_duration * 0.0343 / 2 # Speed of sound in cm/us
return distance
# Function to send data to ThingSpeak
def send_data_to_thingspeak(distance):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": distance
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
response.close()
# Initialize the Wi-Fi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
# Wait for the Wi-Fi connection to establish
while not wifi.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
if __name__ == "__main__":
try:
while True:
distance = read_distance()
send_data_to_thingspeak(distance)
print("Data sent to ThingSpeak: Distance =", distance, "cm")
time.sleep(15) # Send data every 15 seconds (adjust the interval as needed)
except KeyboardInterrupt:
pass