[英]Read a double from 32-bit address flash memory
I have a 32-bit microcontroller and have just written a double to the flash memory. 我有一个32位微控制器,并且刚刚向闪存中写入了两倍。 I now want to read the double back from memory, but I am doing something illegal as the microcontroller goes to the hard fault handler. 现在,我想从内存中读取double,但是当微控制器进入硬故障处理程序时,我在做非法的事情。
First I tried: 首先,我尝试了:
double Flash_Read64(uint32_t address)
{
return *((double *) address);
}
but this did not work. 但这没有用。 Is it because address is 32-bit and the (double *) expect a 64-bit? 是因为地址是32位并且(double *)期望是64位吗?
I then tried: 然后,我尝试:
double Flash_Read64(uint32_t address)
{
uint64_t temp;
double * tempPtr = (double *) &temp;
//Increment address.
address += 4;
//Get MSB.
temp = (*((uint32_t *) (address)));
//Shift MSB to upper half.
temp = (temp << 32);
//Decrement address.
address -= 4;
//Get LSB.
temp |= (*((uint32_t *) address));
return *tempPtr;
}
but still not working. 但仍然无法正常工作。
Any suggestions? 有什么建议么?
EDIT: 编辑:
bool_t Flash_Write64Address(uint32_t address, double data)
{
uint32_t MSB, LSB;
uint32_t * tempPtr = (uint32_t *) &data;
//Get LSB.
LSB = tempPtr[0];
//Write LSB to flash.
flashStatus = FLASH_ProgramWord(address, LSB);
if(flashStatus != FLASH_COMPLETE)
{
DEBUG("Failed to write to flash at address: %u", (unsigned int) address);
return FALSE;
}
//Increment address.
address += 4;
//Get MSB.
MSB = tempPtr[1];
//Write MSB to flash.
flashStatus = FLASH_ProgramWord(address, MSB);
if(flashStatus != FLASH_COMPLETE)
{
DEBUG("Failed to write to flash at address: %u", (unsigned int) address);
return FALSE;
}
return TRUE;
}
To simplify and avoid alignment issues (which I think it is the alignment issue that is causing grief.) 为了简化和避免对齐问题(我认为正是对齐问题引起了悲伤。)
typedef union {
double d;
uint32_t u[2];
} Xlate;
bool_t Flash_Write64Address(uint32_t address, double data) {
Xlate x;
x.d = data;
for (int i=0; i < 2; i++) {
int flashStatus = FLASH_ProgramWord(address, x.u[i]);
address += 4;
if(flashStatus != FLASH_COMPLETE) {
return FALSE;
}
return TRUE;
}
double Flash_Read64(uint32_t address) {
Xlate x;
x.u[0] = *((uint32_t *) address);
x.u[1] = *((uint32_t *) (address + 4));
return x.d;
}
[Edit] [编辑]
I am supposing that address
represents an address with quad-byte alignment (its least 2 bits are 0). 我假设该address
表示一个四字节对齐的地址(至少2位为0)。 If address
did not have 8-byte alignment
(its least 3 bits are 0) and a double
access required it, then 如果address
没有8-byte alignment
(至少3位为0),并且需要double
访问,则
return *((double *) address);
// or
return *tempPtr;
would cause a bus fault. 会导致总线故障。 If this is true, the above code should handle this issue. 如果是这样,则上面的代码应处理此问题。
Alternatively code could insure address
has 8-byte alignment
. 或者,代码可以确保address
具有8-byte alignment
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.