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
    评论
好的,我可以为您介绍如何使用 Arduino 和 ESP32 来控制 LED 并通过 MQTT 协议实现远程控制。 在开始之前,您需要准备以下材料: - Arduino UNO 板子 - ESP32 板子 - LED - 杜邦线若干 - 电阻 接下来,我们将分以下几个步骤进行操作: 1. 硬件连接 将 ESP32 和 Arduino UNO 连接起来,可以通过以下方式实现: - 将 ESP32 的 GND 引脚接到 Arduino UNO 的 GND 引脚上。 - 将 ESP32 的 3.3V 引脚接到 Arduino UNO 的 3.3V 引脚上。 - 将 ESP32 的 RX 引脚接到 Arduino UNO 的 TX 引脚上。 - 将 ESP32 的 TX 引脚接到 Arduino UNO 的 RX 引脚上。 在连接完成后,将电阻与 LED 并联连接,将电阻的一端连接到 ESP32 的引脚上,将 LED 的正极连接到电阻的另一端,将 LED 的负极连接到 ESP32 的 GND 引脚上。 2. MQTT 库的安装 在 Arduino IDE 中,点击“工具”栏,选择“管理库”,搜索 MQTT 库并安装。 3. 编写代码 接下来,我们要编写代码,将其上传到 ESP32 板子中。以下是代码实现的具体步骤: - 在代码开头引入所需的库,包括 WiFiClient、PubSubClient 和 WiFi。 - 设置 WiFi 的 SSID 和密码。 - 设置 MQTT 服务器的地址,端口和主题。 - 在 setup() 函数中,连接 WiFi 和 MQTT 服务器。 - 在 loop() 函数中,通过 MQTT 接收控制信息并控制 LED 。 以下是完整的代码: ``` #include <WiFi.h> #include <PubSubClient.h> // Replace with your network credentials const char* ssid = "your_SSID"; const char* password = "your_PASSWORD"; // Replace with your MQTT Broker IP address const char* mqtt_server = "your_MQTT_BROKER_IP"; const int mqtt_port = 1883; const char* topic = "led_control"; WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin(115200); delay(100); // Connect to Wi-Fi network with SSID and password Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); client.setServer(mqtt_server, mqtt_port); } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived in topic: "); Serial.println(topic); String message = ""; for (int i = 0; i < length; i++) { message += (char)payload[i]; } Serial.println("Message received: " + message); if (message == "on") { digitalWrite(LED_BUILTIN, HIGH); } else if (message == "off") { digitalWrite(LED_BUILTIN, LOW); } } void reconnect() { while (!client.connected()) { Serial.print("Connecting to MQTT..."); if (client.connect("ESP32Client")) { Serial.println("connected"); client.subscribe(topic); } else { Serial.print("failed with state "); Serial.print(client.state()); delay(2000); } } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); } ``` 4. 测试 将 ESP32 板子连接到电脑并上传代码后,打开串口监视器。如果一切正常,您应该能够看到 ESP32 成功连接到 WiFi 和 MQTT 服务器,并等待接收 LED 控制信息。 接下来,可以使用任何 MQTT 客户端向主题“led_control”发送“on”或“off”消息来控制 LED 的开关状态。 以上就是使用 Arduino 和 ESP32 来控制 LED 并通过 MQTT 协议实现远程控制的实验步骤,希望对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

雨轩智能

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

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

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

打赏作者

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

抵扣说明:

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

余额充值