Firmata.pm 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package Device::Firmata;
  2. use strict;
  3. use warnings;
  4. use Device::Firmata::Constants;
  5. use Device::Firmata::Base
  6. ISA => 'Device::Firmata::Base',
  7. FIRMATA_ATTRIBS => {
  8. };
  9. =head1 NAME
  10. Device::Firmata - Perl interface to Firmata for the arduino platform.
  11. =head1 VERSION
  12. Version 0.64
  13. =cut
  14. our $VERSION = '0.64';
  15. our $DEBUG = 0;
  16. =head1 SYNOPSIS
  17. use strict;
  18. use warnings;
  19. use Device::Firmata::Constants qw/ :all /;
  20. use Device::Firmata;
  21. use Time::HiRes 'sleep';
  22. $|++;
  23. my $led_pin = 13;
  24. my $device = Device::Firmata->open('/dev/ttyUSB0') or die "Could not connect to Firmata Server";
  25. $device->pin_mode($led_pin=>PIN_OUTPUT);
  26. my $iteration = 0;
  27. while (1) {
  28. my $strobe_state = $iteration++%2;
  29. $device->digital_write($led_pin=>$strobe_state);
  30. sleep 0.5;
  31. }
  32. =head1 SUBROUTINES/METHODS
  33. =head2 open
  34. establish serial connection with an Arduino micro-controller. Single argument is the name of the device file mapped to the arduino. Typically '/dev/ttyUSB0' or 'COM9'
  35. =cut
  36. sub open {
  37. # --------------------------------------------------
  38. # Establish a connection to Arduino via the serial port
  39. #
  40. my ( $self, $serial_port, $opts ) = @_;
  41. # We're going to try and create the device connection first...
  42. my $package = "Device::Firmata::Platform";
  43. eval "require $package";
  44. my $serialio = "Device::Firmata::IO::SerialIO";
  45. eval "require $serialio";
  46. my $io = $serialio->open( $serial_port, $opts );
  47. my $platform = $package->attach( $io, $opts ) or die "Could not connect to Firmata Server";
  48. # Figure out what platform we're running on
  49. $platform->probe;
  50. return $platform;
  51. }
  52. sub listen {
  53. # --------------------------------------------------
  54. # Listen on socket and wait for Arduino to establish a connection
  55. #
  56. my ( $pkg, $ip, $port, $opts ) = @_;
  57. my $netio = "Device::Firmata::IO::NetIO";
  58. eval "require $netio";
  59. return $netio->listen( $ip, $port, $opts ) || die "Could not bind to socket";
  60. }
  61. 1;