2013-10-11 53 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