Perl: Open a serial port at a given speed

I needed to open a serial port to read and write data from my Arduino. The after much digging I was able to come up with the following function to get a file handle for a given serial port at a specific speed.

use Fcntl qw(O_RDWR);

# Open a serial port at a given speed and return a filehandle
sub open_serial_port {
    my $dev   = shift();
    my $speed = shift();

    sysopen(my $fh, $dev, O_RDWR) or die("Unable to open $dev\n");

    # Figure out the integer that maps to a given speed
    # perl -E 'use IO::Tty qw( B115200 ); say B115200'
    my $speed_map = {
        9600   => 13,
        19200  => 14,
        38400  => 15,
        57600  => 4097,
        115200 => 4098,
    };

    my $speed_int = $speed_map->{$speed};
    if (!$speed_int) {
        die("Unable to find speed $speed\n");
    }

    # Set the baud on the FH
    my $attr = POSIX::Termios->new;
    $attr->getattr($fh->fileno);
    $attr->setispeed($speed_int);
    $attr->setattr($fh->fileno);

    $fh->autoflush;

    return $fh;
}
Leave A Reply
All content licensed under the Creative Commons License