I'm working on a stepper motor project with the Raspberry Pi and I needed to detect when an an optical mouse stops seeing motion. I'm using the mouse in place of an optical encoder to tell me when the stepper is stalled.
This code works on Raspbian with or without X. Since POSIX::read() waits for mouse events at first I thought I would have to use a second thread to poll somehow. Then I found the alarm function in "Programming Perl".
I found solutions for reading raw mouse data in Python but of course I wanted to do it in Perl. And I'm sharing it here so others can find it. (The oo Mouse module makes websearches for Perl related mouse projects difficult to find.)
#!/usr/bin/perl
use warnings;
use strict;
use POSIX;
use Time::HiRes qw( ualarm );
### Detect if the mouse is moving or stopped. Tested on Raspian Linux.
### Adapted from http://www.the-ownage.com/?p=835
### The guy soldered a pair of wires to a mouse button
### and used it to detect water leaks and send himself notifications.
my $fd;
my $buf;
my $mousedev="/dev/input/mouse0";
$fd = POSIX::open($mousedev, &POSIX::O_RDONLY) or die ("Cannot open $m
+ousedev: $!");
my $stopped = 1;
print time,"--Mouse is stopped--\n";
while( 1 ) {
local $SIG{ALRM} =
sub {
print time,"--Mouse is stopped--\n" if ! $stopped; #on tra
+nsition
$stopped = 1; ### turn on output bit on Raspberry Pi
$buf ="";
};
ualarm 200_000; ## time out after 0.2 seconds
POSIX::read($fd, $buf, 1);
if ( $buf and $stopped ) {
print time,"--Mouse is moving--\n";
$stopped = 0; ### turn off output
}
ualarm 0;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|