import machine, time
import dht
from umqtt.simple import MQTTClient
import network
from math import log
sensor = dht.DHT22(machine.Pin(4)) # Assuming GPIO 4 for DHT22
def read_sensor():
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print('Temperature: {}°C, Humidity: {}%'.format(temp, hum))
return temp, hum
# WiFi credentials
ssid = 'Wokwi-GUEST' # Your WiFi SSID
password = '' # Your WiFi password
# ThingSpeak MQTT settings
mqtt_server = "mqtt3.thingspeak.com" # ThingSpeak MQTT server address
channel_id = "2496287" # Your ThingSpeak Channel ID
write_api_key = "KSJFGA0HWGPVZYOS" # Your ThingSpeak channel write API key
client_id = "GQs3MyM0EhgyNRwhMCQqEjE" # Client ID for MQTT connection (can be empty)
mqtt_user = "GQs3MyM0EhgyNRwhMCQqEjE"
mqtt_password = "dMsyE6A/C+PKRo1UtcHyobVZ"
# Connect to WiFi
station = network.WLAN(network.STA_IF) # Create a station interface for WiFi connection
station.active(True) # Activate the station interface
station.connect(ssid, password) # Connect to the WiFi network
while station.isconnected() == False: # Wait until the connection is successful
pass
print("Connection successful")
def send_to_thingspeak(temp, hum):
client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_password)
client.connect() # Connect to the MQTT server
client.publish("channels/2496287/publish/fields/field1", str(temp)) # Publish temp to the specified channel
client.publish("channels/2496287/publish/fields/field2", str(hum)) # Publish hum to the specified channel
client.disconnect()
led = machine.Pin(2, machine.Pin.OUT)
from machine import ADC, Pin
import math
# Initialize ADC
adc = ADC(Pin(34)) # Use the correct pin number here
adc.atten(ADC.ATTN_11DB) # For full range measurement
def read_ntc_temperature():
analog_value = adc.read()
# Ensure analog_value does not lead to a domain error in the logarithm
if analog_value <= 0 or analog_value >= 1023:
return None # Prevent math domain error
beta = 3950
try:
celsius_value = 1 / (math.log(1 / (1023. / analog_value - 1)) / beta + 1.0 / 298.15) - 273.15
except ValueError:
# Catch any other math domain errors and return None
return None
return celsius_value
temperature = read_ntc_temperature()
if temperature is not None:
print('Temperature: {:.2f}°C'.format(temperature))
else:
print('Error reading temperature or invalid value')
if celsius_value > 20:
led.on()
else:
led.off()
while True:
temp, hum = read_sensor() # Measure distance using the ultrasonic sensor
send_to_thingspeak(temp, hum) # Send the measured distance to ThingSpeak
print("Sent temperature:", temp, "to ThingSpeak") # Print confirmation message
print("Sent humidity:", hum, "to ThingSpeak") # Print confirmation message
time.sleep(5)