无法向字符串添加换行符

时间:2017-06-25 15:25:38

标签: arduino hid lf

我有一个Arduino Leonardo,并尝试将其用作串口转USB转换器。在Serial1我有一个以数字结尾的字符串。这个数字我试图通过USB进入PC。它工作得非常好,但我最后需要一个'\n',我不知道如何。当我在第Keyboard.println行或Keyboard.write行中尝试时,我会得到不同数量的行,其中预期的数字会被拆分。

#include <Keyboard.h>
String myEAN ="";
const int myPuffergrosse = 50;
char serialBuffer[myPuffergrosse];
void setup() {
    Keyboard.begin();
    Serial1.begin(9600);
    delay(1000);
}
String getEAN (char *stringWithInt)
// returns a number from the string (positive numbers only!)
{
    char *tail;
    // skip non-digits
    while ((!isdigit (*stringWithInt))&&(*stringWithInt!=0)) stringWithInt++;
    return(stringWithInt);
} 

void loop() {   
    // Puffer mit Nullbytes fuellen und dadurch loeschen
    memset(serialBuffer,0,sizeof(myPuffergrosse));
    if ( Serial1.available() ) {
        int incount = 0;
        while (Serial1.available()) {
            serialBuffer[incount++] = Serial1.read();      
        }
        serialBuffer[incount] = '\0';  // puts an end on the string
        myEAN=getEAN(serialBuffer);
        //Keyboard.write(0x0d);  // that's a CR
        //Keyboard.write(0x0a);  // that's a LF
    }
}

1 个答案:

答案 0 :(得分:0)

由于myEAN是一个字符串,只需添加字符...

myEAN += '\n';

或者,对于完整回车/换行组合:

myEAN += "\r\n";

请参阅文档:https://www.arduino.cc/en/Tutorial/StringAppendOperator

我建议您在getEAN函数中使用String ...

String getEAN(String s)
{
  // returns the first positive integer found in the string.

  int first, last;
  for (first = 0; first < s.length(); ++first)
  {
     if ('0' <= s[first] && s[first] <= '9')
       break;
  }
  if (first >= s.length())
    return "";

  // remove trailing non-numeric chars.
  for (last = first + 1; last < s.length(); ++last)
  {
     if (s[last] < '0' || '9' < s[last])
       break;
  }

  return s.substring(first, last - 1);
}