c++ - 为什么我没有收到字节数组中的数据?

标签 c++ pointers arduino

我是 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/

相关文章:

c - 是否可以检查取消引用任意内存是否会使 C 中的程序先验崩溃?

visual-studio-code - Visual Studio Code 的智能感知无法识别 Arduino 端口管理

c++ - g++ 编译器如何包含 boost::regex

c++ - 输入类型转换?

c++ - 使用 Netbeans 在 C++ 中包含 <string>

C++如何正确复制指针的容器( vector )?

c++ - : list<object *> and list<object &> 之间的差异

c - Arduino 系列在 Debian 上运行良好,但在 Raspbian 上挂起

c++ - 串行监视器显示来自 Arduino Mega 的意外输入

c++ - STL或Boost中是否有QList类型的数据结构?