【发布时间】:2015-10-31 18:02:31
【问题描述】:
背景 我正在使用 IAR Embedded Workbench IDE 和在 STM32F091(ARM Cortex-M0 内核)微控制器上运行的工具链开发一个用 C 语言编写的嵌入式应用程序。应用程序将数据写入微控制器嵌入式闪存,其中只能输入 32 位字(也许半字也可以)。
问题描述 数据存储在一个 uint8_t 字节类型数组中,其开头是一些头信息(在这种情况下是来自板载调制解调器的 AT 响应代码),不应将其写入闪存。我想发送一个 uint32_t 指针,指向 uint8_t 缓冲区中实际数据开始的位置。但是如果这个偏移量不是 4 字节对齐的,我的应用程序就会崩溃,因为它试图访问一个未对齐的 uint32_t 类型。
这描述了我正在尝试做的事情(不是真正的代码,只是一个例子):
uint8_t modemResponseBuffer[MAX_MODEM_RESPONSE_SIZE];
/* Get the modem response data (including modem response header data) */
size_t modemResponseSize = GetModemResponseData(modemResponseBuffer);
/* Get the actual data size from the header information */
size_t dataSize = GetActualDataSizeFromModemResponseHeader(modemResponseBuffer);
/* Get the offset to where the actual data starts in the modem response */
size_t modemDataOffset = GetModemResponseDataOffset(modemResponseBuffer);
/* Write the data part of the response to embedded flash memory.
The modemDataOffset can be any number which messes up 4 byte data alignment */
ProgramFlashMemory(DATA_FLASH_STORAGE_ADDRESS, (uint32_t*)&modemResponseBuffer[modemDataoffset],
dataSize);
在ProgramFlashMemory函数内部,FLASH_ProgramWord标准外设库函数被循环调用。
问题 我如何有效地解决这个问题?我正在使用内存有限(32 kb RAM)的系统,因此我不希望将所需内容从 uint8_t 缓冲区复制到 uint32_t 类型的新缓冲区。目前我已经通过循环手动逐字节对齐数据,但这对我来说似乎相当笨拙。但我还没有想出更好的解决方案,我对我可能在这里收到的建议很感兴趣。
另外,如果有人知道,我也想知道为什么应用程序在这种情况下会崩溃。我的核心(或任何核心?)无法处理未对齐的数据类型的原因是什么?
【问题讨论】:
-
需要表头数据吗?
-
好吧,我需要它来识别应用程序正在接收的数据类型及其大小。如果我为说明问题而制作的示例不清楚,我很抱歉。
-
写入闪存后是否需要标头?
-
在回答我的问题时,我想到了这个问题:您确定
ProgramFlashMemory ()期望字节数 (uint8_t) 而不是uint32_t的数量吗? -
"...我的应用程序崩溃了,因为它尝试访问未对齐的 uint32_t 类型。"您对此有何结论?