those switches have two pins out: A and B. and their states change depending on the rotation.
so you can look up a table, based on the previous states of A+B and the current states of A+B -> state machine.
when you rotate the switch, A goes 0, 1, 1, 0; and B goes 0, 0, 1, 1;
so if AB is 10 (the 2nd position), and AB was 11 (the 3rd position), you know the switch has moved counterclockwise.
here is the code.
===========code==================
//determine increment / decrement of the encoder
unsigned char encoder_read(PORT_TYPE port, PORT_TYPE pin_a, PORT_TYPE pin_b) {
const signed char ABs_states[]={0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
static unsigned char encoder_output=0x00;
static unsigned char ABs=0x00; //AB key read out, Previous in the high 2 bits and current in the low two bits;
unsigned char tmp;
ABs <<=2; //left 2 bits now contain the previous AB key read-out;
tmp=IO_GET(port, pin_a | pin_b); //read ab pins
if (tmp & pin_a) ABs |= 0x02; //set the 1st bit if A is high now;
if (tmp & pin_b) ABs |= 0x01; //set the 0th bit if B is high;
ABs &= 0x0f; //only retain ABs' last 4 bits (A_previous, B_previous, A_current, B_current)
encoder_output += ABs_states[ABs];
return encoder_output; //return the absolute value
//return ABs_states[ABs]; //return the relative value (+1 = clockwise, 0, -1 = counterclockwise)
}
========end code============
depending on which "return" statement you use, you can either get the absolute value or the relative value of the switches.
so you can look up a table, based on the previous states of A+B and the current states of A+B -> state machine.
when you rotate the switch, A goes 0, 1, 1, 0; and B goes 0, 0, 1, 1;
so if AB is 10 (the 2nd position), and AB was 11 (the 3rd position), you know the switch has moved counterclockwise.
here is the code.
===========code==================
//determine increment / decrement of the encoder
unsigned char encoder_read(PORT_TYPE port, PORT_TYPE pin_a, PORT_TYPE pin_b) {
const signed char ABs_states[]={0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
static unsigned char encoder_output=0x00;
static unsigned char ABs=0x00; //AB key read out, Previous in the high 2 bits and current in the low two bits;
unsigned char tmp;
ABs <<=2; //left 2 bits now contain the previous AB key read-out;
tmp=IO_GET(port, pin_a | pin_b); //read ab pins
if (tmp & pin_a) ABs |= 0x02; //set the 1st bit if A is high now;
if (tmp & pin_b) ABs |= 0x01; //set the 0th bit if B is high;
ABs &= 0x0f; //only retain ABs' last 4 bits (A_previous, B_previous, A_current, B_current)
encoder_output += ABs_states[ABs];
return encoder_output; //return the absolute value
//return ABs_states[ABs]; //return the relative value (+1 = clockwise, 0, -1 = counterclockwise)
}
========end code============
depending on which "return" statement you use, you can either get the absolute value or the relative value of the switches.
一周热门 更多>