2017-06-25 75 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

然後製作你自己的。 –