Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Pins
- int encoderPin1 = 2;
- int encoderPin2 = 3;
- int encoderSwitchPin = 4; //push button switch
- // Encoder Magic
- volatile int lastEncoded = 0;
- volatile long encoderValue = 0;
- long lastencoderValue = 0;
- long last =0;
- int val=0;
- int oldval=0;
- int lastMSB = 0;
- int lastLSB = 0;
- // Debounce Stuff for the push button
- long btn_debounce_start = 0;
- int btn_debounce_duration = 500;
- void setup() {
- pinMode(encoderPin1, INPUT);
- pinMode(encoderPin2, INPUT);
- pinMode(encoderSwitchPin, INPUT);
- digitalWrite(encoderPin1, HIGH); //turn pullup resistor on
- digitalWrite(encoderPin2, HIGH); //turn pullup resistor on
- digitalWrite(encoderSwitchPin, HIGH); //turn pullup resistor on
- Serial.begin(9600);
- }
- void loop(void) {
- if(encoderBtnOK()){
- // this is when the button is pressed
- }
- if(encoderBtnUp()){
- // this when you turn the encoder to one side
- }
- if(encoderBtnDown()){
- // this when you turn the encoder to another side
- }
- // Stuff for the other stuff to work :)
- updateEncoder();
- encoderWatchdog();
- }
- void updateEncoder(){
- int MSB = digitalRead(encoderPin1); //MSB = most significant bit
- int LSB = digitalRead(encoderPin2); //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
- }
- void encoderWatchdog(){
- //Serial.println(encoderValue);
- if(last != encoderValue){
- if(encoderValue == last+4){
- encoderUp = true;
- last=encoderValue;
- }
- if(encoderValue == last-4){
- encoderDown = true;
- last=encoderValue;
- }
- }
- }
- boolean encoderBtnOK(){
- if(digitalRead(encoderSwitchPin)){
- if(millis() - btn_debounce_start > btn_debounce_duration){
- btn_debounce_start = millis();
- return true;
- }
- }
- return false;
- }
- boolean encoderBtnUp(){
- if(encoderUp == true){
- encoderUp = false;
- return true;
- }
- return false;
- }
- boolean encoderBtnDown(){
- if(encoderDown == true){
- encoderDown = false;
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement