Pico W: Klimasensor per MQTT
DHT22-Werte per MQTT, LED per Nachricht.
- RP2040 (Pico W)
- Wi-Fi router
- DHT22
Im Simulator öffnenOhne Konto: Simulieren drücken, und es läuft.
So funktioniert es
Pico W liest einen DHT22 an GP15 und sendet Temperatur und Feuchte alle 2 s an den MQTT-Broker des virtuellen Netzes (PubSubClient). Im Panel „Netzwerk“ erscheinen die Nachrichten; eine Nachricht „on“ oder „off“ an das Topic pico/led schaltet die Onboard-LED. Temperatur und Feuchte des Sensors im Inspektor ändern, auch während die Simulation läuft.
Verdrahtung
Jede Zeile ist eine Verbindung (Netz) mit den Pins, die sie verbindet.
| Netz | Pins |
|---|---|
| GND | A1 GNDU2 GND |
| 3V3 | A1 3V3U2 VCC |
| DHT | A1 GP15U2 DATA |
Bauteile
Firmware
sketch.ino · 50 Zeilen
// 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(" %");
}
}
}Im Simulator öffnen