18
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

ESP32をMQTTでPublishする

ESP32をWIfiに繋いで、ネットワーク内に用意しているRaspberryPiのMosquittoにMQTTでPublishする

ESP32-DevKitC 及び HiLetgo ESP-32s NodeMCU
ArduinoIDE 1.8.5
Mosquitto 1.4.10 on RaspberryPi

PubSubClient.hは
knolleary/pubsubclientを使用する
https://github.com/knolleary/pubsubclient

MQTT.ino

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

    // WiFi
    const char ssid[] = "######";
    const char passwd[] = "######";

    // Pub/Sub
    const char* mqttHost = "######"; // MQTTのIPかホスト名
    const int mqttPort = 1883;       // MQTTのポート
    WiFiClient wifiClient;
    PubSubClient mqttClient(wifiClient);

    const char* topic = "topic";     // 送信先のトピック名
    char* payload;                   // 送信するデータ

    void setup() {
        Serial.begin(115200);

        // Connect WiFi
        connectWiFi();

        // Connect MQTT
        connectMqtt();
    }

    void loop() {

        // 送信処理 topic, payloadは適宜
        payload = "payload";
        mqttClient.publish(topic, payload);
        delay(1000);

        // WiFi
        if ( WiFi.status() == WL_DISCONNECTED ) {
            connectWiFi(); 
        }
        // MQTT
        if ( ! mqttClient.connected() ) {
            connectMqtt();
        }
        mqttClient.loop();  

    }

    /**
     * Connect WiFi
     */
    void connectWiFi()
    {
        WiFi.begin(ssid, passwd);
        Serial.print("WiFi connecting...");
        while(WiFi.status() != WL_CONNECTED) {
            Serial.print(".");
            delay(100);
        }
        Serial.print(" connected. ");
        Serial.println(WiFi.localIP());
    }
    /**
     * Connect MQTT
     */
    void connectMqtt()
    {
        mqttClient.setServer(mqttHost, mqttPort);
        while( ! mqttClient.connected() ) {
            Serial.println("Connecting to MQTT...");
            String clientId = "ESP32-" + String(random(0xffff), HEX);
            if ( mqttClient.connect(clientId.c_str()) ) {
                Serial.println("connected"); 
            }
            delay(1000);
            randomSeed(micros());
    }
}

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
18
Help us understand the problem. What are the problem?