我正在尝试从linux上的端口读取数据然后我想要使用这些数据我以为当我写下面的代码时,每个字节的数据都将存储在数组的一个单元格中,但是当我尝试测试并打印出来它总是第1个字节打印整个数据,所有其他字节都是空的。有谁知道如何在一个单元格中存储读取的每个字节。代码写下来请告诉我我错过了什么?
int decode_gps() {
while(1){
unsinged int UBX_buffer[40];
if (read(fd,&UBX_buffer,1)>0) {
// cout<<UBX_buffer[0]<<endl;
switch(UBX_step) //we start from zero and increment as we go through the cases
{
case 0:
if(UBX_buffer[0]==0xB5) UBX_step++; break; // UBX sync char 1 //check for the first data packet and go to next byte
case 1: if(UBX_buffer[1]==0x62) UBX_step++;// UBX sync char 2 //check for the second data packet and go to the next byte
else UBX_step=0; break; //if first and second packets are not correct then go back and check again
case 2: UBX_class=UBX_buffer[2]; checksum(UBX_class); UBX_step++; break;
case 3: UBX_id=UBX_buffer[3]; checksum(UBX_id); UBX_step++; break;
case 4: UBX_payload_length_hi=UBX_buffer[4]; checksum(UBX_payload_length_hi); UBX_step++; break;
case 5: UBX_payload_length_lo=UBX_buffer[5]; checksum(UBX_payload_length_lo); UBX_step++; break;
case 6: // Payload data read...
if (UBX_payload_counter < UBX_payload_length_hi) // We stay in this state until we reach the payload_length
{
UBX_buffer[UBX_payload_counter] = data;
checksum(data);
UBX_payload_counter++;
}
else
UBX_step++;
break;
case 7: ck_a=data; UBX_step++; break; // First checksum byte
case 8: ck_b=data; // Second checksum byte
// We end the GPS read...
if((ck_a= ck_a)&&(ck_b= ck_a)) // Verify the received checksum with the generated checksum..
parse_ubx_gps(); // Parse new GPS packet...
UBX_step=0;
UBX_payload_counter=0;
ck_a=0;
ck_b=0;
GPS_timer=0; //Restarting timer...
break;
} // End Switch
} //end if
} //end while loop
close(fd);
return(0);
}
答案 0 :(得分:1)
这一行:
if (read(fd,&UBX_buffer,1)>0)
读取一个字节。除了UBX_buffer[0]
之外,您永远不会将数据转换为该特定行。
不确定您是否打算使用:
if (read(fd,&UBX_buffer[UBX_step],1)>0)
另一方面,您一次只处理一个字节,因此只需将int UBX_buffer[40]
更改为unsigned char UBX_buffer;
,然后使用UBX_buffer
代替UBX_buffer[x]
即可我认为这个伎俩。
答案 1 :(得分:0)
不清楚使用哪个read()函数。应该将整个数据读入UXB_buffer吗?
我又不明白你的意思 “但是当我尝试测试并打印出来时,总是第一个字节打印整个数据而所有其他字节都是空的”
如果数据长度超过一个字节,第一个字节如何打印整个数据?