0
0
Drone-programmingHow-ToBeginner · 4 min read

IoT Project for Weather Monitoring Station: Setup and Code Example

An IoT weather monitoring station collects data from sensors like temperature and humidity, then sends it using MQTT protocol to a server or cloud. You can use devices like ESP32 or Raspberry Pi with sensors and write code to publish sensor data to an MQTT broker for real-time monitoring.
📐

Syntax

The basic syntax for an IoT weather monitoring station involves initializing sensors, reading sensor data, connecting to Wi-Fi, and publishing data to an MQTT broker.

Key parts:

  • Sensor Initialization: Setup sensor pins and communication.
  • Wi-Fi Connection: Connect the device to the internet.
  • MQTT Client Setup: Define broker address and topic.
  • Data Publishing: Send sensor readings as messages.
cpp
void setup() {
  // Initialize sensor
  sensor.begin();
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  // Setup MQTT client
  mqttClient.setServer(broker, port);
  mqttClient.connect(clientId);
}

void loop() {
  // Read sensor data
  float temperature = sensor.readTemperature();
  float humidity = sensor.readHumidity();
  // Create message
  String payload = "{\"temp\": " + String(temperature) + ", \"hum\": " + String(humidity) + "}";
  // Publish to MQTT topic
  mqttClient.publish(topic, payload.c_str());
  delay(60000); // Wait 1 minute
}
💻

Example

This example uses an ESP32 microcontroller with a DHT11 sensor to read temperature and humidity, then publishes the data to an MQTT broker every minute.

cpp
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

#define DHTPIN 4
#define DHTTYPE DHT11

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";
const char* mqtt_server = "broker.hivemq.com";
const char* mqtt_topic = "weather/station1";

WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  dht.begin();
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");
  client.setServer(mqtt_server, 1883);
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("ESP32Client")) {
      Serial.println("MQTT connected");
    } else {
      delay(5000);
    }
  }
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  char payload[50];
  snprintf(payload, sizeof(payload), "{\"temp\": %.1f, \"hum\": %.1f}", temperature, humidity);
  client.publish(mqtt_topic, payload);
  Serial.print("Published: ");
  Serial.println(payload);

  delay(60000); // Wait 1 minute
}
Output
WiFi connected MQTT connected Published: {"temp": 23.4, "hum": 56.7} Published: {"temp": 23.5, "hum": 56.5} ...
⚠️

Common Pitfalls

  • Wi-Fi connection failure: Not handling reconnection can stop data flow.
  • MQTT broker unreachable: Ensure broker address and port are correct.
  • Sensor read errors: Check for NaN values before publishing.
  • Incorrect topic format: Use consistent topic names for subscribers.
cpp
// Wrong: No check for sensor data validity
float temp = dht.readTemperature();
client.publish(topic, String(temp).c_str());

// Right: Check sensor data before publishing
float temp = dht.readTemperature();
if (!isnan(temp)) {
  client.publish(topic, String(temp).c_str());
} else {
  Serial.println("Sensor read error");
}
📊

Quick Reference

Remember these tips for your IoT weather station:

  • Use reliable Wi-Fi and handle reconnections.
  • Validate sensor data before sending.
  • Use MQTT for lightweight, real-time data transfer.
  • Secure your MQTT broker with authentication if possible.

Key Takeaways

Use MQTT protocol to send sensor data efficiently from IoT devices.
Always check sensor readings for errors before publishing.
Handle Wi-Fi and MQTT reconnections to maintain continuous data flow.
Choose simple sensors like DHT11 for temperature and humidity monitoring.
Secure your IoT communication channels to protect data integrity.