极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 16172|回复: 5

arduino 关于serialEvent() 的问题

[复制链接]
发表于 2018-1-1 11:24:47 | 显示全部楼层 |阅读模式
String inputString = "";         // a String to hold incoming data
boolean 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;
  }
   }
}
回复

使用道具 举报

 楼主| 发表于 2018-1-1 12:49:37 | 显示全部楼层
仔细想想,arduino中的串口还是采用的查询的方式,不是中断的方式。可能吧
回复 支持 反对

使用道具 举报

发表于 2018-1-2 09:25:17 | 显示全部楼层
boolean flag==ture;
这句错了吧,而且感觉你的逻辑有点绕,又用了flag,又用stringComplete ,两个标志变量,不知道目的何在?
回复 支持 反对

使用道具 举报

发表于 2018-1-2 14:11:55 | 显示全部楼层
catnull 发表于 2018-1-2 09:25
boolean flag==ture;
这句错了吧,而且感觉你的逻辑有点绕,又用了flag,又用stringComplete ,两个标志变 ...


boolean flag==false;
这里应该这样写,我打错了。
是这样的意图:就是通过串口发出一个命令后,等待收到命令后再执行下面的代码,所以用了一个flag 标志位。
回复 支持 反对

使用道具 举报

发表于 2018-1-4 13:42:32 | 显示全部楼层
本帖最后由 Super169 于 2018-1-4 13:43 编辑

看不到你的程式會在那裡變更 flag 的值.

如果你想在 serialEvent 變更 flag 的值, 要設定成 volatile, 否則 optimizer 會當成是不會改變的.
如果沒其他事要做, 只是要等待回傳, 直接 while (!Serial.available()); 就可以了.
回复 支持 反对

使用道具 举报

发表于 2018-1-6 11:21:30 | 显示全部楼层
boolean flag==true;  这句本意是想赋值吧?写成比较了

就像楼上说的,不管初始值是true还是false,没有发现改变此值的语句。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-19 16:51 , Processed in 0.044549 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表