我正在通过Serial进行两次arduinos通信。它有效,但存在结构问题:当我从一个arduino发送数据时,另一个不知道她收到了什么...
是否可以为每个通信添加“标题”;与使用套接字或HTTP进行的事件正确通信的方法。有没有图书馆可以实现这一目标?
我认为序列化和反序列化JSON以在数据中添加“标题”但是它有点过分。
您可以使用类似于serial.parseint()的东西来分解您的串行传输,然后查找标头。如果你用逗号分隔所有的通信,那么你就会知道第一个被解析出来的是标题。解析逗号的arduino示例如下所示:
void loop() {
// if there's any serial available, read it:
while (Serial.available() > 0) {
// look for the next valid integer in the incoming serial stream:
int red = Serial.parseInt();
// do it again:
int green = Serial.parseInt();
// do it again:
int blue = Serial.parseInt();
// look for the newline. That's the end of your sentence:
if (Serial.read() == '\n') {
// constrain the values to 0 - 255 and invert
// if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);
// fade the red, green, and blue legs of the LED:
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
// print the three numbers in one string as hexadecimal:
Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);
}
}
}
获得标题后,您可以执行switch()语句来检查大小写:例如
while (Serial.available() > 0) {
int header = Serial.parseInt();
...
switch (header){
case header1:
code here...
break;
case header2:
code here...
break;
default:
break;
}