我是 C++ 初学者,正在尝试为我的 Arduino 创建一个程序。下面的代码编译正常,但结果与我预期的不同。
我希望在我的 PC 上收到的是:0x04、0x61、0x62、0x63。
我在我的电脑上收到的是:0xff 0x00 0xb1 0x00。
我尽量减少代码,使其只解决我遇到的问题。
byte *assembleFrame() {
byte frame[] = { 4 , 'a' , 'b' , 'c' , 'd' };
return frame;
}
void setup() {
Serial.begin( 115200 );
};
void loop() {
byte *frame = assembleFrame();
Serial.write( frame , 4 );
// should send 0x04 0x61 0x62 0x63, leaving out 0x64 being 5th element.
while ( 1 ) {
}
}
我认为它与指针有关,但无法弄清楚。
仅供引用:
Serial.write( buf , len ) arguments:
buf: an array to send as a series of bytes
len: the length of the buffer
编辑: 到目前为止的解决方案:
int assembleFrame( byte *frame ) {
int octetCounter = 0;
frame[ octetCounter++ ] = 'A'; // preamble
frame[ octetCounter++ ] = 'B'; // preamble
frame[ octetCounter++ ] = 0; // frame length set at end of function
frame[ octetCounter++ ] = h;
frame[ octetCounter++ ] = m;
frame[ octetCounter++ ] = s;
frame[ 2 ] = octetCounter; // frame length
return frame[ 2 ];
}
void loop() {
int bytes_in_frame = assembleFrame( frame );
Serial.write( frame, bytes_in_frame ); // assuming ptr + bytes to send
delay( 1000 );
}
它给出了想要的结果。
最佳答案
+Krister 的回答很好,如果可能的话,我会建议您将缓冲区传递给您的汇编函数来改进它。
/* Takes in an array of bytes with at least the given size, returns
* the number of bytes written into the frame.
*/
int assembleFrame(byte *frame, int frame_size) {
frame[0] = 4;
frame[1] = 'a';
frame[2] = 'b';
frame[3] = 'c';
frame[4] = 'd';
return 5; // only used five bytes in the frame
}
/* then in loop() */
byte frame[10];
bytes_in_frame = assembleFrame(frame, 10);
someDataSendingFunction(frame, bytes_in_frame); // assuming ptr + bytes to send
这样你就不会在以后造成内存泄漏的可能性。
关于c++ - 为什么我没有收到字节数组中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10079338/