import machine
import time
import json # The most important library for this module
import dht
# --- Configuration ----
DEVICE_ID = "PICO_W_BLDG_01"
LOCATION = "Server_Room"
# --- DHT22 Setup ---
# DHT22 DATA pin connected to GP15
sensor = dht.DHT22(machine.Pin(16))
print("Experiment 4.1: JSON Packaging Started (DHT22)...")
print("-" * 40)
while True:
try:
# 1. SENSE: Get Raw Data from DHT22
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# 2. STRUCTURE: Create a Python Dictionary (Schema)
data_dictionary = {
"sensor_id": DEVICE_ID,
"location": LOCATION,
"telemetry": {
"temp": round(temperature, 2),
"humidity": round(humidity, 2),
"unit": "Celsius"
},
"timestamp_ms": time.ticks_ms(), # Relative time since boot
"status": "OK"
}
# 3. TRANSLATE: Serialize to JSON String
json_packet = json.dumps(data_dictionary)
# 4. OUTPUT: Send to Console / Serial
print(f"RAW DICTIONARY: {data_dictionary}")
print(f"JSON PACKET: {json_packet}")
print(f"DATA TYPE: {type(json_packet)}")
except OSError:
print("Sensor read error")
print("-" * 40)
time.sleep(5)