2017-06-25 74 views
-1

我有一个Arduino莱昂纳多,并试图使用它作为串行到USB转换器。在Serial1我有一个字符串以数字结尾。这个数字我试图通过USB连接到PC。它工作得很好,但最后我需要一个'\n',我不知道如何。当我在Keyboard.printlnKeyboard.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

键盘发送的键不是字符。该库只是将换行符转换为“Enter”键。 –

+0

欢迎来到Stack Overflow!在尝试提出更多问题之前,请阅读[我如何提出一个好问题?](http://stackoverflow.com/help/how-to-ask)。 –

+0

你为什么要把最后一个字符设置为'null',这就是你认识到'\ 0'的原因吧?这个字符串不是'\ n'分隔的字符串,你最需要在'\ 0'之前放置'\ n'。 –

回答

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); 
} 
+0

newLine,newLine,123,newLine – toolsmith

+0

然后制作你自己的。 –