MQTT

1、首先安装ESP8266库
以下是windows安装方法,mac os见:https://www.arduino.cn/thread-76222-1-1.html
或腾讯微云 packages/
在这里插入图片描述

2、安装PubSubClient.h
PubSubClient可以在Arduino IDE的库管理器中找到:

在这里插入图片描述

3、程序
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid=“WiFi账号”;
const char* password=“WiFi密码”;
const char* mqtt_server=“broker.mqtt-dashborder.com”;
const char* TOPIC=“home/devices/onoff/”;
const char* client_id=“clientId-ApjJZcy9Dh”;
WiFiClient espclient;
PubSubClient client(espclient);
long lastMsg = 0;

void setup_wifi()
{
delay(10);
Serial.println();
Serial.println(“connecting to”);
Serial.println(ssid);
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED)
{
delay(500);
Serial.print(".");
}

Serial.println();
Serial.println(“connected”);
Serial.println(“IP Address”);
Serial.println(WiFi.localIP());
}
void setup() {
// put your setup code here, to run once:
pinMode(11,OUTPUT);
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server,1883);
client.setCallback(callback);
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()){
reconnect();
}
client.loop();
long now=millis();
if(now-lastMsg>2000){
//可以换成每2s发送一次温度
lastMsg=now;
client.publish(“home/status/”,"{device:client_id,‘status’:‘on’}");
}
}
void callback(char* topic,byte* payload,unsigned int length)
{
Serial.print(“Message arrived topic is”);
Serial.println(topic);
Serial.println(“Content is”);
Serial.println();
for(int i=0;i<length;i++)
{
Serial.print((char)payload[i]);

}
Serial.println();
if((char)payload[0]==‘1’){
digitalWrite(11,HIGH);
}else
{
digitalWrite(11,LOW);
}
}
void reconnect(){
while(!client.connected()){
Serial.print(“Attempting MQTT connecting…”);
if(client.connect(client_id)){
client.subscribe(TOPIC);

}else{
  Serial.print("failed,rc=");
  Serial.print(client.state());
  Serial.println("try again in 5 seconds");
  delay(5000);
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值