Pico W: climate sensor over MQTT
DHT22 values over MQTT, LED by message.
- RP2040 (Pico W)
- Wi-Fi router
- DHT22
Open in the simulatorNo account needed: press Simulate and it runs.
How it works
The Pico W reads a DHT22 on GP15 and sends temperature and humidity to the virtual network's MQTT broker every 2 s (PubSubClient). The messages appear in the "Network" panel; a message "on" or "off" to the topic pico/led switches the onboard LED. Change the sensor's temperature and humidity in the inspector, even while the simulation runs.
Wiring
Each line is one connection (net) and the pins it joins.
| Net | Pins |
|---|---|
| GND | A1 GNDU2 GND |
| 3V3 | A1 3V3U2 VCC |
| DHT | A1 GP15U2 DATA |
Parts
Firmware
sketch.ino · 50 lines
// Pico W + DHT22 (GP15): sends temperature and humidity to the MQTT broker every 2 s,
// the topic "pico/led" (on/off) switches the onboard LED. Messages are in the "Network" panel.
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
const char* SSID = "CircuitLab";
const char* PASS = "secret123";
WiFiClient net;
PubSubClient mqtt(net);
DHT dht(15, DHT22);
void onMessage(char* topic, byte* payload, unsigned int len) {
String msg; for (unsigned int i = 0; i < len; i++) msg += (char)payload[i];
Serial.print("MQTT "); Serial.print(topic); Serial.print(" = "); Serial.println(msg);
if (String(topic) == "pico/led") digitalWrite(LED_BUILTIN, msg == "on" ? HIGH : LOW);
}
void connectMqtt() {
while (!mqtt.connected()) {
if (mqtt.connect("pico-w-climate")) { mqtt.subscribe("pico/led"); Serial.println("MQTT connected"); }
else delay(500);
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
dht.begin();
WiFi.begin(SSID, PASS);
while (WiFi.status() != WL_CONNECTED) delay(100);
Serial.print("IP: "); Serial.println(WiFi.localIP());
mqtt.setServer("broker.lab", 1883);
mqtt.setCallback(onMessage);
}
uint32_t last = 0;
void loop() {
connectMqtt();
mqtt.loop();
if (millis() - last >= 2000) {
last = millis();
float t = dht.readTemperature(), h = dht.readHumidity();
if (!isnan(t)) {
mqtt.publish("pico/climate/temperature", String(t, 1).c_str());
mqtt.publish("pico/climate/humidity", String(h, 0).c_str());
Serial.print(t, 1); Serial.print(" C "); Serial.print(h, 0); Serial.println(" %");
}
}
}Open in the simulator