0

我正在将数据从 Arduino 发送到串口:

byte xBeeFrame[23];
unsigned int windData, 
signed int tempData;
xBeeFrame[0] = 0x7E;
xBeeFrame[18] = (windData >> 8) & 0xFF;
xBeeFrame[19] = windData & 0xFF;
xBeeFrame[20] = (tempData >> 8) & 0xFF;
xBeeFrame[21] = tempData & 0xFF;

问题是在 C 程序中解析这些数据。我怎么做猫?这是我读取串行端口的方式:

unsigned char bytes[254];
                if (read(tty_fd,bytes,sizeof(bytes))>0){
                    ///write(STDOUT_FILENO,bytes,sizeof(bytes));              // if new data is available on the serial port, print it out

感谢帮助!

4

1 回答 1

2

好的,所以我首先要做的是创建一个单独的头文件来声明您将用于在 Arduino 和 PC 之间进行通信的结构。所以在一个像comms.h

#ifndef COMMS_H
#define COMMS_H
typedef struct commFrame_t commFrame_t {
    unsigned int wind, 
    signed int temperature;     
}
#endif COMMS_H

然后在您的 Arduino 代码中,您需要#include "comms.h"发送数据,如下所示:

commFrame_t frame;
// Fill the frame with data
frame.wind = someWindValue;
frame.temperature = someTemperatureValue;
// Send the frame
Serial.write(&frame, sizeof(frame));

在 PC 端,您还将#include "comms.h"阅读相同的框架:

commFrame_t frame;

if (read(tty_fd,&frame,sizeof(frame))){
    // Process a frame
}

这不是万无一失的,因为丢失的字符会导致整个协议失控,但作为初始原型可能没问题。除非您将结构直接传递给某些 XBee 设备,否则我不明白为什么您需要分隔符。

于 2013-03-10T20:31:46.143 回答