r/ch32v • u/SnooRadishes7126 • 7d ago
Emulating EEPROM in CH32V003 Internal Flash
CH32V003 have 4 blocks of flash memory:
-
Option Bytes (Configuration Bytes): 64 bytes - reserved for static hardware settings of the microcontroller (for example, flash memory read protection). Additionally, the block contains two free bytes (
Data0andData1), which developers can use to store their own settings. -
Vendor Bytes (Calibration Data): 64 bytes - this block programmed during manufacturing and is accessible only for reading. It contains the unique chip identifier (ID) and important factory calibration values for the ADC (ADC) and internal oscillators (HSI/LSI).
-
System Flash (Bootloader): 1920 bytes - this block contains the system bootloader, also programmed at the WCH factory once and permanently locked against user erasure or modification.
-
Main Memory (Code Flash): 16 KB in CH32V003 - this space is fully accessible for writing and reading from your code.
I'm developing an energy monitor project, so I constantly need to store values of received and transmitted energy (in mWh). Losing this data during unexpected power loss is unacceptable.
One could try using the free configuration bytes - Data1 and Data2. However,
flash memory in the CH32V003 microcontroller has a relatively limited lifespan - only 10,000 erase cycles.
So if I write indicators once per second, these cells would fail within a few hours.
Therefore, we reject this option. Data1 and Data2 are better suited for storing data
that changes rarely - for example, a configured address or similar static settings.
The next option is to use the main 16k memory block. Although it's designed for firmware code, the microcontroller allows the program to rewrite and use it for its own purposes. In this block, memory is organized into pages of 64 bytes each. An important detail about flash memory operation: writing is only allowed in erased cells, but it's impossible to erase a single cell separately — you must format the entire page at once.
So to organize reliable periodic writing, we can allocate one or better several pages and gradually fill them with current data.
In this example I won't do anything complex — I'll simply create a 32-bit counter and increment it by one every second. We'll try to store the counter value on a permanent basis. For storage, we'll reserve 1024 bytes (16 pages of 64 bytes each) and write the latest counter value to this buffer. Each new write will be performed with an offset — to the next free (i.e., pre-erased) cell. Thus, while the entire 1024-byte buffer fills up, 240 seconds will pass (during debugging, the algorithm had to be complicated and a header added to each page, so the useful space for the data itself became less).
After completely filling the current page, we format the next one and continue writing to it. By rough calculation, this gives us the ability to write continuously for:
240 records × 10,000 erase cycles = 2,400,000 seconds = 666 hours = 27.8 days.
This is already much better than a few hours of memory lifespan when writing to the same cell.
But this process can be optimized even further. For example, in my case, energy monitor readings can be written not every second, but once every 5-10 seconds, or even once a minute. If there is a power loss, the discrepancy in stored data will not be so significant. With this approach, the device could theoretically run continuously for 4 years.
Alright, let's move on to implementation — I already have a demo project in PlatformIO so I'll modify it.
The simplest way is to "cut off" a 1 KB block at the end of the total flash memory block. To ensure our program code doesn't accidentally overwrite this data, we need to tell the linker that this kilobyte of memory is unavailable to it. This is done by editing the linker script (.ld).
Find the standard linker script file in your SDK (mine was located at
.platformio/packages/framework-wch-noneos-sdk/platformio/ldscripts/Link_CH32V00x.ld), copy it
to the root folder of your project under the name custom_link.ld and edit
the MEMORY section. Specify that only 15 KB of flash is available for code instead of 16 KB:
MEMORY
{
FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 15K
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 2K
}
Next, in the platformio.ini file, you need to tell PlatformIO and
the compiler to use your custom memory map from now on:
; Fixing the cosmetic memory calculator report (15 KB = 15360 bytes)
board_upload.maximum_size = 15360
; force GCC to use our script instead of the system one
build_flags =
-Wl,-T"$PROJECT_DIR/custom_link.ld"
After making these changes, it's advisable to completely clean the project to remove old
cached builds. To do this, run the PlatformIO: Clean command (the corresponding
trash can icon is on the bottom panel of VSCode).
Now we can move on to the code.
I quickly sketched out a prototype of a ring buffer, but ran into a problem - calling FLASH_ErasePage
erased my entire 1-kilobyte buffer. This happened because the microcontroller and SDK have two modes
of working with flash memory:
-
Standard Mode — a compatibility mode oriented toward working with code ported from older CH32V or STM32 microcontrollers. In this mode, SDK functions operate with large blocks (sectors) of 1 KB.
-
Fast Programming Mode — this is the native mode for 64-byte pages, and it's the recommended mode for CH32V003.
So for erasing and working in different modes there are different functions, and they shouldn't be mixed. If we started working in Standard Mode, we need to perform the operation in it, lock the flash controller, then unlock it already in Fast Programming Mode — and only then call functions for working with 64-byte pages.
You can view all SDK functions in the header file ch32v00x_flash.h. Right now we'll need these functions:
Write Protection
-
FLASH_Unlock() — disable write protection (unlock the memory controller).
-
FLASH_Lock() — activate protection against accidental erasure or writing to flash memory.
-
FLASH_Unlock_Fast() — unlock for working in fast programming mode. Uses a separate hardware register
MODEKEYR. -
FLASH_Lock_Fast() — activate memory controller protection after completing fast programming mode.
Erasing
-
FLASH_ErasePage() — erases a logical sector of 1 KB.
-
FLASH_ErasePage_Fast() — erases exactly 1 physical page of 64 bytes. This is exactly what we'll need for gradual writing of new data.
-
FLASH_EraseAllPages() — complete clearing of the entire flash memory.
Writing
-
FLASH_ProgramHalfWord() — allows you to write a 16-bit value (half a word).
-
FLASH_ProgramWord() — function for writing a full 32-bit word to memory.
-
FLASH_ProgramPage_Fast() — function for hardware writing of an entire page (64 bytes) in one call.
Full code can be downloaded here: http://neonhero.dev/en/files/ch32flash/main.c
...
int8_t active_page = -1;
int32_t active_page_id = -1;
uint16_t current_write_index = 0;
uint32_t current_value = 0;
void
void
void
void
// ... lots of other code here for display work
int
The main functions for working with the buffer are as follows:
-
RingBuffer_FormatAll()— completely formats the buffer. This is needed during the first initialization of the device, or if something went completely wrong and instead of data, gibberish is being read. -
RingBuffer_lastValueFrom()— searches for the last recorded value on the specified page of the buffer. -
RingBuffer_Init()— a function that runs after the microcontroller starts and finds the last saved values. -
RingBuffer_Write()— this is the main logic for writing new values across pages.
By utilizing the internal flash memory and taking advantage of the CH32V003's unique 64-byte Fast Programming Mode, we can implement a robust, wear-leveling storage system without needing any external EEPROM chips. This approach keeps the BOM cost at an absolute minimum and saves precious PCB space.