如何解决Serial.println 中的 VSCode ESP32 类型错误
我决定为我的 ESP32 从 Arduino IDE 切换到 VSCode 和 PlatformIO。我正在使用带有回调的 BLE 服务器示例作为测试:
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
class MyCallBack: public BLECharacteristicCallbacks {
void onRead(BLECharacteristic *pCharacteristic) {
std::__cxx11::string val = pCharacteristic->getValue();
if ((val.length() > 0)) {
Serial.println(val);
}
}
};
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE work!");
BLEDevice::init("Long name works now");
BLEServer *pServer = BLEDevice::createServer();
BLEService *pService = pServer->createService(SERVICE_UUID);
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,BLECharacteristic::PROPERTY_READ
);
pCharacteristic->setValue("Hello World!");
pCharacteristic->setCallbacks(new MyCallBack());
pService->start();
// BLEAdvertising *pAdvertising = pServer->getAdvertising(); // this still is working for backward compatibility
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
Serial.println("Characteristic defined! Now you can read it in your phone!");
}
void loop() {
// put your main code here,to run repeatedly:
delay(2000);
}
我很确定当我在 Arduino IDE 中使用它时它上传并运行良好但在 VSCode 中我收到一个错误:
no instance of overloaded function "HardwareSerial::println" matches the argument list -- argument types are: (std::__cxx11::string) -- object type is: HardwareSerial
除了 getValue
的 BLECharacteristic
返回 std::__cxx11::string
。
我也尝试过 #define _GLIBCXX_USE_CXX11_ABI 0
根据:Converting std::__cxx11::string to std::string 但我只用 std::string
反而得到同样的错误。
如果 getValue
返回正确的类型,为什么我无法将值打印到串行?
解决方法
您看到的错误是抱怨编译器无法找到以 println
作为参数的 HardwareSerial
的 std::__cxx11::string
方法版本。问题不在于 getValue()
方法返回了错误的东西;问题是 Serial.println()
没有被编写为接受 getValue()
作为参数返回的内容。
您需要将蓝牙函数返回的 std::__cxx11::string
强制转换或以其他方式转换为 String
或 char *
,println()
方法接受这两者。您可以使用 .c_str()
方法来执行此操作。
if ((val.length() > 0)) {
Serial.println(val.c_str());
}
您可以通过阅读有关 Serial.println
和 std::__cxx11::string
的文档找到这一点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。