使用 ESP8266 并在尝试将字节数组转换为字符串时出现编译错误

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

我对 C++ 非常陌生,尤其是 ESP8266。我有一个简单的回调函数,每次将消息放入 MQTT 队列时都会调用该函数。以下代码应该读取字节,转换为 char* 并将它们传递给 LED 进行显示。

一位朋友建议使用以下两行将字节转换为字符。

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <iostream>
#include <string>

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

// copy the bytes into a string var
std::string byteString(payload, length);

// Then if you need to access it as a char*
char* charString = byteString.c_str()

 lcd.setCursor(0,1);
 lcd.print(charString);
 delay(2000); 
 
} 

但是,这似乎失败了

basic_string.h:147:33: note:   no known conversion for argument 1 from 'byte*' {aka 'unsigned char*'} to 'std::__cxx11::basic_string<char>::__sv_wrapper'

我确实尝试用谷歌搜索该错误,并且确实看到了一些类似的错误,表明我可能使用的是较旧版本的 C++。

这是我第一次涉足 C++ 世界,并超越了 ESP 设备的基本复制和粘贴示例,如果您能提供任何指示或解释我可能在这里缺少的内容,我将非常感激。

非常感谢!

c++ esp8266
1个回答
0
投票

经过一番尝试和错误,我无法将字节数组转换为字符串,但是据我所知,我刚刚创建了一个相同大小的字符串,以 null 终止它并从字节复制了字节数组。

我确信这并不理想,但在我学习更多 C++ 之前,它会将 ascii 字符打印到我的 LCD 显示器上。该设备的全部目的实际上是将温度打印到 LCD 显示屏上。

感谢所有帮助我走上正轨的人。

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

  
 char lcdmsg[sizeof( payload ) + sizeof( ( char )'\0' )] = { '\0' };
 memcpy(lcdmsg, payload, length);

 // Print to the display
 lcd.setCursor(0,1);
 lcd.print(lcdmsg);
 delay(2000); 
 
} 
© www.soinside.com 2019 - 2024. All rights reserved.