Ok. Maybe the following will help.
package Device::SerialPort::Arduino;
use strict;
use warnings;
use Time::HiRes;
use Carp;
use Device::SerialPort;
use vars qw($VERSION);
our $VERSION = '0.07';
sub new {
my $class = shift;
my $self = bless {}, $class;
my %init = @_;
# Sets many parameters for Device::SerialPort usage
$self->{'port'} = $init{'port'};
$self->{'baudrate'} = $init{'baudrate'};
$self->{'databits'} = $init{'databits'};
$self->{'parity'} = $init{'parity'};
$self->{'stopbits'} = $init{'stopbits'};
$self->initialize();
return $self;
}
sub initialize {
my $self = shift;
$self->{'DSP'} = Device::SerialPort->new( $self->{'port'} )
or croak "Can't open " . $self->{'port'} . " - $!\n";
# Checks if the baudrate was defined otherwise sets a default
# value which is 9600
$self->{'baudrate'} = 9600
unless ( defined( $self->{'baudrate'} ) );
$self->{'DSP'}->baudrate( $self->{'baudrate'} );
# Checks for some default parameters which shouldn't be changed
$self->{'databits'} = 8
unless ( defined( $self->{'databits'} ) );
$self->{'parity'} = 'none'
unless ( defined( $self->{'parity'} ) );
$self->{'stopbits'} = 1
unless ( defined( $self->{'stopbits'} ) );
# Sets the remaining parameters
$self->{'DSP'}->databits( $self->{'databits'} );
$self->{'DSP'}->parity( $self->{'parity'} );
$self->{'DSP'}->stopbits( $self->{'stopbits'} );
}
sub communicate {
my $self = shift;
my $chars = shift;
# Returns 0 if $chars is an empty string
return 0 unless $chars;
$self->{'DSP'}->write($chars);
return $chars;
}
sub receive {
my $self = shift;
my $delay = shift;
while (1) {
# Check if any data is coming in. If true
# returns the character just catched.
my $char = $self->{'DSP'}->lookfor();
return $char
if $char;
# The following lines, will be used for
# slower reading, but lower CPU usage, and to
# avoid buffer overflow due to sleep function. (arduino.cc)
if ( defined $delay ) {
$self->{'DSP'}->lookclear;
sleep($delay);
}
}
}
James
There's never enough time to do it right, but always enough time to do it over...