STM32F0 I2C HAL将结构保存到I2C EEPROM

时间:2016-10-22 10:38:42

标签: c struct stm32 eeprom

我需要保存一个结构:

struct {
  uint16_t value;
  uint16_t flag;
} status;

使用

进入外部I2C EEPROM
HAL_StatusTypeDef HAL_I2C_Mem_Write (I2C_HandleTypeDef * hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t * pData, uint16_t Size, uint32_t Timeout)

功能

你能建议我这样做的正确方法吗?

1 个答案:

答案 0 :(得分:2)

如果你仔细观察所有数据类型存储简单字节,区别在于字节的解释方式。

基本上你需要一个指向缓冲区的uint8_t* pData指针和要传输的字节数(uint16_t Size)。因此,将结构指针强制转换为uint8_t*并使用sizeof()获取大小。

这是一个模拟,请原谅我糟糕的测试环境(intunsigned char)。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  int value;
  int flag;
} status;

int main(void) {

    status stat;
    stat.value = 15;
    stat.flag = 1;

    int size = sizeof(status);                            // number of bytes to be sent
    unsigned char* pData;                                 // (uint8_t*) unsigned char* pointer to data

    unsigned char eeprom[size];                           // simulated EEPROM
    unsigned char pDataReceived[size];                    // for read back from EEPROM test
    status* read_back;                                    // for read back from EEPROM test

    printf("%d %d\n", stat.value, stat.flag);             // verify data in original format

    pData = (unsigned char*)(&stat);                      // cast data pointer to (uint8_t*) unsigned char*
    printf("%d %d\n", ((status*)pData)->value, ((status*)pData)->flag);   // verify data after cast

    memcpy(eeprom, pData, size);                          // I2C write bytes simulation
    printf("%d %d\n", ((status*)eeprom)->value, ((status*)eeprom)->flag); // verify data in simulated EEPROM

    memcpy(pDataReceived, eeprom, size);                  // I2C read bytes simulation
    read_back = (status*)(pDataReceived);                 // cast back to struct type
    printf("%d %d\n", read_back->value, read_back->flag); // verify received data in original format

    return 0;
}

写例:

struct status stat;
// operations on the struct
uint8_t* addressOfStruct= (uint8_t*)(&stat);
uint16_t sizeOfStruct  = sizeof(status);

HAL_StatusTypeDef HAL_I2C_Mem_Write (&hi2c, DevAddress, MemAddress, MemAddSize, addressOfStruct, sizeOfStruct, 100);

阅读示例:

struct status* read;
uint16_t sizeOfBuffer = sizeof(status);
uint8_t receiveBuffer[sizeOfBuffer];

HAL_StatusTypeDef HAL_I2C_Mem_Read (&hi2c, DevAddress, MemAddress, MemAddSize, receiveBuffer, sizeOfBuffer, 100);

read = (status*)(receiveBuffer); // or copy or move the data