如何将 std::string 写入 ESP32 NVS
另请参阅:如何将 ESP32 NVS 值读入 std::string
将 std::string 写入 NVS 相当容易。你可以使用 .c_str() 获取 const char* 指针,然后按照如何将 string (const char*) 写入 ESP32 NVS中所示进行操作
你可以使用此实用函数将 string (const char*) 写入 NVS:
nvs_write_string.cpp
bool NVSWriteString(nvs_handle_t nvs, const std::string& key, const std::string& value) {
esp_err_t err;
if((err = nvs_set_blob(nvs, key.c_str(), value.data(), value.size())) != ESP_OK) {
Serial.printf("Failed to write NVS key %s: %srn", key, esp_err_to_name(err));
return false;
}
return true;
}使用示例
此示例基于如何在 ESP32 上初始化 NVS。最重要的是,它假设你已经初始化了 NVS 并且 myNVS 存在且有效。
nvs_write_usage_example.cpp
char mySerialNo[128] = {0};
_NVS_WriteString(myNVS, "SerialNo", "0000001");这会将值 0000001 写入 NVS,键为 SerialNo
注意 NVS 字符串是长度限定的(即:长度存储在 NVS 中)且不一定是 NUL 终止的。此代码不在 NVS 中存储 NUL 终止符。
Check out similar posts by category:
ESP8266/ESP32
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow