Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
for using rotary encoder on Arduino without library
#define ROT_PIN_A 2
#define ROT_PIN_B 3
uint8_t prev;
int16_t counter;
void funcInterruptA()
{
Serial.print("A : ");
funcInterrupt();
}
void funcInterruptB()
{
Serial.print("B : ");
funcInterrupt();
}
int8_t checkStateRotaryEncoder(uint8_t status)
{
int8_t result=0;
static const uint8_t positive_array[4]={0b0010,0b1011,0b1101,0b0100};
static const uint8_t negative_array[4]={0b0001,0b0111,0b1110,0b1000};
for(int8_t i=0;i<4;i+=1)
{
if(status==positive_array[i])
{
result=1;
break;
}
if(status==negative_array[i])
{
result=-1;
break;
}
}
return result;
}
void funcInterrupt()
{
uint8_t current=0;
uint8_t ca=(digitalRead(ROT_PIN_A));
uint8_t cb=(digitalRead(ROT_PIN_B));
current+=ca<<1;
current+=cb;
if(prev==current)
{
Serial.println();
return;
}
current+=prev<<2;
counter+=checkStateRotaryEncoder(current);
Serial.println(counter);
// current+=1<<4; //ゼロ埋めさせるためのダミー
// Serial.println(current,BIN);
prev=(ca<<1)+cb;
}
void setup() {
Serial.begin(9600);
pinMode(ROT_PIN_A,INPUT);
pinMode(ROT_PIN_B,INPUT);
attachInterrupt(digitalPinToInterrupt(ROT_PIN_A),funcInterruptA,CHANGE);
attachInterrupt(digitalPinToInterrupt(ROT_PIN_B),funcInterruptB,CHANGE);
prev=0;
counter=0;
Serial.println("START");
}
void loop() {
delay(1000*1000*1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.