【发布时间】:2017-11-28 14:09:33
【问题描述】:
我有一个 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
}
}
【问题讨论】:
-
键盘发送的是键而不是字符。该库只是将换行符转换为“Enter”键。
-
欢迎来到 Stack Overflow!在尝试提出更多问题之前,请阅读How do I ask a good question?。
-
你为什么要将最后一个字符设置为
null,这就是\0,你意识到了吗?这将分隔字符串而不是\n,您最有可能需要将\n放在\0之前。 -
对不起朋友,我很笨。故障是时间问题。我在从函数中获取字符串之后并在发送到键盘之前插入了一个延迟(50)。所以字符串连接正确,我得到了我可爱的 1234567891011。谢谢你的帮助。
-
那么您应该将解决方案添加为答案并为未来的读者接受它