import machine
import time
import urequests
import network
# Replace with your WiFi credentials
ssid = "Airtel 4G"
password = "8500182257@"
# ThingSpeak details
api_key = "1I3VSY9ALR9C4QFG"
channel_id = "2456546"
# Define GPIO pins
trig_pin = machine.Pin(15, machine.Pin.OUT)
echo_pin = machine.Pin(14, machine.Pin.IN)
def get_distance():
# Send a pulse
trig_pin.value(1)
time.sleep_us(10)
trig_pin.value(0)
# Measure pulse duration
start_time = time.ticks_us()
while echo_pin.value() == 0:
pass
start_time = time.ticks_us()
while echo_pin.value() == 1:
pass
pulse_duration = time.ticks_us() - start_time
# Calculate distance
distance_cm = pulse_duration * 0.034 / 2
return distance_cm
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(0.5)
print("Connected to WiFi")
while True:
connect_wifi() # Connect to WiFi on every loop
distance = get_distance()
print(f"Distance: {distance} cm")
# Send data to ThingSpeak
url = f"https://api.thingspeak.com/update.json"
headers = {'Content-Type': 'application/json'}
data = {'api_key': api_key, 'field1': distance}
response = urequests.post(url, headers=headers, json=data)
if response.status_code != 200:
print("Failed to send data to ThingSpeak:", response.text)
# Wait for a few seconds before sending the next data
time.sleep(15)