USB 上的 Arduino Uno MQTT

问题描述 投票:0回答:1

总脚本菜鸟在这里。在 chatgpt 的帮助下,我一直在尝试通过 MQTT 在 Arduino Uno 上发布来自我的 LM35 的数据,以监控我阁楼的温度,但没有任何运气。 目前我的设置包括 Windows 客户端 PC、我的 Arduino Uno R3 和 LM35(没有 esp 或 ethernetshield)。 Arduino 必须通过端口 COM3 上的 USB 将数据从 LM35 发送到 Windows 客户端,这应该充当代理。 我似乎无法让它真正输出任何东西。当我尝试运行草图时,我总是会出现乱七八糟的乱码(见附图) Gibberish output 当我自己通过命令行发布内容时,数据显示在子端

我已经尝试了很多东西,但这是我目前的草图,如果有人能提供帮助那就太棒了!

#include <OneWire.h>
#include <DallasTemperature.h>
#include <PubSubClient.h>

const char* mqtt_server = "10.6.53.4";
const int mqtt_port = 1883;
const char* mqtt_topic = "temp/attic";
const int oneWireBus = A0;

OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);

PubSubClient mqttClient;

void setup() {
  Serial.begin(9600);
  sensors.begin();

  mqttClient.setServer(mqtt_server, mqtt_port);
  while (!mqttClient.connected()) {
    Serial.println("Connecting to MQTT broker...");
    if (mqttClient.connect("arduino_client")) {
      Serial.println("Connected to MQTT broker");
    } else {
      Serial.print("Failed with state ");
      Serial.print(mqttClient.state());
      delay(2000);
    }
  }
}

void loop() {
  sensors.requestTemperatures();
  float temperature = sensors.getTempCByIndex(0);
  
  char payload[6];
  dtostrf(temperature, 5, 2, payload);
  
  String topic = "temp/attic";

  if (!mqttClient.connected()) {
    Serial.print("Connecting to MQTT broker...");
    if (mqttClient.connect("ArduinoUnoClient")) {
      Serial.println("connected");
    } else {
      Serial.print("failed with state ");
      Serial.println(mqttClient.state());
      delay(2000);
      return;
    }
  }

  Serial.println("Connected to MQTT broker");
  Serial.println("Publishing temperature data...");
  Serial.print("Topic: ");
  Serial.println(topic);
  Serial.print("Payload: ");
  Serial.println(payload);

  mqttClient.publish(topic.c_str(), payload);

  delay(5000);
}


mqtt arduino-uno
1个回答
1
投票

除非您的 Arduino 用作 USB 以太网适配器,否则这将NOT 工作。 PubSub 客户端需要一个活跃的 TCP 堆栈才能工作,它不能只通过 USB 发送“MQTT 数据包”。

虽然技术上可以通过几乎任何双向连接在两个设备之间发送 MQTT 数据包,但您必须自己从头开始编写整个客户端和整个代理/usb2broker 桥接端。

这里一个更好的选择是从 Arduino 代码中删除所有 MQTT 代码并将传感器读数写入串行输出并编写一个简短的 Python 脚本来读取这些代码,然后将它们发布到 MQTT 代理。

© www.soinside.com 2019 - 2024. All rights reserved.