STM32F0 I2C HAL 保存结构到 I2C EEPROM

STM32F0 I2C HAL save struct to I2C 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)

函数

你能建议我一个正确的方法吗?

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

基本上你需要一个 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