Writes data to the flash memory. 向闪存写入数据。
108{
110 {
111 return ErrorCode::ARG_ERR;
112 }
113
114 uint32_t addr = base_address_ + offset;
115 if (!IsInRange(addr, data.
size_))
116 {
117 return ErrorCode::OUT_OF_RANGE;
118 }
119
120#if defined(__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
121 bool i_cache_enabled = ((SCB->CCR & SCB_CCR_IC_Msk) != 0U);
122 if (i_cache_enabled)
123 {
124 SCB_DisableICache();
125 }
126#endif
127
128#if defined(__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
129 bool d_cache_enabled = ((SCB->CCR & SCB_CCR_DC_Msk) != 0U);
130 if (d_cache_enabled)
131 {
132 SCB_DisableDCache();
133 }
134#endif
135
136 HAL_FLASH_Unlock();
137
138 const uint8_t* src =
reinterpret_cast<const uint8_t*
>(data.
addr_);
139 size_t written = 0;
140
141#if defined(STM32H7) || defined(STM32H5)
142 alignas(32) uint32_t flash_word_buffer[8] = {0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu,
143 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu,
144 0xFFFFFFFFu, 0xFFFFFFFFu};
145 while (written < data.
size_)
146 {
148
149 std::memset(flash_word_buffer, 0xFF, sizeof(flash_word_buffer));
150 std::memcpy(flash_word_buffer, src + written, chunk_size);
151
152 if (memcmp(reinterpret_cast<const uint8_t*>(addr + written), src + written,
153 chunk_size) == 0)
154 {
155 written += chunk_size;
156 continue;
157 }
158
159 if (HAL_FLASH_Program(program_type_, addr + written,
160 reinterpret_cast<uint32_t>(flash_word_buffer)) != HAL_OK)
161 {
162 HAL_FLASH_Lock();
163 return ErrorCode::FAILED;
164 }
165
166 written += chunk_size;
167 }
168
169#else
170 while (written < data.
size_)
171 {
173
174 if (memcmp(reinterpret_cast<const uint8_t*>(addr + written), src + written,
175 chunk_size) == 0)
176 {
177 written += chunk_size;
178 continue;
179 }
180
181 uint64_t word = 0xFFFFFFFFFFFFFFFF;
182 std::memcpy(&word, src + written, chunk_size);
183
184 if (HAL_FLASH_Program(program_type_, addr + written, word) != HAL_OK)
185 {
186 HAL_FLASH_Lock();
187 return ErrorCode::FAILED;
188 }
189
190 written += chunk_size;
191 }
192#endif
193
194 HAL_FLASH_Lock();
195
196#if defined(__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
197 if (i_cache_enabled)
198 {
199 SCB_EnableICache();
200 }
201#endif
202
203#if defined(__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
204 if (d_cache_enabled)
205 {
206 SCB_EnableDCache();
207 }
208#endif
209
210 return ErrorCode::OK;
211}
size_t size_
数据大小(字节)。 The size of the data (in bytes).
const void * addr_
数据存储地址(常量)。 The storage address of the data (constant).
size_t MinWriteSize() const
Returns the minimum writable block size in bytes. 获取最小可写块大小(字节)。
constexpr auto min(T1 a, T2 b) -> typename std::common_type< T1, T2 >::type
计算两个数的最小值