import machine
import onewire
import ds18x20
import time
import network
import urequests # For making HTTP requests
# Wi-Fi credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ThingSpeak API key
THINGSPEAK_API_KEY = "1FC7IXABIKFSXVXJ"
THINGSPEAK_URL = "https://api.thingspeak.com/update"
# Connect to Wi-Fi
print("Connecting to WiFi...", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
ip = wlan.ifconfig()[0]
print(f"Device IP: {ip}")
wait = 10
while wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
wait -= 1
print('Waiting for connection...')
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError('Network connection failed')
else:
print('Wi-Fi connected!')
print('IP:', wlan.ifconfig()[0])
data_pin = machine.Pin(2)
ow = onewire.OneWire(data_pin)
ds = ds18x20.DS18X20(ow)
roms = ds.scan()
if roms:
print("Found DS18B20 devices:", roms)
else:
print("No DS18B20 devices found. Check your circuit or connections.")
def send_to_thingspeak(temp):
try:
response = urequests.get(f"{THINGSPEAK_URL}?api_key={THINGSPEAK_API_KEY}&field1={temp}")
if response.status_code == 200:
print(f"Data sent to ThingSpeak: {temp} °C")
else:
print(f"Failed to send data to ThingSpeak. Status code: {response.status_code}")
response.close()
except Exception as e:
print(f"Error sending data to ThingSpeak: {e}")
while roms:
print("Reading temperature...")
ds.convert_temp()
time.sleep(1) # Wait for the conversion to complete
for rom in roms:
temp = ds.read_temp(rom)
if temp is not None:
print(f"Temperature: {temp:.2f} °C")
send_to_thingspeak(temp)
else:
print("Error reading temperature. Check your connections.")
time.sleep(2)
print("Script Stopped")