//https://docs.wokwi.com/parts/wokwi-ky-040 참고
#define L_LED 13
#define ENCODER_A 2
#define ENCODER_B 3
#define SW 4
int lastStateA;
int lastStateSW;
int cnt = 0;
volatile int flag = LOW;
volatile int dir = LOW; //LOW == 시계방향, HIGH == 반시계방향
void setup() {
pinMode(L_LED, OUTPUT);
pinMode(ENCODER_A, INPUT);
pinMode(ENCODER_B, INPUT);
pinMode(SW, INPUT_PULLUP); //저항을 달거나 INPUT_PULLUP을 사용한다
attachInterrupt(digitalPinToInterrupt(ENCODER_A), cntEncoder, CHANGE);
lastStateA = digitalRead(ENCODER_A);
lastStateSW = digitalRead(SW);
Serial.begin(9600);
}
void cntEncoder()
{
int StateA = digitalRead(ENCODER_A);
int StateB = digitalRead(ENCODER_B);
if (StateA == LOW && StateB == HIGH) {
cnt++;
//Serial.println("Rotated clockwise ⏩");
//Serial.println(cnt);
dir = LOW;
}
if (StateA == LOW && StateB == LOW) {
cnt--;
//Serial.println("Rotated counterclockwise ⏪");
//Serial.println(cnt);
dir = HIGH;
}
flag = HIGH;
//lastStateA = StateA;
}
void loop() {
//----------------------------------
/*
int StateA = digitalRead(ENCODER_A);
if (StateA != lastStateA) { //엔코더A의 상태가 변하면
int StateB = digitalRead(ENCODER_B);
if (StateA == LOW && StateB == HIGH) {
cnt++;
Serial.println("Rotated clockwise ⏩");
Serial.println(cnt);
}
if (StateA == LOW && StateB == LOW) {
cnt--;
Serial.println("Rotated counterclockwise ⏪");
Serial.println(cnt);
}
lastStateA = StateA;
}
*/
//----------------------------------
if(flag)
{
if(dir)
{
//반시계방향
Serial.println("Rotated counterclockwise ⏪");
Serial.println(cnt);
}
else
{
//시계방향
Serial.println("Rotated clockwise ⏩");
Serial.println(cnt);
}
flag = LOW;
}
//----------------------------------
int sw_state = digitalRead(SW);
if(lastStateSW != sw_state)
{
if(sw_state == LOW) //스위치 누르면, https://docs.wokwi.com/parts/wokwi-ky-040 참고
{
cnt = 0;
Serial.println("cnt Reset " + cnt);
}
lastStateSW = sw_state;
}
}