如果您關閉所有數據類型存儲簡單字節,不同之處在於如何解釋字節。
基本上你需要一個uint8_t* pData
指向緩衝區的指針和要傳輸的字節數(uint16_t Size
)。所以將結構指針轉換爲uint8_t*
並使用sizeof()
獲取大小。
這裏是一個模擬,請原諒我我糟糕的測試環境(int
s和unsigned char
s)。
#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
@danstm你設法得到它的工作? –
是的!非常感謝你。 – danstm