Connect to Serial Port Using Perl


This is a simple example of how to control a serial port using perl in linux.
For WIN32 systems please check out the Win32::Serial module.


#!/usr/bin/perl

use Device::SerialPort;

my $port = Device::SerialPort->new("/dev/ttyUSB0");
$port->databits(8);
$port->baudrate(19200);
$port->parity("none");
$port->stopbits(1);

while(1) {
my $byte=$port->read(1);
print "$byte";
}

Share

10 responses to “Connect to Serial Port Using Perl”

  1. if you take a look at the original post above you should see how to read from the serial port once you have connected. I have included below for clarity.

    while(1) {
    my $byte=$port->read(1);
    print “$byte”;
    }

  2. I am not a programmer. I try to crank up a small perl script to read an IO Board through the serial port. If I send the command ~ver~ from minicom, the board responds with ~VER:3.1~

    When I ran the following code, the board prints the correct response into the minicom window. How can I read the port from perl?

    #!/usr/bin/perl
    use Device::SerialPort;
    my $port = Device::SerialPort ->new(“/dev/ttyACM0”);
    $port->baudrate(115200);
    $port->parity(“none”);
    $port->databits(8);
    $port->stopbits(1);
    $port->handshake(“xoff”);
    $port->write_settings;
    $port->write(“~ver~”);

    # how can I read the port?

  3. Don’t forget to $port->write_settings; or you will be left wondering why things are not working the way you expect.

    Following from cpan doc on Device::SerialPort (which is a cut and paste of the Win32::SerialPort doc)

    $PortObj = new Win32::SerialPort ($PortName, $quiet)
    || die “Can’t open $PortName: $^E\n”; # $quiet is optional

    $PortObj->user_msg(ON);
    $PortObj->databits(8);
    $PortObj->baudrate(9600);
    $PortObj->parity(“none”);
    $PortObj->stopbits(1);
    $PortObj->handshake(“rts”);

    $PortObj->write_settings || undef $PortObj;

  4. Sorry Jaynail I have not personally used the zwave controller in my projects so I don’t have much advise to give in relation to zwave.

  5. Hi all

    Need help,

    Did you experience using zwave controller in linux host? How did you manage the data?

%d bloggers like this: