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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #!/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"; } |
Nice! This is the first example that I’ve tried that actually worked! The main difference is that most sites have you use
my $byte = $port->lookfor(); #Which does not work!!!
my $byte = $port->read(1); #works!!!
Thanks!
Thanks for the simple example. Couple of notes, though:
The example above will spin on cpu, reading as fast as the processor can cycle through the loop.
# to effectively poll at .1 second intervals, try setting:
$port->read_char_time(0);
$port->read_const_time(100);
# and in your while loop, don’t have read do so much work, and only print if you have something to print:
while (1) {
my ($count,$bytes) = $port->read(255);
print “$bytes” if $count > 0;
}
The example above will spin on cpu, reading as fast as the processor can cycle through the loop.
# to effectively poll at .1 second intervals, try setting:
$port->read_char_time(0);
$port->read_const_time(100);
# and in your while loop, don’t have read do so much work, and only print if you have something to print:
while (1) {
my ($count,$bytes) = $port->read(255);
print “$bytes” if $count > 0;
}