c - Perl Device::SerialPort 不会使用 printf 显示传入数据(但可以使用 print)

标签 c perl arduino serial-communication

我正在写一个小问题,通过 USB 串口与 Arduino 对话。 我有一个关于 Arduino 发送数据和一切的小测试程序 如果我使用 print 显示数据,则有效,但如果我使用 printf(这是在 Perl 中),则无效。

下面的代码不起作用,print 语句被注释掉了。此代码将一遍又一遍地打印 <>。而如果我使用 print 而不是 printf 它将打印传入的数据。

use Device::SerialPort;

$ob = Device::SerialPort->new("/dev/ttyACM0") or die "new failed\n" ;
$ob->baudrate(115200) or die "parm set failed" ;
$ob->parity('none') or die "parm set failed" ;
$ob->databits(8) or die "parm set failed" ;
$ob->stopbits(1) or die "parm set failed";
$ob->handshake('none') or die "parm set failed" ;
$ob->write_settings or die "no settings\n";
while(1){
    ($count, $line) = $ob->read(255);
#   print  $line;
    printf("<%s>\n", $line);
}

最佳答案

我的问题不在于代码,而在于终端 (stdout) 缓冲输出。

读取返回零字符,因此 $line 是一个空字符串,它被静默添加到输出行缓冲区。最终 串行数据将接收行尾 (\n) 并导致缓冲区打印显示接收到的串行数据。

使用格式化的 printf,\n 导致每次读取返回时打印输出缓冲区。而且,这显示的和无尽的空流 括号。这让可怜的码头运算符(operator)感到困惑。

问题已解决....在尝试打印之前测试从读取返回的字符数。

use Device::SerialPort;
$ob = Device::SerialPort->new("/dev/ttyACM0") or die "new failed\n" ;
$ob->baudrate(115200) or die "parm set failed" ;
$ob->parity('none') or die "parm set failed" ;
$ob->databits(8) or die "parm set failed" ;
$ob->stopbits(1) or die "parm set failed";
$ob->handshake('none') or die "parm set failed" ;
$ob->write_settings or die "no settings\n";
while(1){
  ($count, $line) = $ob->read(255);
  if($count >0) {
    printf "<%s>\n", $line;
  }
}

关于c - Perl Device::SerialPort 不会使用 printf 显示传入数据(但可以使用 print),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30287832/

相关文章:

c++ - 如何确保数据类型与 C++ 中需要的一样大

c - 瓦尔格林德 C : Argument of function has a fishy (possibly negative) value

c - 如何将 "pointer to a pointer"传递给需要 "pointer to array"的函数

Perl 记录哪些脚本/模块访问了另一个模块

c++ - 在 Arduino ESP8266 上加载配置参数

mysql - 无法使用arduino连接到数据库服务器发送一些数据

c - 使用枚举时的高效 switch 语句

c - 我该如何解决?它崩溃了

regex - 什么匹配这个正则表达式 : qr/(? !)/;

regex - Perl:在替换字符串变量中使用反向引用