我想在UART的传入字节流中检测某个字节模式。我正在使用Arduino。目前,代码检测到单个\r
字符。检测到此字符后,此字符之前的字节流将存储到缓冲区中。这很简单。这是我的代码;
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0 ) {
// read the incoming byte:
incomingByte = Serial.read();
if (incomingByte != '\r') {
buffer_incoming_data[index_buffer]=incomingByte;
index_buffer++;
} else {
index_buffer = 0;
}
}
}
这是我的问题。我想检测一个类似于\r
的字节模式,而不是单个字符0xAA 0xBB 0xCC
。检测到此字节模式时,字节模式之前的字节流将存储到缓冲区中。
答案 0 :(得分:1)
猜猜你在实际循环运算符中调用了loop()方法。我可以建议下一个方法:
int incomingByte = 0; // for incoming serial data
int pattern [] = {0xAA, 0xBB, 0xCC};
int patternIndex = 0;
int patternSize = sizeof(pattern)/sizeof(pattern[0]);
void loop() {
// send data only when you receive data:
if (Serial.available() > 0 ) {
// read the incoming byte:
incomingByte = Serial.read();
if(pattern[patternIndex] != incomingByte){
// if we found begin of pattern but didn't reach the end of it
if(patternIndex>0){
for(int i=0; i<=patternIndex-1; i++){
buffer_incoming_data[index_buffer]=pattern[i];
index_buffer++;
}
}
patternIndex = 0;
}
if(pattern[patternIndex] == incomingByte){
patternIndex++;
}else{
buffer_incoming_data[index_buffer]=incomingByte;
index_buffer++;
}
//if we reached the end of pattern
if(patternIndex==patternSize){
//do something with buffer
patternIndex = 0;
index_buffer = 0;
}
}
}
正如您所看到的,我没有检查index_buffer
“索引超出范围”异常,但您应该这样做。希望我能帮到你。