Arduino在串行计算机上第二次运行
当运行下面的程序时,它会按预期工作,但会为-38添加一个额外的输出作为输入。不管我使用什么输入,它也会打印出-38Arduino在串行计算机上第二次运行,arduino,Arduino,当运行下面的程序时,它会按预期工作,但会为-38添加一个额外的输出作为输入。不管我使用什么输入,它也会打印出-38 int number; void setup() { Serial.begin(9600); } void loop() { number=0; Serial.flush(); while(Serial.available() == 0) { //just waiting while nothing entered } while (Ser
int number;
void setup()
{
Serial.begin(9600);
}
void loop()
{
number=0;
Serial.flush();
while(Serial.available() == 0)
{
//just waiting while nothing entered
}
while (Serial.available()>0)
{
number = Serial.read() - '0';
// read the number in buffer and
//remove ASCII text for "0"
}
Serial.print("You entered: ");
Serial.println(number);
Serial.print(number);
Serial.print(" multiplied by two is ");
number = number * 2;
Serial.println(number);
}
输出如下所示:
>You entered: 4
>4 multiplied by two is 8
>You entered: -38
>-38 multiplied by two is -76
您的问题可能是
串行.flush
。正如美国所说,它
等待传出串行数据的传输完成。(在Arduino 1.0之前,这将删除所有缓冲的传入串行数据。)
您似乎试图实现刷新传入缓冲区的1.0之前的行为。因此,基本上,Serial.flush
在草图中什么都不做,这导致第二次运行读取和计算换行字符(在ASCII中为10)
您可以按如下方式清除缓冲区:
while ( Serial.available() > 0 ) {
Serial.read();
}
但请注意这部分
while (Serial.available()>0)
{
number = Serial.read() - '0';
// read the number in buffer and
//remove ASCII text for "0"
}
可能不会完全按照你的意愿去做。例如,如果您要通过串行发送12
,它可能只打印最后一个字符的结果(2
)。同样,您的程序也可能只输出-38
结果,因为最后一个字符始终是换行符。基本上,你只是运气好,串行数据发送的速度不够快,不可能发生这种情况,但一旦你的循环变长,它很可能会发生
我建议您将计算部分也移动到循环中,并检查输入数据,而不是在第一个字符后刷新缓冲区。考虑这一点:
while ( Serial.available() > 0 )
{
// read the number in buffer and
number = Serial.read();
// make sure the character is 0 - 9 in ASCII
if( number < '0' || number > '9' ){
// invalid character, skip
continue;
}
//remove ASCII text for "0"
number = number - '0';
Serial.print("You entered: ");
Serial.println(number);
Serial.print(number);
Serial.print(" multiplied by two is ");
number = number * 2;
Serial.println(number);
}
while(Serial.available()>0)
{
//读取缓冲区中的数字,然后
number=Serial.read();
//确保ASCII中的字符为0-9
如果(数字<'0'| |数字>'9'){
//无效字符,跳过
继续;
}
//删除“0”的ASCII文本
数字=数字-'0';
Serial.print(“您输入:”);
序列号println(编号);
序列号。打印(编号);
串行打印(“乘以2即为”);
数字=数字*2;
序列号println(编号);
}
这将逐字节读取缓冲区,并将乘法应用于每个(有效)字符。Awesome!非常感谢!!