Counter support

20 views
Skip to first unread message

David Albert

unread,
Dec 7, 2016, 9:18:52 AM12/7/16
to Pi4J
It's common for embedded systems to need to count pulses, for example when monitoring the speed of a motor using an optical encoder.  Ideally the hardware supports this with an embedded counter/timer, but unfortunately the raspberry pi doesn't offer this.  Using a Java listener on a gpio won't work because each pulse will place an event on the Java event queue which will overwhelm the system (a motor spinning at 1000rpm with a 100 tooth encoder will generate 100K events/second).  Without a hardware counter, what's needed (at a minimum) is a class whose objects maintain a count, increment the count in a C ISR in response to a GPIO edge-triggered interrupt, and makes the count available in java.

Is there existing support for a counter class in Pi4J that I missed?

If not, how hard would it be to add?  There is a tutorial for event-driven counting in WiringPi: http://cs.smith.edu/dftwiki/index.php/Tutorial:_Interrupt-Driven_Event-Counter_on_the_Raspberry_Pi

Another great class would be a pulse width input class that measures the time between the rising and falling edge on a GPIO.  This would make interfaces to things like Ultrasonic rangefinders more accurate and much less CPU intensive.

I'm new to Pi4J and any suggestions for how to find or implement this sort of functionality would be much appreciated.  Thanks!
Message has been deleted

David Albert

unread,
Dec 7, 2016, 9:22:35 AM12/7/16
to Pi4J
Oops, bad math: that example should have said 1.67K events/second

Robert Savage

unread,
Dec 9, 2016, 8:29:31 PM12/9/16
to Pi4J
Hi David,

No, there is no counter impl currently in Pi4J. 

I looked at the article that you suggested using WiringPi and that does not look too difficult to implement, but it is a user space ISR and I'm not sure if it will perform fast enough.
A better option (completely outside of Pi4J) might be to create a kernel module that has a kernel ISR and keeps track of the counter and exposes it through sys interface to the user space program.  

This article might be a good place to start:

Thanks, Robert
Reply all
Reply to author
Forward
0 new messages