本文介绍了如何在Arduino上使用分隔符读取字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须通过计算机来管理伺服器.

I have to manage servos from a computer.

所以我必须将管理消息从计算机发送到Arduino.我需要管理伺服器和转角的数量.我正在考虑发送如下内容:"1; 130"(第一个伺服和转角130,距离为;").

So I have to send manage messages from computer to Arduino. I need manage the number of servo and the corner. I'm thinking of sendin something like this : "1;130" (first servo and corner 130, delimeter ";").

有没有更好的方法可以做到这一点?

Are there any better methods to accomplish this?

这是我的这段代码:

String foo = "";
void setup(){
   Serial.begin(9600);
}

void loop(){
   readSignalFromComp();
}

void readSignalFromComp() {
  if (Serial.available() > 0)
      foo = '';
  while (Serial.available() > 0){
     foo += Serial.read(); 
  }
  if (!foo.equals(""))
    Serial.print(foo);
}

这不起作用.有什么问题吗?

This doesn't work. What's the problem?

推荐答案

  • 您可以使用Serial.readString()和Serial.readStringUntil()进行解析arduino上来自Serial的字符串
  • 您还可以使用Serial.parseInt()从serial中读取整数值
    • You can use Serial.readString() and Serial.readStringUntil() to parsestrings from Serial on arduino
    • You can also use Serial.parseInt() to read integer values from serial
    • 代码示例

      int x;
      String str;
      
      void loop() 
      {
          if(Serial.available() > 0)
          {
              str = Serial.readStringUntil('\n');
              x = Serial.parseInt();
          }
      }
      

      要通过串行发送的值将是我的字符串\ n5",结果将是str =我的字符串"和x = 5

      The value to send over serial would be "my string\n5" and the result would be str = "my string" and x = 5

      注意:Serial.available()继承自Stream实用程序类. https://www.arduino.cc/reference/zh-CN/language/functions/communication/serial/available/

      Note: Serial.available() inherits from the Stream utility class.https://www.arduino.cc/reference/en/language/functions/communication/serial/available/

      这篇关于如何在Arduino上使用分隔符读取字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 06:53