Skip to content

Instantly share code, notes, and snippets.

@shanecandoit
Created September 4, 2019 13:32
Show Gist options
  • Save shanecandoit/5bc41f84d31992712157dacf8036f694 to your computer and use it in GitHub Desktop.
Save shanecandoit/5bc41f84d31992712157dacf8036f694 to your computer and use it in GitHub Desktop.
int potPin = A5; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int val = 0; // variable to store the value coming from the sensor
// from https://bildr.org/2012/08/rotary-encoder-arduino/
int orange = 4;
int green = 2;
volatile int lastEncoded = 0;
volatile long encoderValue = 0;
long lastencoderValue = 0;
int lastMSB = 0;
int lastLSB = 0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT
pinMode(orange, INPUT);
pinMode(green, INPUT);
digitalWrite(orange, HIGH); //turn pullup resistor on
digitalWrite(green, HIGH); //turn pullup resistor on
//call updateEncoder() when any high/low changed seen
//on interrupt 0 (pin 2), or interrupt 1 (pin 3)
attachInterrupt(0, updateEncoder, CHANGE);
attachInterrupt(1, updateEncoder, CHANGE);
}
void loop() {
//val = analogRead(potPin); // read the value from the sensor
Serial.println(encoderValue);
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(500); // stop the program for some time
digitalWrite(ledPin, LOW); // turn the ledPin off
delay(500); // stop the program for some time
}
void updateEncoder(){
int MSB = digitalRead(orange); //MSB = most significant bit
int LSB = digitalRead(green); //LSB = least significant bit
int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; //adding it to the previous encoded value
if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011)
encoderValue ++;
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000)
encoderValue --;
lastEncoded = encoded; //store this value for next time
//
Serial.println(encoderValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment