import network
from machine import Pin, PWM
import machine
import urequests
import time
READ_API_KEY = "8PZS5WWY120HW9Z8"
CHANNEL_ID = "2504476"
FIELD_NUMBER = 4
THRESHOLD = 30
# Function to connect to WiFi
def connect_to_wifi(ssid, password):
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
connect_to_wifi('Wokwi-GUEST', '')
SERVO_PIN = 2
servo = PWM(Pin(SERVO_PIN), freq=50) # Initialize servo motor
def fetch_leakage_data():
url = f"https://api.thingspeak.com/channels/{CHANNEL_ID}/fields/{FIELD_NUMBER}.json?api_key={READ_API_KEY}&results=1"
response = urequests.get(url)
if response.status_code == 200:
data = response.json()
feeds = data['feeds']
if feeds:
return float(feeds[0]['field' + str(FIELD_NUMBER)])
return None
# Main loop
while True:
leakage_value = fetch_leakage_data()
# Control servo based on distance
if leakage_value > THRESHOLD:
servo.duty(77) # Adjust duty cycle for the servo position
else:
servo.duty(30) # Adjust duty cycle for the servo position
print("Leakage: {:.2f} %".format(leakage_value))
time.sleep(3) # Wait for 3 seconds before the next measurement