0

我有一个 Arduino Leonardo 并试图将它用作串行到 USB 转换器。在Serial1我有一个以数字结尾的字符串。这个号码我试图通过 USB 连接到 PC。它工作得很好,但我'\n'最后需要一个,我不知道怎么做。当我在 lineKeyboard.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
    }
}
4

1 回答 1

1

由于 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);
}
于 2017-06-26T16:38:01.983 回答