Marais has asked for the wisdom of the Perl Monks concerning the following question:

Greetings, Perl monks:

I'm developing an application which communicates with an Arduino via USB. It runs in a POE environment. I use the Device::SerialPort module to talk to the USB port (as a file).

At times I want to close the connection (when certain errors occur) and re-open it. So far, closing the connection is not working for me. Here's how I open it:

use Symbol qw(gensym); use Device::SerialPort; (etc.) my $port, $handle; $handle = gensym(); $port = tie(*$handle, "Device::SerialPort", "/dev/ttyUSB0"); $port->baudrate(57600); (etc.)

By passing $handle to a POE ReadWrite wheel, I can communicate perfectly with the Arduino. I use the following code to try to close the connection, prior to re-opening it:

$port->close; undef $port; untie *$handle;

and this results in the error message:

<fh> select error: Bad file descriptor (hits=-1)

I have to admit that I don't understand what the "gensym" and "tie" stuff is all about; I'm just following the examples in the documentation, so it's almost certainly due to my ignorance. Can anyone explain how to properly close this port?

Replies are listed 'Best First'.
Re: Destroying tied serial port
by Marais (Novice) on Dec 23, 2012 at 22:00 UTC
    It's embarrassing how often the simple act of documenting your problem leads you to find the cause. In this case, I had a variable ($handle) defined both locally and globally - an old, old story. Fixing that did get me past the problem I described above, not surprisingly. Now of course there is another problem, but I'll consider that one myself a little more before asking for help. --- Marais

      Marais:

      It's not embarrassing at all. In fact it's an old and quite valuable debugging technique. That's why I frequently create a simple 'test case' program to try to illustrate a bug. The act often helps you understand what's going on, and can point out interactions with other parts of your program.

      It's also the reason that we frequently ask for a simple program that illustrates the problem. The act of doing that can help you answer the question yourself, which is a faster way to learn how to code.

      (It's also the reason I like Test Driven Development (TDD), as it's a similar (in some ways) process.)

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

Re: Destroying tied serial port
by jmlynesjr (Deacon) on Dec 24, 2012 at 02:23 UTC

    Also take a look at Device::SerialPort::Arduino. I'm using that to talk to a chipKIT UNO. Maybe something in the code will help you out.

    James

    There's never enough time to do it right, but always enough time to do it over...