views:

79

answers:

3

In a program (Java) I'm making I need to check for a specific pin in the parallel port. Whenever that pin goes from logical 0 to 1 (a positive edge clock) I have to read the data on the port and save it. This happens about every 10ms but can vary a little.

To do this I made a separate thread with a while loop that is constantly checking the port, but this makes the processor go nuts and I know it's because of the while loop. My question is, how can I constantly scan the port without using a processor intensive while loop? The program doesn't know precisely when a pin change will happen, only that it happens around every 10ms.

Thanks!

+1  A: 

It is really tricky to catch hardware interrupts when your code is not running as a part of operating system. What you can do is to put Thread.Sleep ( 5 ). This will sleep for 10 milliseconds, and will let the other threads run or just keep CPU idle and cool. Having 5 ms delay should be enough to ensure won't miss any clock ticks.

This would work when your clock is alternating between 10 ms high and 10 ms low. For other patterns you have to adjust the parameter accordingly.

Vlad
+6  A: 

Fire a thread which is scheduled to execute the given Runnable at a fixed rate. You can use Timer#scheduleAtFixedRate() or ScheduledExecutorService#scheduleAtFixedRate() for this. The last one is preferred.

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new PortScanner(), 0, 10, TimeUnit.MILLISECONDS); // Run every 10 ms.

Where PortScanner can look like this:

public class PortScanner implements Runnable {
    @Override
    public void run() {
        // Scan port here.
    }
}

Don't forget to call scheduler.shutdown() at the moment your application exits, else the thread may hang.

BalusC
+3  A: 

There might be a better solution, but worst case you could just Thread.sleep for 1-2ms every iteration of the while loop.

Cory Petosky
Show me one OS where the thread won't sleep for at least 10ms when called with Thread.sleep(2).
Daniel
Win/Linux did fine, last time I measured 'em, and a quick Google search seems to support that. But I haven't used Java since college and it's possible the granularity has worsened over time.
Cory Petosky