# ---------------- IMPORTS ----------------
import network
import time
import urequests
from machine import Pin, ADC
# ---------------- WIFI CONFIG -----------------
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ---------------- THINGSPEAK CONFIG ----------------
API_KEY = "VBKV78DIV4T379S2" # <-- PUT YOUR Write API Key HERE
BASE_URL = "https://api.thingspeak.com/update"
# ---------------- HARDWARE SETUP ----------------
# Ultrasonic Sensor (HC-SR04)
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
# LDR (Analog Output connected to ADC)
ldr = ADC(26)
# Brake Light LED
brake_light = Pin(15, Pin.OUT)
# ---------------- THRESHOLDS ----------------
CRITICAL_DISTANCE = 50 # cm
NIGHT_THRESHOLD = 30000 # LDR ADC value (for reference)
# ---------------- WIFI CONNECTION ----------------
print("Connecting to WiFi...")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(1)
print("WiFi Connected")
print("System Active: Tesla Autopilot Simulation")
print("-" * 50)
# ---------------- FUNCTIONS ----------------
def measure_distance():
trigger.low()
time.sleep_us(2)
trigger.high()
time.sleep_us(10)
trigger.low()
while echo.value() == 0:
signal_off = time.ticks_us()
while echo.value() == 1:
signal_on = time.ticks_us()
time_passed = signal_on - signal_off
distance = (time_passed * 0.0343) / 2
return distance
def send_to_cloud(dist, light_level, event_type):
print(f"CLOUD: Uploading {event_type} event...")
try:
url = (
f"{BASE_URL}?api_key={API_KEY}"
f"&field1={dist:.1f}"
f"&field2={light_level}"
f"&field3={1 if event_type == 'BRAKE' else 0}"
)
response = urequests.get(url)
response.close()
print("CLOUD: Upload successful")
except:
print("CLOUD: Upload failed")
# ---------------- MAIN LOOP ----------------
last_cloud_update = 0
last_state = "DRIVING"
while True:
# 1️⃣ PERCEPTION (EDGE SENSING)
distance = measure_distance()
light_level = ldr.read_u16()
# 2️⃣ EDGE DECISION (REAL-TIME)
if distance < CRITICAL_DISTANCE:
brake_light.value(1)
current_state = "EMERGENCY_STOP"
print(f"EDGE: CRITICAL OBSTACLE at {distance:.1f} cm")
else:
brake_light.value(0)
current_state = "DRIVING"
print(f"EDGE: Driving safely ({distance:.1f} cm)")
# 3️⃣ CLOUD COMMUNICATION (OPTIMIZED)
current_time = time.time()
# Event-based upload
if current_state == "EMERGENCY_STOP" and last_state == "DRIVING":
send_to_cloud(distance, light_level, "BRAKE")
last_cloud_update = current_time
# Heartbeat upload every 20 seconds
elif (current_time - last_cloud_update) > 20:
send_to_cloud(distance, light_level, "HEARTBEAT")
last_cloud_update = current_time
last_state = current_state
time.sleep(0.5)