从32位地址闪存中读取一个双精度值

时间:2014-02-03 15:45:01

标签: c pointers types type-conversion cortex-m3

我有一个32位微控制器,刚刚写了两个闪存。我现在想从内存中读取双回,但是当微控制器进入硬故障处理程序时,我正在做一些非法操作。

首先我尝试了:

double Flash_Read64(uint32_t address)
{
    return *((double *) address);
}

但这不起作用。是因为地址是32位而(double *)期望是64位吗?

然后我尝试了:

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;
}

但仍无效。

有什么建议吗?

编辑:

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;
}

1 个答案:

答案 0 :(得分:1)

简化并避免对齐问题(我认为这是引起悲伤的对齐问题。)

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;
}

[编辑]
我假设address表示具有四字节对齐的地址(其最少2位为0)。如果address没有8-byte alignment(其中至少3位为0)且需要double访问权限,那么

return *((double *) address);
// or 
return *tempPtr;

会导致总线故障。如果是这样,上面的代码应该处理这个问题 或者,代码可以确保address具有8-byte alignment