2013-10-11 24 views
1

我正在接收像0xFA5D0D01这样的数据包。 现在我想parce它像解析传入的数据包

FA是头1 5D是头2 0D是长度和 01是校验码。 const int data_availabe = Serial.available();

我能写串口,但不能parce像 如果我收到FA然后打印接收头1

const int data_availabe = Serial.available(); 
if (data_availabe <= 0) 
{ 
    return; 
} 
const int c = Serial.read(); 

Serial.print("Receive Status: "); 
Serial.println(STATE_NAME[receiveState]); 
Serial.print(c, HEX); 
Serial.print(" "); 
if (isprint(c))   //isprint checks whether it is printable character or not (e.g non printable char = \t) 
{ 
    Serial.write(c); 
} 
Serial.println(); 
Serial.println(receiveState); 

switch (receiveState) 
{ 
case WAITING_FOR_HEADER1: 
    if (c == HEADER1) 
    { 
     receiveState = WAITING_FOR_HEADER2; 

    } 
    break; 

case WAITING_FOR_HEADER2: 
    if (c == HEADER2) 
    { 
     receiveState = WAITING_FOR_LENGTH; 
    } 
    break; 
} 

因为我们正在exptected数据在哪里receiveState是枚举改变..

回答

2

我假设Arduino正在从USB接收数据。

if (data available <= 0)在做什么?如果您希望在串口读取数据的同时读取数据,则最好在{}内部执行if (Serial.avalaible() > 1),然后使用Serial.read()

如果初始化const你将无法改变其随时间的价值......

什么是readString以及它是如何初始化?

您是否尝试过Serial.print(c)以查看里面有什么?

再一次,如果您可以给我们更多关于为什么以及何时运行这段代码的背景,对我们来说会更容易。

编辑

#define HEADER_1 0xFA // here you define your headers, etc. You can also use variables. 

uint8_t readByte[4]; // your packet is 4 bytes long. each byte is stored in this array. 

void setup() { 
    Serial.begin(9600); 
} 

void loop() { 

    while (Serial.avalaible() > 1) { // when there is data avalaible on the serial port 

     readByte[0] = Serial.read(); // we store the first incomming byte. 
     delay(10); 

     if (readByte[0] == HEADER_1) { // and check if that byte is equal to HEADER_1 

      for (uint8_t i = 1 ; i < 4 ; i++) { // if so we store the 3 last bytes into the array 
       readByte[i] = Serial.read(); 
       delay(10); 
      } 

     } 

    } 

    //then you can do what you want with readByte[]... i.e. check if readByte[1] is equal to HEADER_2 and so on :) 

} 
+0

这不是关于USB,该系列是RS-232,如果你不知道答案,然后不回答。 –

+0

请查看更新后的问题......我无法解析它,因为预期..有些地方出了问题...... –

+0

@ChrisDesjardins我可能完全傻,但你怎么知道这一点? 我编辑了我的答案,告诉我,如果这是你想要做的。 – ladislas