[英]VSCode ESP32 type error in Serial.println
我決定為我的 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
除了BLECharacteristic
的getValue
返回std::__cxx11::string
。
我也嘗試過#define _GLIBCXX_USE_CXX11_ABI 0
根據: Converting std::__cxx11::string to std::string但我得到了同樣的錯誤,只是用std::string
代替。
如果getValue
返回正確的類型,為什么我無法將值打印到串行?
您看到的錯誤是抱怨編譯器無法找到以std::__cxx11::string
作為參數的HardwareSerial
的println
方法版本。 問題不在於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
的文檔來找到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.