[心得] Arduino MQTT 控制、傳輸

#include 
#include 
const int led=2;    //內建LED

 
const char* ssid = "MISR";
const char* password = "WIFI密碼";
const char* mqttServer = "192.168.0.144";
const char* mqtt_server = "192.168.0.144";

const char* mqttUser = "bob01";
const char* mqttPassword = "123456";
const int mqttPort = 1883;


WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

float temperature = 0;
float humidity = 0;

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(led, OUTPUT);
 
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;


  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();


 // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 
  // Changes the output state according to the message
  if (String(topic) == "esp/son") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("開");
      digitalWrite(led, HIGH);
    }
    else if(messageTemp == "soff"){
      Serial.println("關");
      digitalWrite(led, LOW);
    }
  }
}



void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP32Client", mqttUser, mqttPassword)) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp/son");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}



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

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;

  client.publish("esp/test", "yes");
  delay(2000);
    
  }
}

參考:
Https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/

留言

這個網誌中的熱門文章

[心得] Raspberry Pi 4 部屬系統以及解決Xrdp藍(青)色畫面問題