import network
import dht
import machine
from machine import Pin,ADC
from time import sleep
#LDR setup
LDR = ADC(Pin(15, Pin.IN))
LDR.atten(ADC.ATTN_11DB)
led = Pin(4, Pin.OUT)
#servo motor setup
motor = machine.Pin(18, machine.Pin.OUT)
pwm = machine.PWM(motor)
pwm.freq(50)
pwm.duty(0)
def map(x, in_min, in_max, out_min, out_max):
return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
def servo(pin, angle):
pin.duty(map(angle, 0, 180, 20, 120))
#DHT setup
sensor = dht.DHT22(Pin(2))
#wifi setup
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
sleep(0.1)
print(" Connected!")
while True:
try:
#DHT22code
sleep(2)
sensor.measure()
temp = sensor.temperature()
temp_f = temp * (9/5) + 32.0
print('Temperature: %3.1f C' %temp)
print('Temperature: %3.1f F' %temp_f)
#LDR code
ldr_value = LDR.read()
if ldr_value < 2400: #dark
led.on()
elif ldr_value > 2500: #bright
led.off()
except OSError as e:
print('Failed to read sensor.')
#servo motor code
for i in range(0, 181, 10):
servo(pwm, i)
sleep(0.5)
for i in range(180, -1, -10):
servo(pwm, i)
sleep(0.5)