from machine import Pin, ADC, time_pulse_us
import network
import urequests
import time
from dht import DHT22
# Constants
SOUND_SPEED = 340 # Speed of sound in air (cm/s)
TRIG_PULSE_DURATION_US = 10
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
THINGSPEAK_WRITE_API_KEY = '1AC7Y76NLKO6K5PC'
HTTP_HEADERS = {'Content-Type': 'application/json'}
# Initialize sensors
dht22 = DHT22(Pin(13))
trig_pin = Pin(12, Pin.OUT)
echo_pin = Pin(14, Pin.IN)
class LDR:
"""Class to read from a Light Dependent Resistor (LDR)."""
def __init__(self, pin, min_value=0, max_value=100):
if min_value >= max_value:
raise ValueError('Min value must be less than max value')
self.adc = ADC(Pin(pin))
self.adc.atten(ADC.ATTN_11DB)
self.min_value = min_value
self.max_value = max_value
def read(self):
"""Read raw value from the LDR."""
return self.adc.read()
def value(self):
"""Get the value from LDR in the specified range."""
return (self.max_value - self.min_value) * self.read() / 4095 + self.min_value
ldr = LDR(34)
def connect_wifi():
"""Connect to the Wi-Fi network."""
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
timeout = 0
while not wifi.isconnected() and timeout < 10:
print(f'Connecting... ({10 - timeout}s remaining)')
timeout += 1
time.sleep(1)
if wifi.isconnected():
print('Connected to WiFi')
print('Network config:', wifi.ifconfig())
else:
print('Failed to connect to WiFi')
sys.exit()
connect_wifi() # Connect to WiFi
while True:
trig_pin.value(0)
time.sleep_us(5)
trig_pin.value(1)
time.sleep_us(TRIG_PULSE_DURATION_US)
trig_pin.value(0)
try:
ultrason_duration = time_pulse_us(echo_pin, 1, 30000)
distance_cm = SOUND_SPEED * ultrason_duration / 20000
print(f"Distance: {distance_cm:.2f} cm")
except OSError as e:
print("Error reading from ultrasonic sensor:", e)
distance_cm = 0
dht22.measure()
temp = dht22.temperature()
hum = dht22.humidity()
print(f"Temperature: {temp:.2f}°C")
print(f"Humidity: {hum:.2f}%")
ldr_value = ldr.value()
print(f"Luminous intensity = {ldr_value:.2f} lux")
dht_readings = {
'field1': hum,
'field2': temp,
'field3': distance_cm,
'field4': ldr_value
}
try:
request = urequests.post(
f'http://api.thingspeak.com/update?api_key={THINGSPEAK_WRITE_API_KEY}',
json=dht_readings,
headers=HTTP_HEADERS
)
request.close()
print("Data sent to ThingSpeak successfully")
except Exception as e:
print("Error sending data to ThingSpeak:", e)
print("********************************************")
time.sleep(60) # Adjust the sleep time as needed