我很新的Arduino和我找不到任何方式來做到以下幾點。 我有一個typedef結構填補了多個值:將多個變量存儲到memcpy緩衝區
void loop() {
accel.process();
AccelerationReading accelData;
accelData.xAxis = accel.xAxis;
accelData.yAxis = accel.yAxis;
accelData.zAxis = accel.zAxis;
//Irrelevant code after this
}
後的結構充滿我memcpy
它的緩衝區:
uint8_t buffer[6];
memcpy((void*)buffer, (void*)&accelData, 6);
現在這工作正常,但我還需要讀取值來自兩個模擬端口,這兩個值也需要添加到memcpy中。填充兩個變量的代碼:
//New variables
int shortflexposition;
int longflexposition;
//Filling up the variables.
shortflexposition = analogRead(shortflexpin);
longflexposition = analogRead(longflexpin);
的accelData包含6個字節的原始值的,現在我想以後這些字節添加shortflexposition和longflexposition 。變量shortflexposition和longflexposition中的值總是介於0和1023之間。 我應該如何將這些其他變量添加到memcpy中?我試過例如:
uint8_t buffer[8];
memcpy((void*)buffer, (void*)&accelData + shortflexposition, 8);
但是,這似乎寧願增加價值eachother比將它們添加到下一個字節或東西。那麼,如何使用memcpy在下一個字節位置添加新變量?
謝謝! Yenthe
更新: 這是從倫丁代碼試圖..
typedef union
{
struct s
{
AccelerationReading accelData;
uint16_t shortflexposition;
uint16_t longflexposition;
};
uint8_t raw_data [sizeof(struct s)];
} my_data;
void setup() {
// Bean Serial is at a fixed baud rate. Changing the value in Serial.begin() has no effect.
Serial.begin();
accel.init();
}
void loop() {
accel.process();
AccelerationReading accelData;
my_data data;
data.accelData.xAxis = accel.xAxis;
data.accelData.yAxis = accel.yAxis;
data.accelData.zAxis = accel.zAxis;
//Get flex readings
int shortflexposition;
int longflexposition;
//Read the position of the flex sensor (0 to 1023?)
data.shortflexposition = analogRead(shortflexpin);
data.longflexposition = analogRead(longflexpin);
my_data some_other_data = data;
uint8_t buffer[6];
memcpy((void*)buffer, (void*)&accelData, 6);
Bean.setScratchData(1,buffer,6);
Bean.sleep(1000);
}
但給出了以下錯誤:
GetReader.ino: In function 'void loop()':
GetReader.ino:54:8: error: 'union loop()::my_data' has no member named 'accelData'
GetReader.ino:55:8: error: 'union loop()::my_data' has no member named 'accelData'
GetReader.ino:56:8: error: 'union loop()::my_data' has no member named 'accelData'
GetReader.ino:63:8: error: 'union loop()::my_data' has no member named 'shortflexposition'
GetReader.ino:64:8: error: 'union loop()::my_data' has no member named 'longflexposition'
感謝您的回覆@Lundin!我試圖實現它,但我得到錯誤..我用我現在擁有的完整代碼更新了我的問題!我錯過了什麼? – Yenthe
@Yenthe更新了適用於較老編譯器的示例。 – Lundin
嗯是的,這似乎工作!那麼我現在怎樣才能取代Bean.setScratchData(1,buffer,6);與新的數據?我試圖將緩衝區更改爲some_other_data,但它需要一個const uint8_t變量..我不知道該如何轉換它? – Yenthe