Skip to content

Instantly share code, notes, and snippets.

@devdsp
Created November 3, 2019 09:44
Show Gist options
  • Save devdsp/2cfb5e49dd1cf7c9487f5fb063663d17 to your computer and use it in GitHub Desktop.
Save devdsp/2cfb5e49dd1cf7c9487f5fb063663d17 to your computer and use it in GitHub Desktop.
#define ENC_MASK B10000100
#define ENC_STATE0 B00000000
#define ENC_STATE1 B10000000
#define ENC_STATE2 B10000100
#define ENC_STATE3 B00000100
const byte PIN_ENC_A = 2;
const byte PIN_ENC_B = 7;
const byte PIN_ENC_P = 8;
const byte PIN_VOLT = 9;
const byte PIN_LED_R = 3;
const byte PIN_LED_G = 5;
const byte PIN_LED_B = 6;
byte enc_state;
int encoder_cnt = 0;
int encoder_lst = 0;
void setup() {
Serial.begin(57600);
pinMode(PIN_ENC_A, INPUT_PULLUP);
pinMode(PIN_ENC_B, INPUT_PULLUP);
pinMode(PIN_ENC_P, INPUT_PULLUP);
pinMode(PIN_VOLT,OUTPUT);
pinMode(PIN_LED_R,OUTPUT);
pinMode(PIN_LED_G,OUTPUT);
pinMode(PIN_LED_B,OUTPUT);
enc_state = PIND & ENC_MASK;
}
void loop() {
if(
(enc_state == ENC_STATE0 && (PIND & ENC_MASK) == ENC_STATE1) ||
(enc_state == ENC_STATE1 && (PIND & ENC_MASK) == ENC_STATE2) ||
(enc_state == ENC_STATE2 && (PIND & ENC_MASK) == ENC_STATE3) ||
(enc_state == ENC_STATE3 && (PIND & ENC_MASK) == ENC_STATE0)
) {
encoder_cnt = constrain(encoder_cnt+1,24,255);
enc_state = PIND & ENC_MASK;
} else if(
(enc_state == ENC_STATE0 && (PIND & ENC_MASK) == ENC_STATE3) ||
(enc_state == ENC_STATE1 && (PIND & ENC_MASK) == ENC_STATE0) ||
(enc_state == ENC_STATE2 && (PIND & ENC_MASK) == ENC_STATE1) ||
(enc_state == ENC_STATE3 && (PIND & ENC_MASK) == ENC_STATE2)
) {
encoder_cnt = constrain(encoder_cnt-1,24,255);
enc_state = PIND & ENC_MASK;
}
if(encoder_lst != encoder_cnt) {
Serial.println(encoder_cnt);
encoder_lst = encoder_cnt;
analogWrite(PIN_VOLT,encoder_cnt);
}
if(!digitalRead(PIN_ENC_P) && encoder_cnt) {
encoder_cnt=0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment