Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[arduino code examples for A16v3]-14 post data to mqtt topic
#1
Code:
/*
* MQTT example using W5500 and ESP32-S3
* Adapted from KinCony's W5500 TCP Server example
*/

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

// W5500 pin definitions
#define W5500_CS_PIN   15
#define W5500_RST_PIN  1
#define W5500_INT_PIN  2
#define W5500_CLK_PIN  42
#define W5500_MOSI_PIN 43
#define W5500_MISO_PIN 44

// MAC address (must be unique)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// Static IP settings
IPAddress ip(192, 168, 3, 55);
IPAddress subnet(255, 255, 255, 0);
IPAddress gateway(192, 168, 3, 1);
IPAddress dns(192, 168, 3, 1);

// MQTT broker settings
const char* mqtt_server = "192.168.3.100";  // 可改为你的服务器
const int mqtt_port = 1883;
const char* mqtt_topic = "kincony/test";

// Ethernet and MQTT clients
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

// MQTT callback
void mqttCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("]: ");
  for (unsigned int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void mqttReconnect() {
  while (!mqttClient.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (mqttClient.connect("KinConyClient")) {
      Serial.println("connected");
      mqttClient.subscribe(mqtt_topic);  // 订阅主题
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" trying again in 5 seconds");
      delay(5000);
    }
  }
}

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

  // Reset W5500
  pinMode(W5500_RST_PIN, OUTPUT);
  digitalWrite(W5500_RST_PIN, LOW);
  delay(100);
  digitalWrite(W5500_RST_PIN, HIGH);
  delay(100);

  // Start SPI
  SPI.begin(W5500_CLK_PIN, W5500_MISO_PIN, W5500_MOSI_PIN);
  Ethernet.init(W5500_CS_PIN);
  Ethernet.begin(mac, ip, dns, gateway, subnet);

  Serial.print("IP Address: ");
  Serial.println(Ethernet.localIP());

  mqttClient.setServer(mqtt_server, mqtt_port);
  mqttClient.setCallback(mqttCallback);
}

unsigned long lastMsg = 0;

void loop() {
  if (!mqttClient.connected()) {
    mqttReconnect();
  }

  mqttClient.loop();

  // Publish message every 10 seconds
  unsigned long now = millis();
  if (now - lastMsg > 10000) {
    lastMsg = now;
    const char* msg = "Hello from KinCony ESP32S3 board + W5500";
    mqttClient.publish(mqtt_topic, msg);
    Serial.println("Published message");
  }
}
arduino ino file download:

.zip   14-mqtt.zip (Size: 1.19 KB / Downloads: 299)
   
Reply


Forum Jump:


Users browsing this thread:
1 Guest(s)