import network
import urequests
import time
import dht
from machine import Pin, Timer
# Wi-Fi settings
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Connect to Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print("waiting for connection...")
time.sleep(1)
# Check for successful connection
if wlan.status() != 3:
raise RuntimeError('Wi-Fi connection failed')
else:
print('Connected. IP address:', wlan.ifconfig()[0])
# ThingSpeak settings
WRITE_API_KEY = '8LQ9VBV5TLUQ5KQQ'
base_url = 'https://api.thingspeak.com/update'
# Initialize DHT22 sensor
dht_sensor = dht.DHT22(Pin(15))
# Initialize HC-SR04 sensor pins
trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
timer = Timer()
# Function to measure distance using HC-SR04
def measure_distance():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(5)
trig.low()
while echo.value() == 0:
pass
start = time.ticks_us()
while echo.value() == 1:
pass
end = time.ticks_us()
distance = (time.ticks_diff(end, start) / 1000000) * 340 / 2
return distance
# Function to read from sensors and upload to ThingSpeak
def read_and_upload():
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
distance = measure_distance()
# Assuming distance is measured every second, calculate speed as delta distance
# This is a placeholder, you need an actual method to measure changes in distance over time for speed
speed = distance
# Prepare the payload
payload = 'api_key=' + WRITE_API_KEY + '&field1=' + str(temp) + '&field2=' + str(hum) + '&field3=' + str(speed)
# Send the request
response = urequests.get(base_url + '?' + payload)
print(response.text)
response.close()
# Main loop
while True:
read_and_upload()
time.sleep(40)