c - MQTT 回调处理

标签 c arduino mqtt iot

我正在尝试将传递给 mqtt 回调函数的 byte* 参数转换为 int 以进行比较,但我似乎无法让它工作。欢迎任何帮助。

int fsrReading;
void callback(char* topic, byte* payload, unsigned int length) {

  for (int i=0;i<length;i++) {

    Serial.print((char)payload[i]); // This works well

    fsrReading = int((char)payload[i]); 

    if (fsrReading < 0){
       ...

最佳答案

执行此操作的正确方法取决于所使用的数字的确切表示形式。

我怀疑该消息是数字的字符串表示形式:“1234”,它是作为 ascii 字节值数组接收的。

如果是这种情况,您可以重建一个 String 对象并将其转换为 int:

int fsrReading;
void callback(char* topic, byte* payload, unsigned int length) {
  String value = "";
  for (int i=0;i<length;i++) {
      value += (char)payload[i];
  }
  fsrReading = value.toInt();
  ...

这里的 arduino 教程中有一个将 String 转换为 Int 的示例:https://www.arduino.cc/en/Tutorial/StringToIntExample

关于c - MQTT 回调处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33077354/

相关文章:

c++ - Arduino 上的 typedef 结构 : variable does not name a type

http - Arduino 模块 esp8266 返回错误请求

python - 在 spark 版本 2.2.0 中使用 python(pyspark) 从 mqtt 获取数据流

webpack - Angular CLI 代理 : Redirect unsecured local websocket to secured remote websocket

json - 如何使用 paho C 客户端将数据作为 JSON 对象发送到 MQTT 代理

python - 定义 c_char Python 的数组长度

java - main 函数不返回任何内容。为什么?

arduino - ESP32 WPS上电重新连接

c++ - 如何在 C/C++ 中做 TCP 连接池

c - 将 float (弧度角)写入文件时节省空间