Project 3.9.29: Smart Environmental Iot Infrastructure
Advanced Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython
Overview
The Pico acts as an infrastructure-style environmental node that reports sensor health, heartbeat timing, and local readings to a local endpoint.
An IoT deployment is difficult to maintain when nodes report sensor data but not their own health and heartbeat status.
A Pico 2 W prototype with an MQ-5 Liquefied Petroleum/Methane Gas Sensor, BME280, heartbeat LED, local status log, and optional Wi-Fi reporting.
Node-health reporting, structured heartbeat records, and honest infrastructure-prototype wording.
Required Components
![]() Raspberry Pi Pico 2 W |
![]() Soil sensor |
![]() Breadboard |
![]() Jumper wires |
![]() LED |
![]() Resistor |
![]() BME280 |
|
| --- |
Circuit Connections
| Component terminal | Connect to | Pico physical pin | Notes |
|---|---|---|---|
| MQ-5 AO | GPIO 26 ADC0 | GPIO 26 / physical pin 31 | LPG/methane gas proxy input |
| BME280 VCC | 3.3V output | Physical pin 36 | Sensor power |
| BME280 GND | GND | Physical pin 38 | Common ground |
| BME280 SDA | GPIO 20 | GPIO 20 / physical pin 26 | I2C0 SDA |
| BME280 SCL | GPIO 21 | GPIO 21 / physical pin 27 | I2C0 SCL |
| LED anode | 220 ohm resistor to GPIO 16 | GPIO 16 / physical pin 21 | Heartbeat LED |
| --- |
Wiring Diagram

MQ-5 AO -> GPIO 26
BME280 SDA -> GPIO 20
BME280 SCL -> GPIO 21
GPIO 16 -> LED via 220 ohm
BME280 VCC -> 3.3V
BME280 GND -> GND
Wi-Fi uses the Pico 2 W radio and needs no extra wiring
Step-by-Step Assembly
- Connect the MQ-5 analog output to GPIO 26 through a safe ADC path.
- Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
- Connect the LED to GPIO 16 through a 220 ohm resistor.
- Enter the Wi-Fi credentials and local endpoint only after the local heartbeat record is being generated correctly.
- Warm up the gas sensor before comparing infrastructure records across time.
Testing Individual Components
Before running the full project, test each subsystem separately. This makes it easier to find wiring, library, or logic problems before full integration.
- Hardware setup: Assemble the Pico, sensor, indicator, and load wiring exactly as shown in the connection table before applying power.
- Test the input sensor: Test the gas sensor and BME280 separately so the health record fields are believable.
- Test the output device: Blink the LED with a short script so the heartbeat indicator is confirmed.
- Test the decision logic: Confirm that the record sequence number increases and that sensor_ok changes if the BME280 fails.
- Run the full system: Run the full node and compare the local heartbeat log with any uploaded server record.
- Validate the prototype: Discuss what other infrastructure fields would be needed in a larger deployment.
- Save the project: Save the validated program on the Pico as main.py and keep a copy on the computer for future edits.
Full Project Code
After completing and checking the circuit connections, open Thonny IDE, copy and paste this code into a new file or upload the project file to the Raspberry Pi Pico 2 W, then run it from Thonny.
import bme280
import network
import socket
import time
import ujson as json
from machine import ADC, I2C, Pin
GAS_PIN = 26
BME_SDA_PIN = 20
BME_SCL_PIN = 21
LED_PIN = 16
LOG_FILE = 'infra_309.jsonl'
UPLOAD_ENABLED = False
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
SERVER_HOST = '192.168.1.50'
SERVER_PORT = 8000
SERVER_PATH = '/infrastructure'
INTERVAL_S = 60
mq5 = ADC(GAS_PIN)
i2c = I2C(0, sda=Pin(BME_SDA_PIN), scl=Pin(BME_SCL_PIN), freq=400000)
climate = bme280.BME280(i2c=i2c)
led = Pin(LED_PIN, Pin.OUT)
sequence = 0
def connect_wifi(timeout_s=15):
wlan = network.WLAN(network.STA_IF)
if wlan.isconnected():
return wlan
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
for _ in range(timeout_s):
if wlan.isconnected():
return wlan
time.sleep(1)
return None
def append_record(record):
try:
with open(LOG_FILE, 'a') as handle:
handle.write(json.dumps(record) + '\n')
except OSError:
print('Could not write local infrastructure record')
def upload_record(record):
if not UPLOAD_ENABLED:
return False
wlan = connect_wifi()
if wlan is None:
return False
address = socket.getaddrinfo(SERVER_HOST, SERVER_PORT)[0][-1]
body = json.dumps(record)
request = 'POST {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}'.format(
SERVER_PATH,
SERVER_HOST,
len(body),
body,
)
sock = socket.socket()
try:
sock.connect(address)
sock.send(request.encode())
sock.recv(128)
return True
finally:
sock.close()
def blink():
led.on()
time.sleep_ms(120)
led.off()
print('Environmental IoT infrastructure node ready')
while True:
sequence += 1
sensor_ok = True
try:
values = climate.values
temperature = float(values[0].replace('C', ''))
pressure = float(values[1].replace('hPa', ''))
humidity = float(values[2].replace('%', ''))
except OSError:
temperature = 0
sensor_ok = False
record = {
'device_id': 'infra_309',
'sequence': sequence,
'uptime_s': time.ticks_ms() // 1000,
'gas_raw': mq5.read_u16(),
'temperature_c': temperature,
'sensor_ok': sensor_ok,
}
append_record(record)
uploaded = upload_record(record)
print(record, 'uploaded' if uploaded else 'local_only')
blink()
time.sleep(INTERVAL_S)
How the Code Works
| Code Section | What It Does | Why It Matters | What to Modify During Testing |
|---|---|---|---|
| Heartbeat record | Creates a record that includes both sensor values and node-health fields | Infrastructure visibility is about node state as much as sensor data | Add new fields only when you can validate them consistently |
| sensor_ok flag | Tracks whether the BME280 read succeeded in the current cycle | Node health should show whether data quality is trustworthy | Extend the same idea to other sensors if the node grows later |
| append_record and upload_record | Store the heartbeat locally first, then optionally upload it | Local-first logging helps infrastructure debugging when networking is unstable | Inspect the local file before assuming the upload path is the failure point |
| Heartbeat LED | Shows a visible pulse each infrastructure cycle | A visible heartbeat is useful even before the network tools are ready | If the LED blinks but records are missing, debug storage or networking next |
Expected Result
The serial monitor reports the current reading or state clearly.
The hardware output responds when the decision logic changes state.
Subsystem behavior matches the thresholds, timing, or rules described in the document.
Validation Checks
- Normal condition test: confirm the system stays in its safe or idle state under baseline conditions
- Warning condition test: move the input close to the chosen threshold and confirm the transition is sensible
- Critical condition test: trigger the strongest alert or control state and confirm the output response is correct
- Calibration test: compare the sensor or timing against a known reference or repeated trial
- Limitation test: deliberately create an awkward or noisy condition and note how the prototype behaves
Deployment and Limitations
- This prototype is suitable for local pilots where sensor data must be logged or transmitted over short periods
- Before deployment, network reliability, power backup, and endpoint security need attention
- The system should keep useful local behavior even when communication fails
Troubleshooting
| Problem | Possible Cause | Solution |
|---|---|---|
| The heartbeat LED blinks but no server data appears | UPLOAD_ENABLED is false or the endpoint is wrong | Check the upload flag, credentials, and server path |
| sensor_ok is always false | The BME280 I2C wiring is unstable | Test the BME280 separately and shorten the I2C wires |
| The local record file never grows | The Pico file write failed | Test a simple file write and confirm the storage path is working |
| Gas values drift for a long time | The MQ-5 is still warming up | Allow more warm-up time before comparing records |






