Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 通过串口向Arduino发送字符串_String_Serial Port_Arduino - Fatal编程技术网

String 通过串口向Arduino发送字符串

String 通过串口向Arduino发送字符串,string,serial-port,arduino,String,Serial Port,Arduino,我目前正在尝试向我的Arduino云发送一个字符串,并试图让它根据我发送的内容回复 我在这里学习了一些代码的框架,并一直在尝试它,但除了显示“就绪”的串行监视器之外,我无法再进一步了 代码是: //declace a String to hold what we're inputting String incomingString; void setup() { //initialise Serial communication on 9600 baud Serial.begin(96

我目前正在尝试向我的Arduino云发送一个字符串,并试图让它根据我发送的内容回复

我在这里学习了一些代码的框架,并一直在尝试它,但除了显示“就绪”的串行监视器之外,我无法再进一步了

代码是:

//declace a String to hold what we're inputting
String incomingString;

void setup() {
  //initialise Serial communication on 9600 baud
  Serial.begin(9600);
  while(!Serial);
  //delay(4000);
  Serial.println("Ready!");
  // The incoming String built up one byte at a time.
  incomingString = "";
}

void loop () {
  // Check if there's incoming serial data.
  if (Serial.available() > 0) {
    // Read a byte from the serial buffer.
    char incomingByte = (char)Serial.read();
    incomingString += incomingByte;

    // Checks for null termination of the string.
    if (incomingByte == '\0') {
      // ...do something with String...
      if(incomingString == "hello") {
        Serial.println("Hello World!"); 
      }

      incomingString = "";
    }
  } 
}
谁能给我指出正确的方向吗


谢谢

我怀疑问题在于,当您这样做时,您正在将空终止符添加到字符串的末尾:incomingString+=incomingByte。当您使用字符串对象而不是原始字符*字符串时,您不需要这样做。对象将自行处理终止

结果是您的if条件有效地做到了这一点:if hello\0==hello。。。。显然它们不相等,所以条件总是失败的

我相信解决方案只是确保如果字节为null,则不会追加该字节。

尝试以下方法:

String IncomingData = "";
String Temp = "";
char = var;

void setup()
{
Serial.begin(9600);
//you dont have to use it but if you want
// if(Serial) 
{
  Serial.println("Ready");
}
//or
while(!Serial)
{delay(5);}
Serial.println("Ready");
void loop()
{
while(Serial.available())
{
  var = Serial.read();
 Temp = String(var);
 IncomingData+= Temp;
 //or
 IncomingData.concat(Temp);

 // you can try 
   IncomindData += String(var);
}
 Serial.println(IncomingData);
 IncomingData = "";
}

同意根据这一点,@adeptionvention应该替换incomingString+=incomingByte;if incomingByte=='\0'{和if incomeByte incomingString+=incomingByte;else{。