import network
import time
import urequests
from machine import Pin, PWM, time_pulse_us
# ---------------- WIFI ----------------
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ---------------- THINGSPEAK ----------------
API_KEY = "Q5SK90EDJQW6BK1U"
# ---------------- ULTRASONIC SENSOR ----------------
trigger = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
# ---------------- SERVO ----------------
servo = PWM(Pin(15), freq=50)
# ---------------- OBJECT COUNT ----------------
count = 0
object_detected = False
# ---------------- WIFI CONNECT ----------------
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
print("Connecting to WiFi", end="")
while not wifi.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nWiFi Connected!")
# ---------------- DISTANCE FUNCTION ----------------
def get_distance():
trigger.off()
time.sleep_us(2)
trigger.on()
time.sleep_us(10)
trigger.off()
duration = time_pulse_us(echo, 1)
distance = (duration * 0.0343) / 2
return distance
# ---------------- SERVO FUNCTION ----------------
def set_angle(angle):
duty = int((angle / 180) * 102 + 26)
servo.duty(duty)
# ---------------- MAIN LOOP ----------------
while True:
distance = get_distance()
print("Distance:", distance)
# Object Detection
if distance < 30 and object_detected == False:
count += 1
object_detected = True
print("Object Count =", count)
# Open Gate
set_angle(90)
# Upload to ThingSpeak
url = "https://api.thingspeak.com/update?api_key={}&field1={}&field4={}".format(
API_KEY,distance,count
)
try:
response = urequests.get(url)
print("Uploaded to ThingSpeak")
response.close()
except:
print("Upload Failed")
# Reset detection
elif distance > 20:
object_detected = False
# Close Gate
set_angle(0)
time.sleep(2)