Reputation: 75
I'm writing a short problem to talk to an Arduino over a USB serial port.
I have a little test program on the Arduino sending data and everything
works if I display the data with print
, but not if I use printf
(this is in Perl).
The code that doesn't work is below with the print
statement commented out. This code will print <> over and over. While if I use the print
instead of the printf
it will print the incoming data.
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);
}
Upvotes: 1
Views: 598
Reputation: 75
My problem was not the code but the terminals (stdout) buffered output.
The read was returning with zero characters so the $line was an empty string that is silently added to the output line buffer. Eventually the serial data would receive the end of line (\n) and cause the buffer to print displaying the received serial data.
With the formated printf the \n caused the output buffer to print every time the read returned. And, this displayed and endless stream of empty brackets. This confused the poor terminal operator.
Problem solved.... test the character count returned from the read before trying to printf it.
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;
}
}
Upvotes: 2