#!/usr/bin/perl -w use POSIX; $port = '2'; $fd = POSIX::open('/dev/ttyS'. $port, O_RDWR | O_NOCTTY) or die "$! in open"; $termios = POSIX::Termios->new; $termios->getattr($fd) or die "$! in getattr"; print $termios->getispeed, " ", $termios->getospeed, " ", POSIX::B9600, " ", POSIX::B38400, "\n"; POSIX::tcflush($fd, &POSIX::TCIOFLUSH); $buff = '!!SP2!SE'; POSIX::write($fd, $buff, 8); my $rin = ''; my $rout; vec($rin, fileno(STDIN), 1) = 1; my $sonar_in = ''; my $sonar_out; vec($sonar_in, $fd, 1) = 1; # # wait 1/20 second, or until keypress; if keypress, STOP! # until (select($rout=$rin, undef, undef, 0.5) == 1) { POSIX::tcflush($fd, &POSIX::TCIOFLUSH); $buff = '!!SR'; POSIX::write($fd, $buff, 4); $sonar_dist = 0; do { if (select ($sonar_out=$sonar_in, undef, undef, 0.5) == 1) { while (!defined ($ret = POSIX::read($fd,$sonar_buff, 1))) { print "<\n"; }; if ($sonar_buff !~ /\n/) { $sonar_dist = $sonar_dist * 10 + $sonar_buff; }; } else { $sonar_buff = "\n"; $sonar_dist = "TIMEOUT"; } } until ($sonar_buff =~ /\n/); print "$sonar_dist\n"; }; END { $buff = '!!SD'; POSIX::write($fd, $buff, 4); POSIX::close($fd); }