JimLS has asked for the wisdom of the Perl Monks concerning the following question:

I'm wanting a serial port monitor that displays the received data as hexadecimal and when it receives "01" it moves to a new line and starts the line with the time or elapsed time (format of time is not critical, I just want at least 1/10 second resolution for the time between messages). Seemed like a fairly simple thing to get started with but I'm not getting very far. Before I added the ord() it would just hang with no errors or output. After adding the ord() it outputs a continuous string of repeating "30". This is on XP with ActiveState perl.

#!/usr/bin/perl use strict; use warnings; use Win32::SerialPort; use Time::HiRes; my $PORT = "COM1"; # port to watch my $now; my $hex; my $inbyte; print "prog start \n"; my $starttime; $starttime = Time::HiRes::time(); $now = Time::HiRes::time() - $starttime; print "Before serial port iniialization time is: $now \n"; my $port = Win32::SerialPort->new($PORT) || die "Can't Open $PORT: $!" +; $port->databits(8); $port->baudrate(9600); $port->parity("none"); $port->stopbits(1); while(1) { $inbyte=ord($port->read(1)); $hex = unpack('H2', "$inbyte"); if ($inbyte == 1){ # assume this is start of new packet $now = Time::HiRes::time() - $starttime; print "\n $now $hex"; } else { print " ", $hex; } }

Replies are listed 'Best First'.
Re: Getting started - serial, bytes and hex output
by ikegami (Patriarch) on Feb 28, 2011 at 18:48 UTC

    "\x30" is "0". This would seem to indicate you've made an incorrect assumption as to what read returns. Checking the docs confirms this.

    ($count_in, $string_in) = $PortObj->read($InBytes); warn "read unsuccessful\n" unless ($count_in == $InBytes);