mqtt 예제
페이지 정보

본문
#include <ESP8266WiFi.h>
#include <MQTTPubSubClient.h>
WiFiClient client;
MQTTPubSubClient mqtt;
char* ssid = "무선 SSID";
char* password = "비밀번호";
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("WIFI connect OK");
Serial.println("mqtt connecting ");
while (!client.connect("mqtt 서버주소", 1883)) {
Serial.print(".");
delay(500);
}
Serial.println("mqtt connect OK");
mqtt.begin(client);
Serial.println("mqtt broker connecting");
//while (!mqtt.connect()) {
while (!mqtt.connect("클라이언트 이름", "mqtt ID", "mqtt PW")) {
Serial.print(".");
delay(500);
}
Serial.println("mqtt broker connect OK");
// 모든 패킷이 올 때 호출되는 subscribe 콜백
mqtt.subscribe([](const String& topic, const String& payload, const size_t size) {
Serial.println("mqtt received: " + topic + " - " + payload);
});
// /hello가 왔을 때 호출되는 주제 및 콜백 구독
mqtt.subscribe("/hello", [](const String& payload, const size_t size) {
Serial.print("/hello ");
Serial.println(payload);
});
}
void loop() {
mqtt.update(); // should be called
// publish message
static uint32_t prev_ms = millis();
if (millis() > prev_ms + 1000) {
prev_ms = millis();
String msg = "arduino - " + String(prev_ms);
Serial.println(msg);
mqtt.publish("/intertech/arduino", msg);
}
}
- 이전글node-red 설치 22.09.27
- 다음글넥션 HMI 라이브러리 설치 22.06.21
댓글목록
등록된 댓글이 없습니다.