ESP8266 + MQTT实现远程控制LED灯

之前有简单介绍阿里云上安装Mosquitto,如果没有服务器也可以在本地机器进行安装。

// mqtt + esp8266
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>

const char* ssid = "your_wifi_name";  // wifi名称
const char* password = "your_wifi_password"; // wifi密码
const char* mqtt_server = "your_mqtt_server";  // mqtt服务器地址,如本地ip192.168.31.22
 
WiFiClient espClient;
PubSubClient client(espClient);
 
const byte ledPin = D4; // 需要控制的led灯
 
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++) {
  char receivedChar = (char)payload[i];
  Serial.print(receivedChar); // 打印mqtt接收到消息

  if (receivedChar == '1') {  // 收到消息是 '1' 点亮LED灯
    digitalWrite(ledPin, HIGH);
  }
  if (receivedChar == '0')    // 收到消息是 '0' 关闭LED灯
   digitalWrite(ledPin, LOW);
  }
  Serial.println();
}
 
 
void reconnect() {
 while (!client.connected()) {
   Serial.print("Attempting MQTT connection...");
   if (client.connect("ESP8266 Client")) {
    Serial.println("connected");
    client.subscribe("ledStatus");  // 订阅 'ledStatus' 这个topic
   } else {
     Serial.print("failed, rc=");
     Serial.print(client.state());
     Serial.println(" try again in 5 seconds");
     delay(5000);
   }
 }
}
 
void setup()
{
 Serial.begin(9600);
 
 client.setServer(mqtt_server, 1883); // 连接mqtt
 client.setCallback(callback);        // 设置回调,控制led灯
 
 pinMode(ledPin, OUTPUT);
}
 
void loop()
{
 if (!client.connected()) {
  reconnect();
 }
 client.loop();
}

python发布订阅代码

# python 3.6

import random
import time
import random
from paho.mqtt import client as mqtt_client


broker = '127.0.0.1'
port = 1883
#消息主题
topic = "ledStatus"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'


def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def publish(client):
    while True:
        time.sleep(3)
#         msg = {"ledStatus":random.randint(0,1)}
        msg=random.randint(0,1)
        print("msg="+str(msg))
        result = client.publish(topic, str(msg))
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")


def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)


if __name__ == '__main__':
    run()

esp8266 上传采集数据代码

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>
#include <ArduinoJson.h> //JSON数据解析

const char* ssid = "yuxuan";  // wifi名称
const char* password = "yuxuan@+"; // wifi密码

const char* mqtt_server = "192.168.0.195";  // mqtt服务器地址,如本地ip192.168.31.22

const char* updata_topic = "updata_test";

StaticJsonDocument<200> json;
String JSONmessageBuffer = "";

WiFiClient espClient;
PubSubClient client(espClient);
 
const byte ledPin = 2; // 需要控制的led灯
 
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++) {
  char receivedChar = (char)payload[i];
  Serial.print(receivedChar); // 打印mqtt接收到消息

  if (receivedChar == '1') {  // 收到消息是 '1' 点亮LED灯
    digitalWrite(ledPin, HIGH);
  }
  if (receivedChar == '0')    // 收到消息是 '0' 关闭LED灯
   digitalWrite(ledPin, LOW);
  }
  Serial.println();
}
 
 
void reconnect() {
 while (!client.connected()) {
   Serial.print("Attempting MQTT connection...");
   if (client.connect("ESP8266 Client")) {
    Serial.println("connected");
    client.subscribe("ledStatus");  // 订阅 'ledStatus' 这个topic
   } else {
     Serial.print("failed, rc=");
     Serial.print(client.state());
     Serial.println(" try again in 5 seconds");
     delay(5000);
   }
 }
}
 
void setup()
{
 Serial.begin(9600);
 
 client.setServer(mqtt_server, 1883); // 连接mqtt
 client.setCallback(callback);        // 设置回调,控制led灯
 
 pinMode(ledPin, OUTPUT);
}
 
void loop()
{
 if (!client.connected()) {
  reconnect();
 }
 client.loop();
 //上传设备采集数据
 JsonObject json_root = json.to<JsonObject>();
 json_root["roomLocation123"] = "LivingRoom123";
 JsonObject device_name = json_root.createNestedObject("DeviceName");  //创建Obj
 JsonObject DHT11_01_values = device_name.createNestedObject("DHT11_01");
 DHT11_01_values["Temperature:"] = random(1,5);;
 DHT11_01_values["Humidity:"] = random(11,15);;

 JsonObject Relay_01_state = device_name.createNestedObject("Relay_01");
 Relay_01_state["State"] = "OFF";

 serializeJson(json, JSONmessageBuffer);
 Serial.println(JSONmessageBuffer);
 client.publish(updata_topic, JSONmessageBuffer.c_str());  // String.c_str() String转化为char[]
 JSONmessageBuffer = "";

 delay(500);
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨轩智能

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值