Last active
August 29, 2015 14:11
-
-
Save houmei/6524d5254652c7460a6e to your computer and use it in GitHub Desktop.
ロータリーエンコーダテスト 割り込みを使う場合
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// original: | |
// http://www.ct-robo.sakura.ne.jp/371 | |
// https://sites.google.com/site/wasurenaiweb/arduino/rotaryencoder | |
// | |
// ロータリーエンコーダーの配線に合わせる | |
int dRotAPin = 2; // intterupt pin | |
int dRotBPin = 3; | |
int R_count = 0; | |
// ロータリーエンコーダーの状態を記憶する | |
// 割り込み中に変化する変数はvolatileをつけて宣言する | |
volatile int m_nOldRot = 0; | |
volatile int m_nValue = 0; | |
void setup() | |
{ | |
// ピンの設定 | |
// INPUTモードにします。 | |
pinMode(dRotAPin, INPUT_PULLUP); | |
pinMode(dRotBPin, INPUT_PULLUP); | |
// 外部割り込みを設定します | |
// D2ピンが 変化 した時にrotRotEnd()を呼び出します | |
// attachInterrupt(0, rotRotEnc, CHANGE); // for UNO | |
attachInterrupt(1, rotRotEnc, CHANGE); // for 32U4 | |
//シリアル通信速度を設定します | |
Serial.begin(9600); | |
} | |
void loop() | |
{ | |
int t; | |
//シリアルモニターに角度を表示させる | |
t=R_count; | |
if(m_nValue != 0){ | |
R_count = R_count + m_nValue; | |
m_nValue = 0; | |
} | |
if (t!=R_count) Serial.println(R_count); | |
delay(100); | |
} | |
// 外部割り込みから呼び出される変数 | |
void rotRotEnc(void) | |
{ | |
int aPin,bPin; | |
aPin=digitalRead(dRotAPin); | |
bPin=digitalRead(dRotBPin); | |
if(!aPin){ // ロータリーエンコーダー回転開始 | |
m_nOldRot = bPin?1:-1; // inc(CW):dec(CCW) | |
} else { // ロータリーエンコーダー回転停止 | |
// if (bPin) m_nValue=m_nValue+m_nOldRot; // CW not worked | |
if(bPin){ | |
if(m_nOldRot == -1){ | |
// 左回転の時の処理 | |
m_nValue--; | |
} | |
} else { | |
if(m_nOldRot == 1){ | |
//右回転の時の処理 | |
m_nValue++; | |
} | |
} | |
// ここでロータリーエンコーダーの状態をクリア | |
m_nOldRot = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment