如何 Serial.println() std::string

在 Arduino 中,如果你有一个 std::string

how-to-serial-println-a-stdstring.cpp
std::string str = "test";

你不能直接打印它 - 尝试这样做会导致以下错误消息:

serial_compile_error.txt
src/main.cpp: In function 'void setup()':
src/main.cpp:122:22: error: no matching function for call to 'HardwareSerial::println(std::__cxx11::string&)'
   Serial.println(cert);
                      ^
In file included from /home/uli/.platformio/packages/framework-arduinoespressif32@src-76bf6cf11a70195daa934985b7bd68e2/cores/esp32/Stream.h:26,
                 from /home/uli/.platformio/packages/framework-arduinoespressif32@src-76bf6cf11a70195daa934985b7bd68e2/cores/esp32/Arduino.h:166,
                 from src/main.cpp:1:
/home/uli/.platformio/packages/framework-arduinoespressif32@src-76bf6cf11a70195daa934985b7bd68e2/cores/esp32/Print.h:96:12: note: candidate: 'size_t Print::println(const __FlashStringHelper*)'
     size_t println(const __FlashStringHelper *);
            ^~~~~~~
/home/uli/.platformio/packages/framework-arduinoespressif32@src-76bf6cf11a70195daa934985b7bd68e2/cores/esp32/Print.h:96:12: note:   no known conversion for argument 1 from 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const __FlashStringHelper*'
/home/uli/.platformio/packages/framework-arduinoespressif32@src-76bf6cf11a70195daa934985b7bd68e2/cores/esp32/Print.h:97:12: note: candidate: 'size_t Print::println(const String&)'
     size_t println(const String &s);

解决方案

你可以使用 .c_str() 将其转换为可以直接打印的 NUL 终止 char*

serial_print_solution.cpp
Serial.println(str.c_str());

Check out similar posts by category: Arduino, C/C++, Embedded