Serial Communication in Perl

Serial communication is still used a bit today. Arduino's are fun programmable microcontrollers and the main method of communication is serial over USB. This example will show you how to communicate using serial in Perl.

In Windows, the Win32::SerialPort module should be used. It only worked with 32-bit Perl too. On Linux, use Device::SerialPort. Both modules can be installed from CPAN. They both have the same methods and are used the same way, only the name is different. Also, in Windows the device name will be COM1 or similar. On Linux it will be /dev/ttyUSB3 or similar. You can use dmesg after plugging in the device to see what it connected as.

# For Linux
use Device::SerialPort;
my $port = Device::SerialPort->new("/dev/ttyUSB3");

# For Windows. You only need one or the other.
# Uncomment these for Windows and comment out above
#use Win32::SerialPort;
#my $port = Win32::SerialPort->new("COM3");

$port->baudrate(9600); # Configure this to match your device

$port->write("\nBegin perl serial listener\n");

while (1) {
    my $char = $port->lookfor();
    if ($char) {
        print "Received character: $char \n";
    $port->lookclear; # needed to prevent blocking
    sleep (1);

# Writing to the serial port
# $port->write("This message going out over serial");