我想写一个固件,向EEPROM存储器写入结构并从中读取。将结构转换为字节流是可行的,然而,当我通过将结构放入命名空间或调用向结构传递指针的函数来抽象问题时,字节偏移量似乎会以2的倍数变化。
为了创建结构的内存映射,我正在使用以下方法:
template <typename U>
void StoreStruct(U *structure, unsigned int location) {
byte values[sizeof(U)];
memcpy(values, structure, sizeof(U));
...
}
template <typename U>
void RetrieveStruct(U *result, unsigned int location) {
byte readValues[sizeof(U)];
...
memcpy(result, readValues, sizeof(U));
}
当从公共名称空间调用这些时,它们将按预期运行。当从一组架构名称空间调用时,字节偏移量似乎会四处移动。这是意料之中的事吗?
更新:
测试代码:
eeprom.h:
#include <Wire.h>
#include <Arduino.h>
#ifndef EEPROM_H
#define EEPROM_H
struct ExampleStructure {
const byte magic[4] = {192,43,67,181};
byte settingsVersion[4] = {0, 0, 0, 1};
};
namespace EEPROM {
const int memoryI2CAddress = 0x50;
bool CompareArrays(byte *array1, byte *array2, unsigned int count) {
bool result = true;
for (unsigned int i = 0; i < count; i++) { result = result && (array1[i] == array2[i]); }
return result;
}
void ReadBytes(byte *result, unsigned int count, unsigned int baseAddress) {
while (Wire.available()) { Wire.read(); } //Clear buffer
Wire.beginTransmission(memoryI2CAddress);
Wire.write((byte)(baseAddress >> 8));
Wire.write((byte)(baseAddress & 0xFF));
Wire.endTransmission();
unsigned int returnCount = Wire.requestFrom(memoryI2CAddress, count);
for (unsigned int i = 0; i < returnCount; i++) { result[i] = Wire.read(); }
}
void WriteBytes(byte *values, unsigned int count, unsigned int address) {
Wire.beginTransmission(memoryI2CAddress);
Wire.write((byte)(address >> 8));
Wire.write((byte)(address & 0xFF));
Wire.write(values, count);
Wire.endTransmission();
delay(5);
byte checkBytes[count];
ReadBytes(checkBytes, count, address);
if (!CompareArrays(values, checkBytes, count)) { Serial.println("Written bytes not written correctly."); }
else { Serial.println("Everything went fine"); }
}
template <typename U>
void StoreStruct(U *structure, unsigned int location) {
byte values[sizeof(U)];
memcpy(values, structure, sizeof(U));
WriteBytes(values, sizeof(U), location);
}
void Initialise() {
Wire.begin();
ExampleStructure a;
a.settingsVersion[0] = 0;
a.settingsVersion[1] = 0;
a.settingsVersion[2] = 0;
a.settingsVersion[3] = 1;
StoreStruct(&a, 896);
}
}
#endif
settings.h
#include "eeprom.h"
#ifndef SETTINGS_H
#define SETTINGS_H
namespace Settings {
void Initialise() {
ExampleStructure a;
a.settingsVersion[0] = 0;
a.settingsVersion[1] = 0;
a.settingsVersion[2] = 0;
a.settingsVersion[3] = 1;
EEPROM::StoreStruct(&a, 896);
}
}
#endif
主文件:
#include "eeprom.h"
#include "settings.h"
void setup() {
Serial.begin(115200);
Settings::Initialise();
EEPROM::Initialise();
}
void loop() {}
输出:
Writing:
Written bytes not written correctly.
Writing:
Everything went fine
这个问题的答案很模糊,与结构和名称空间完全无关。从本质上讲,我使用的是一个不熟悉的库。(电线.h(