1

我收到一个像 0xFA5D0D01 这样的数据包。现在我想把它像

FA 是 Header1 5D 是 Header2 0D 是长度,01 是校验和。常量 int data_available = Serial.available();

我能够写入串行端口,但不能像收到 FA 那样将其打包,然后打印收到的 Header1

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

当我们获得预期的数据时,receiveState 正在发生变化。

4

1 回答 1

3

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

if (data available <= 0)做什么?如果你想在串口可用的时候从串口读取数据,你最好if (Serial.avalaible() > 1)在.Serial.read(){}

如果您初始化 aconst您将无法随着时间的推移更改其值...

什么是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 :)

}
于 2013-10-11T07:15:03.247 回答