import network # Library for Wi-Fi connection
import machine
import utime
import dht
import urequests # HTTP requests library
# Pin configuration for DHT22
DATA_PIN = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
sensor = dht.DHT22(DATA_PIN)
# Power BI streaming dataset URL
POWER_BI_URL = "https://api.powerbi.com/beta/dbd6664d-4eb9-46eb-99d8-5c43ba153c61/datasets/ecc802ee-394f-44bc-b299-1763e33a3dcc/rows?experience=power-bi&key=all2WgQ9aro4l5y38hEciqHStAzvTycB6EBo42iUJbVsFJPBDDK3w2CXFNDmHjZ4%2FpOUWp3hwM3%2FYX7U04UW9A%3D%3D"
# Wi-Fi Credentials
WIFI_SSID = "Wokwi-GUEST" # Replace with your Wi-Fi network name
WIFI_PASSWORD = "" # Replace with your Wi-Fi password
# Function to connect to Wi-Fi
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to Wi-Fi...")
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
utime.sleep(1) # Wait until connected
print("Wi-Fi connected:", wlan.ifconfig())
# Function to send data to Power BI
def send_to_power_bi(temp, humidity):
try:
# Step 1: Test Internet Connectivity
try:
response = urequests.get("http://clients3.google.com/generate_204")
if response.status_code == 204:
print("Internet connection OK")
response.close()
else:
print("Internet test failed")
response.close()
return # Exit if there is no internet connection
except Exception as e:
print("No internet connection:", e)
return # Exit the function if no internet
# Step 2: Prepare and Send Data
timestamp = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(*utime.localtime()[:6])
payload = [{
"temperature1": temp,
"humidity1": humidity,
"timestamp1": timestamp
}]
headers = {'Content-Type': 'application/json'}
print("Payload:", payload) # Debug print
response = urequests.post(POWER_BI_URL, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 202:
print("Data sent successfully to Power BI")
else:
print("Failed to send data. Status code:", response.status_code)
print("Response:", response.text)
response.close()
except Exception as e:
print("Error sending data to Power BI:", e)
def read_and_display_data():
try:
sensor.measure() # Take sensor measurements
temp = sensor.temperature()
humidity = sensor.humidity()
# Display readings
print("Temperature: {:.2f}°C, Humidity: {:.2f}%".format(temp, humidity))
# Send data to Power BI
send_to_power_bi(temp, humidity)
except Exception as e:
print("Error reading sensor data:", e)
# Main Script
connect_to_wifi() # Connect to Wi-Fi before running the main loop
while True:
read_and_display_data()
utime.sleep(5) # Wait 5 seconds before next reading