26
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ESP32をMQTTでPublishする

Last updated at Posted at 2018-06-21

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());
    }
}

26
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?