我收到的信息包如0xFA5D0D01。 现在我想像
那样进行分类FA是Header1 5D是Header2 0D是长度和 01是校验和。 const int data_availabe = 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是枚举更改。
答案 0 :(得分: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 :)
}