0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

5pin のロータリーエンコーダ

Posted at
  • 概要
    格安(Amazonで¥200くらい)の、5ピンのプッシュスイッチ付きロータリーエンコーダについてのメモ。

    • ボード実装

      • 3ピン側
        ロータリーエンコーダとして扱う。
        ピン配置は真ん中をGNDに、左右をA,Bに接続する。

      • 2ピン側
        プッシュスイッチとして扱う。
        5vとGNDはどちらでもよい。

    • Arduino Leonardo

ロータリーエンコーダは割り込み、プッシュスイッチは周期的にチェックする。
Arduino Leonardoの割り込みは、0, 1, 2, 3, 7のピンのみが可能。

#define PIN_ROTARY_A 3
#define PIN_ROTARY_B 7
#define PIN_PUSH 15
static const int rotaryPtn[] = {0, 1, -1, 0, -1, 0, 0, 1, 1, 0, 0, -1, 0, -1, 1, 0, 0};

bool prevRotaryA = false;
bool prevRotaryB = false;
int count = 0;
char prbuf[50];

void setup() {
  pinMode(PIN_PUSH, INPUT);

  pinMode(PIN_ROTARY_A, INPUT_PULLUP);
  pinMode(PIN_ROTARY_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_ROTARY_A), count_rotary, CHANGE);
  attachInterrupt(digitalPinToInterrupt(PIN_ROTARY_B), count_rotary, CHANGE);

  Serial.begin(9600);
}

void loop() {
  sprintf(prbuf, "count:%d, push:%d", count, is_push());
  Serial.println(prbuf);
  delay(10);
}

void count_rotary() {
  bool rotaryA, rotaryB;
  int ptn;
  rotaryA = digitalRead(PIN_ROTARY_A);
  rotaryB = digitalRead(PIN_ROTARY_B);
  
  ptn = 0x0f & (prevRotaryA << 3 | prevRotaryB << 2 | rotaryA << 1 | rotaryB);

  switch(rotaryPtn[ptn]){
    case -1:
      count++;
      break;
    case 1:
      count--;
      break;
    default:
      break;
  }

  prevRotaryA = rotaryA;
  prevRotaryB = rotaryB;
}

bool is_push(){
  return !digitalRead(PIN_PUSH);
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?