Want some programming help? [close]

Serial Communication in Perl

Introduction

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.

Install SerialPort library

You will first need to install cpan and then you can install the serial library with:

cpan install Device::SerialPort
# or
cpan install Win32::SerialPort

Example

Here is some example code how to to read and write over the serial port.

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

# For Windows. You only need one or the other.
# Uncomment these two lines below 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->databits(8);
$port->parity("none");
$port->stopbits(1);

$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");

Here is another simple example that will simple read and output any data received:

use Device::SerialPort;
# use Win32::SerialPort;  # Use instead for Windows

my $port = Device::SerialPort->new("/dev/ttACM0");
$port->baudrate(115200); # Configure this to match your device
$port->databits(8);
$port->parity("none");
$port->stopbits(1);

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

Conclusion

After reading this you should understand how to do very basic serial console interaction using Perl.

References

Advertisement