Writes data to the flash memory. 向闪存写入数据。
152{
153 ASSERT(SystemCoreClock <= 120000000);
154
155
156 Flash_ExitEnhancedReadIfEnabled();
157
158
159 Flash_SetAccessClock_HalfSysclk();
160
162 {
163 Flash_SetAccessClock_Sysclk();
164 ASSERT(false);
165 return ErrorCode::ARG_ERR;
166 }
167
168 const uint32_t start_addr = base_address_ + static_cast<uint32_t>(offset);
169 if (!IsInRange(start_addr, data.
size_))
170 {
171 Flash_SetAccessClock_Sysclk();
172 ASSERT(false);
173 return ErrorCode::OUT_OF_RANGE;
174 }
175
176 const uint8_t* src =
reinterpret_cast<const uint8_t*
>(data.
addr_);
177 const uint32_t end_addr = start_addr +
static_cast<uint32_t
>(data.
size_);
178
179 FLASH_Unlock();
180 ClearFlashFlagsOnce();
181
182 const uint32_t hw_begin = start_addr & ~1u;
183 const uint32_t hw_end = (end_addr + 1u) & ~1u;
184
185 for (uint32_t hw = hw_begin; hw < hw_end; hw += 2u)
186 {
187 volatile uint16_t* p = reinterpret_cast<volatile uint16_t*>(hw);
188 volatile uint16_t orig = *p;
189 volatile uint16_t val = orig;
190
191 if (hw >= start_addr && hw < end_addr)
192 {
193 uint8_t b0 = src[hw - start_addr];
194 val = static_cast<uint16_t>((val & 0xFF00u) | b0);
195 }
196 if ((hw + 1u) >= start_addr && (hw + 1u) < end_addr)
197 {
198 uint8_t b1 = src[(hw + 1u) - start_addr];
199 val = static_cast<uint16_t>((val & 0x00FFu) | (static_cast<uint16_t>(b1) << 8));
200 }
201
202 if (val == orig) continue;
203
204
205 if (((~orig) & val) != 0u && orig != 0xE339u)
206 {
207 FLASH_Lock();
208 Flash_SetAccessClock_Sysclk();
209 ASSERT(false);
210 return ErrorCode::FAILED;
211 }
212
213 if (FLASH_ProgramHalfWord(hw, val) != FLASH_COMPLETE)
214 {
215 FLASH_Lock();
216 Flash_SetAccessClock_Sysclk();
217 ASSERT(false);
218 return ErrorCode::FAILED;
219 }
220
221 ASSERT(*p == val);
222
223 FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_WRPRTERR);
224 }
225
226 FLASH_Lock();
227 Flash_SetAccessClock_Sysclk();
228 return ErrorCode::OK;
229}
size_t size_
数据大小(字节)。 The size of the data (in bytes).
const void * addr_
数据存储地址(常量)。 The storage address of the data (constant).