Writes data to the flash memory. 向闪存写入数据。
71{
73 {
74 return ErrorCode::ARG_ERR;
75 }
76
77 uint32_t addr = base_address_ + offset;
78 if (!IsInRange(addr, data.
size_))
79 {
80 return ErrorCode::OUT_OF_RANGE;
81 }
82
83 HAL_FLASH_Unlock();
84
85 const uint8_t* src =
reinterpret_cast<const uint8_t*
>(data.
addr_);
86 size_t written = 0;
87
88#if defined(STM32H7) || defined(STM32H5)
89 alignas(32) uint32_t flash_word_buffer[8] = {0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu,
90 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu,
91 0xFFFFFFFFu, 0xFFFFFFFFu};
92 while (written < data.
size_)
93 {
95
96 std::memcpy(flash_word_buffer, src + written, chunk_size);
97
98 if (memcmp(reinterpret_cast<const uint8_t*>(addr + written), src + written,
99 chunk_size) == 0)
100 {
101 written += chunk_size;
102 continue;
103 }
104
105 if (HAL_FLASH_Program(program_type_, addr + written,
106 reinterpret_cast<uint32_t>(flash_word_buffer)) != HAL_OK)
107 {
108 HAL_FLASH_Lock();
109 return ErrorCode::FAILED;
110 }
111
112 written += chunk_size;
113 }
114
115#else
116 while (written < data.
size_)
117 {
119
120 if (memcmp(reinterpret_cast<const uint8_t*>(addr + written), src + written,
121 chunk_size) == 0)
122 {
123 written += chunk_size;
124 continue;
125 }
126
127 uint64_t word = 0xFFFFFFFFFFFFFFFF;
128 std::memcpy(&word, src + written, chunk_size);
129
130 if (HAL_FLASH_Program(program_type_, addr + written, word) != HAL_OK)
131 {
132 HAL_FLASH_Lock();
133 return ErrorCode::FAILED;
134 }
135
136 written += chunk_size;
137 }
138#endif
139
140 HAL_FLASH_Lock();
141 return ErrorCode::OK;
142}
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
计算两个数的最小值