Skip to content

Instantly share code, notes, and snippets.

@hocarm
Last active April 6, 2017 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hocarm/3ac1c4240a26524ac2c2b68163965e96 to your computer and use it in GitHub Desktop.
Save hocarm/3ac1c4240a26524ac2c2b68163965e96 to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// bạn thay đổi thông tin bên dưới cho phù hợp
const char* ssid = "ten_wifi";
const char* password = "mat_khau";
const char* mqtt_server = "ip_may_cai_node_red"; /// lấy ip bằng lệnh ifconfig, ví dụ 192.168.1.105
const uint16_t mqtt_port = 1883;
const byte ledPin = D0;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
pinMode(ledPin, OUTPUT); // Khởi tạo LED
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
// Kết nối wifi
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* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Bật LED nếu nhận được lệnh là 1
if ((char)payload[0] == '1') {
Serial.println("ON");
digitalWrite(ledPin, LOW); // LED có sẵn trên NodeMCU bật ở mức 0(LOW)
}
// Tắt LED nếu nhận được lệnh là 0
if ((char)payload[0] == '0') {
Serial.println("OFF");
digitalWrite(ledPin, HIGH); // LED tắt ở mức 1(HIGH)
}
}
void reconnect() {
// Đợi tới khi kết nối
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Khi kết nối thành công sẽ gửi chuỗi helloworld lên topic event
client.publish("event", "hello world");
// ... sau đó sub lại thông tin
client.subscribe("event");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Thực hiện 2s gửi dữ liệu helloworld lên broker 1 lần
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("event", msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment