import machine
import time
import json
import dht
DEVICE_ID = "VARSHITHA_17"
LOCATION = "Server_Room"
# Initialize DHT22 on Pin 16
sensor = dht.DHT22(machine.Pin(16))
print("experiment 4.1: JSON packaging Started (DHT22)...")
print("-" * 40)
while True:
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# FIXED: Changed 'data.dictionary' to 'data_dictionary'
data_dictionary = {
"sensor_id": DEVICE_ID,
"location": LOCATION,
"telemetry": {
"temp": round(temperature, 2),
"humidity": round(humidity, 2),
"unit": "celsius"
},
"timestamp_ms": time.ticks_ms(),
"status": "OK"
}
# Convert dictionary to a JSON string
json_packet = json.dumps(data_dictionary)
# FIXED: Used lowercase 'json_packet' to match definition
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)