通过Serial发送字符串到Arduino

时间:2013-11-08 12:11:57

标签: string serial-port arduino

我正在尝试向我的Arduino Yun发送一个字符串,并尝试根据我发送的内容回复它。

我在这里选择了一些代码的框架并且一直在试验它,但除了显示“准备好”的串行监视器之外,我无法继续下去。

代码是:

//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 = "";
    }
  } 
}

有人能指出我正确的方向吗?

由于

2 个答案:

答案 0 :(得分:0)

我怀疑问题是你在执行以下操作时将空终结符添加到字符串的末尾:incomingString += incomingByte。当您使用字符串对象(而不是原始char *字符串)时,您不需要这样做。该对象将自行处理终止。

结果是您的if条件实际上是这样做的:if ("hello\0" == "hello") ...。显然他们不平等,所以情况总是失败。

我认为解决方案只是确保如果字节为空,则不附加字节。

答案 1 :(得分:0)

试试这个:

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 = "";
}