public class RotaryEncoder
{
private InterruptPort PortA;
private InterruptPort PortB;
private uint prevA = 0;
private uint prevB = 0;
private uint prevPort = 0;
public int Position{get; private set;}
public RotaryEncoder(Cpu.Pin pinA, Cpu.Pin pinB)
{
PortA = new InterruptPort(
pinA,
false,
Port.ResistorMode.PullUp,
Port.InterruptMode.InterruptEdgeBoth);
PortB = new InterruptPort(
pinB,
false,
Port.ResistorMode.PullUp,
Port.InterruptMode.InterruptEdgeBoth);
PortA.OnInterrupt += OnInterrupt;
PortB.OnInterrupt += OnInterrupt;
}
void OnInterrupt(uint port, uint state, DateTime time)
{
if (port == prevPort)
return;
prevPort = port;
if (((uint)PortA.Id) == port){
if (state > 0 && prevB > 0)
--Position;
prevA = state;
}
else{
if (prevA == 0 && state == 0)
++Position;
prevB = state;
}
}
}
No comments:
Post a Comment