ESP32F030 FLASH 模拟eeprom代码
时间: 2023-10-01 20:04:48 浏览: 154
对于ESP32F030,可以使用内部闪存来实现类似EEPROM的功能。以下是使用ESP-IDF的示例代码:
```c
#include "esp_system.h"
#include "nvs_flash.h"
#include "nvs.h"
#define EEPROM_NAMESPACE "eeprom"
void eeprom_init()
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
}
void eeprom_write(uint16_t address, uint8_t data)
{
nvs_handle_t handle;
ESP_ERROR_CHECK(nvs_open(EEPROM_NAMESPACE, NVS_READWRITE, &handle));
ESP_ERROR_CHECK(nvs_set_u8(handle, address, data));
ESP_ERROR_CHECK(nvs_commit(handle));
nvs_close(handle);
}
uint8_t eeprom_read(uint16_t address)
{
uint8_t data;
nvs_handle_t handle;
ESP_ERROR_CHECK(nvs_open(EEPROM_NAMESPACE, NVS_READONLY, &handle));
ESP_ERROR_CHECK(nvs_get_u8(handle, address, &data));
nvs_close(handle);
return data;
}
void eeprom_erase_all()
{
nvs_flash_erase();
}
void eeprom_erase(uint16_t address)
{
nvs_handle_t handle;
ESP_ERROR_CHECK(nvs_open(EEPROM_NAMESPACE, NVS_READWRITE, &handle));
ESP_ERROR_CHECK(nvs_erase_key(handle, address));
ESP_ERROR_CHECK(nvs_commit(handle));
nvs_close(handle);
}
```
在初始化时,需要调用eeprom_init()函数。写入和读取数据的函数分别是eeprom_write()和eeprom_read()。擦除单个地址的函数是eeprom_erase(),擦除所有数据的函数是eeprom_erase_all()。
使用示例:
```c
#include "eeprom.h"
void app_main()
{
eeprom_init();
//写入数据
eeprom_write(0, 0x11);
eeprom_write(1, 0x22);
eeprom_write(2, 0x33);
//读取数据
uint8_t data = eeprom_read(1);
//擦除单个地址
eeprom_erase(1);
//擦除所有数据
eeprom_erase_all();
}
```
阅读全文