import machine
import utime
import dht
# Initialize UART for ESP8266
uart = machine.UART(0, baudrate=115200, tx=machine.Pin(0), rx=machine.Pin(1))
# Initialize DHT22 sensor
sensor = dht.DHT22(machine.Pin(15))
# Function to send AT command to ESP8266
def send_at_command(command, delay=1):
uart.write((command + '\r\n').encode())
utime.sleep(delay)
while uart.any():
print(uart.read().decode())
# Connect to WiFi
def connect_wifi(ssid, password):
send_at_command('AT+RST', 2)
send_at_command('AT+CWMODE=1')
send_at_command(f'AT+CWJAP="{ssid}","{password}"', 5)
# Send data to ThingSpeak
def send_to_thingspeak(api_key, temperature, humidity):
send_at_command('AT+CIPSTART="TCP","api.thingspeak.com",80', 2)
data = f"GET /update?api_key={api_key}&field1={temperature}&field2={humidity}"
send_at_command(f'AT+CIPSEND={len(data)+2}', 2)
uart.write((data + '\r\n').encode())
utime.sleep(2)
send_at_command('AT+CIPCLOSE', 1)
# Main program
ssid = 'POCO'
password = 'e77337aa59a3'
api_key = 'SVCBCXYLRRF9XQSS' # Replace with your ThingSpeak Write API Key
connect_wifi(ssid, password)
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print(f"Temperature: {temp}°C, Humidity: {hum}%")
send_to_thingspeak(api_key, temp, hum)
except Exception as e:
print('Error:', e)
utime.sleep(15)