2021-5-31 22:10:10 [显示全部楼层]
2771浏览
查看: 2771|回复: 1

[进阶] 请问ESP32的例子为什么不能成功 串口不能接收数据 serialEvent()

[复制链接]
请问ESP32的例子为什么不能成功 串口不能接收数据
int zhengshu;
String zifu="zjybest esp32 first prog";//全局变量

void setup()
{
  Serial.begin(115200);    //串口调试

}

void loop()
{
  Serial.println(zifu);
  Serial.print("shuzi:");
  Serial.println(zhengshu);
  delay(1000);
}

void serialEvent()
{
  String intchars="";//局部变量
  String chars="";
  int temp;
  while(Serial.available()>0)//一直等待数据接收完成 用if的话loop函数执行一次接受1个字符
  {
    char inchar=Serial.read();
    if(isDigit(inchar)) //是数字就执行
    {
      intchars+=inchar;//数字字符串
    }
    else chars+=inchar;//否则就是字符串
  }
  temp=intchars.toInt();//将数字字符串转换成整数
  Serial.print("jieshou -.-ok");//调试加入的好习惯 ?可以不要此句
  zhengshu=temp;//赋值给全局变量,每次发送都覆盖原来的数据
  zifu=chars;//赋值给全局变量,每次发送都覆盖原来的数据
}


zjybest  学徒
 楼主|

发表于 2021-5-31 22:38:51


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;
    }
  }
}
回复

使用道具 举报

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

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail