arduino 关于serialEvent() 的问题
String inputString = ""; // a String to hold incoming databoolean stringComplete = false;// whether the string is complete
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
这个是arduino 官网提供 的程序
改成这样就不行了,不知为什么??
boolean flag==ture;
void loop() {
// print the string when a newline arrives:
while(flag==true){
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
} 仔细想想,arduino中的串口还是采用的查询的方式,不是中断的方式。可能吧 boolean flag==ture;
这句错了吧,而且感觉你的逻辑有点绕,又用了flag,又用stringComplete ,两个标志变量,不知道目的何在? catnull 发表于 2018-1-2 09:25
boolean flag==ture;
这句错了吧,而且感觉你的逻辑有点绕,又用了flag,又用stringComplete ,两个标志变 ...
boolean flag==false;
这里应该这样写,我打错了。
是这样的意图:就是通过串口发出一个命令后,等待收到命令后再执行下面的代码,所以用了一个flag 标志位。 本帖最后由 Super169 于 2018-1-4 13:43 编辑
看不到你的程式會在那裡變更 flag 的值.
如果你想在 serialEvent 變更 flag 的值, 要設定成 volatile, 否則 optimizer 會當成是不會改變的.
如果沒其他事要做, 只是要等待回傳, 直接 while (!Serial.available()); 就可以了.
boolean flag==true;这句本意是想赋值吧?写成比较了
就像楼上说的,不管初始值是true还是false,没有发现改变此值的语句。
页:
[1]