C读取和解析串行端口

C读取和解析串行端口,c,serial-port,arduino,C,Serial Port,Arduino,我正在将数据从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; xBee

我正在将数据从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;
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
问题是在C程序中解析这些数据。我怎么做? 以下是我如何读取串行端口:

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;
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

谢谢你的帮助

好的,我首先要做的是创建一个单独的头文件来声明用于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代码中,您需要
#包括“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端,您还将
#包括“comms.h”
,并读取相同的帧:

commFrame_t frame;

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

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

我很好奇,为什么您使用的结构称为xBeeFrame-您只是通过串行端口发送,对吗?有没有理由不将其声明为结构?还有,为什么字节1-17是空的?最后,为什么要将其读入254字节的缓冲区?1-17不是空的。他们被另一个数据填满了。例如,xBeeFrame[0]是0x7E(分隔符)。问题是我是C语言的新手,不知道如何读取数据。你能推荐一下吗?我可以使用什么作为读取缓冲区?谢谢,谢谢。我试试看。使用分隔符,因为我有4个arduino+xbee设备,它们(每秒)向另一个连接到PC的xbee设备发送温度和风数据。因此,串行端口中的数据以混乱的顺序进行传输。