import machine
import time
import json # The most important library for this module
# --- Configuration ---
DEVICE_ID = "PICO_W_BLDG_01"
LOCATION = "Server_Room"
# Setup Internal Temp Sensor
sensor_temp = machine.ADC(4)
conversion_factor = 3.3 / 65535
print("Experiment 4.1: JSON Packaging Started...")
print("-" * 40)
while True:
# 1. SENSE: Get Raw Data
reading = sensor_temp.read_u16() * conversion_factor
temperature = 27 - (reading - 0.706)/0.001721
# 2. STRUCTURE: Create a Python Dictionary
# This is where we define the 'Schema' or the identity of our data
data_dictionary = {
"sensor_id": DEVICE_ID,
"location": LOCATION,
"telemetry": {
"temp": round(temperature, 2),
"unit": "Celsius"
},
"timestamp_ms": time.ticks_ms(), # Relative time since boot
"status": "OK"
}
# 3. TRANSLATE: Serialize to JSON String
# 'json.dumps' (Dump String) turns the dictionary into a standardized JSON text
json_packet = json.dumps(data_dictionary)
# 4. OUTPUT: Send to Console/Serial
# In a real IoT system, this string would be sent to an MQTT Broker or Web API
print(f"RAW DICTIONARY: {data_dictionary}")
print(f"JSON PACKET: {json_packet}")
# Verification of data type
print(f"DATA TYPE: {type(json_packet)}")
print("-" * 40)
time.sleep(5)
Loading
pi-pico-w
pi-pico-w