USB, select(), POSIX::Termios, baudrates

The following script demonstrates USB IO. The connected device is an MCA (AXAS, FastComTec interface).

 
#!/usr/bin/perl
#
# [root@haso111m temp]# stty -F  /dev/ttyUSB0 -a
# speed 921600 baud; rows 0; columns 0; line = 0;
# intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
# eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
# werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
# -parenb -parodd cs8 hupcl -cstopb cread clocal -crtscts
# ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff
# -iuclc -ixany -imaxbel -iutf8
# -opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
# -isig -icanon -iexten -echo echoe -echok -echonl -noflsh -xcase -tostop -echoprt
# -echoctl -echoke
#
use strict;
use Fcntl;
use POSIX qw(:termios_h);

sysopen(USB, "/dev/ttyUSB0", O_RDWR) || die "failed to open \n"; 

my $term = POSIX::Termios->new();
$term->getattr( fileno(USB)) || die("Failed getattr: $!");
my $echo = $term->getlflag(); 
$echo &= ~ECHO;
$echo &= ~ECHOK;
$echo |= ECHOE;
$term->setlflag( $echo); 
$term->setcflag( &POSIX::CS8 | 
                 &POSIX::CREAD | 
	         &POSIX::CLOCAL | 
	         &POSIX::HUPCL); 
$term->setiflag( &POSIX::IGNBRK); 

$term->getattr( fileno(USB)) || die("Failed getattr: $!");
$term->setospeed( 4103); 
$term->setispeed( 4103); 
$term->setattr( fileno(USB), TCSANOW) || die "Failed setattr: $!";

my $com = "?\015\012"; # help
my $buffer = ""; 
my $cuffer = ""; 

syswrite(USB, $com, length( $com)) or die " write failed \n"; 

my $rin = my $win = my $ein = ""; 
vec( $rin, fileno( USB), 1) = 1; 
$ein = $rin | $win; 
my $nfd = select( $rin, $win, $ein, 0.1); 

while( $nfd)
{
    sysread(USB, $buffer, 1000);
    $cuffer .= $buffer;     
    $nfd = select( $rin, $win, $ein, 0.1); 
}
print " $cuffer \n"; 
close( USB);

Normally the function $term->setospeed() is invoked this way: $term->setospeed( &POSIX::B9600). However, the higher baud rates are not defined in the POSIX module yet. Still these speeds can be selected by supplying some code, e.g. 921600 bits per second is specified by $term->setospeed( 4103). The table 12.1 displays all codes.


Table 12.1: Baud rates and setispeed/setospeed
B0 0
B50 1
B75 2
B110 3
B134 4
B150 5
B200 6
B300 7
B600 8
B1200 9
B1800 10
B2400 11
B4800 12
B9600 13
B19200 14
B38400 15
B57600 4097
B115200 4098
B230400 4099
B460800 4100
B500000 4101
B576000 4102
B921600 4103
B1000000 4104
B1152000 4105
B2000000 4107
B2500000 4108
B3000000 4109
B3500000 4110
B4000000 4111