Smart Pin Quadrature Encoder Demo
JonnyMac
Posts: 9,104
Turns out that using the smart pin quadrature encoder mode is as easy as it seems -- still, it's better to put up real code than to simply talk about it, so here we go.
Interestingly, I tested this across the pin 31-32 boundary and it worked.
Things that I used to do in my P1 encoder cog (preset value, range limiting) turned out easy to handle with simple variables. The object also accounts for those detented encoders that return 4 counts per click (I'm testing with one).
Here's the setup code for the object:
Edit: Improved button() method and updated files for PNut v34n.
Interestingly, I tested this across the pin 31-32 boundary and it worked.
Things that I used to do in my P1 encoder cog (preset value, range limiting) turned out easy to handle with simple variables. The object also accounts for those detented encoders that return 4 counts per click (I'm testing with one).
Here's the setup code for the object:
pub start(a, b, btn, d4x, preset, lo, hi) : result | dif '' Start the encoder object '' -- continuous count mode '' -- a & b are encoder inputs (active-low) '' -- btn is the button input (active-low, -1 if not used) '' -- set d4x to true if each "click" is 4 counts '' -- preset is initial value for encoder '' -- lo & hi are limit values for encoder dif := b - a if ((dif == 0) or (dif < -3) or (dif > 3)) result := false else apin := a ' save pins & limits longmove(@btnpin, @btn, 5) mod4x := (d4x) ? 2 : 0 ' fix detent modifier pinstart(apin, SP_ENC | dif.[2..0] << 24, 0, 0) ' start a/b quadrature mode set(preset) ' preset encoder value result := trueThis is the code that returns the encoder value -- handles the 4x detent issue, preset value, and range limiting.
pub value() : result '' Return encoder value result := (rdpin(apin) sar mod4x) + offset if (result < lolimit) ' limit range result := set(lolimit) elseif (result > hilimit) result := set(hilimit)
Edit: Improved button() method and updated files for PNut v34n.
Comments
This such an important feature but has been given no priority which I find to be ridiculous when there is so much emphasis on "ROBOTICS" here.
Instead it's all about graphics which will never compete with the Pi. Go figure.
Be happy that there's quadrature hardware in every smartpin. It's just a RDPIN away.