1

I have a rotary encoder and 2 buttons to a. Store the encoder value b. Reset the encoder value to 0. The reset buttons work fine the issue is with the set/store button. Where the value changes without pressing the button as well. Any help is appreciated.

int encoderPin1 = 2;
int encoderPin2 = 3;

volatile int lastEncoded = 0; 
volatile double encoderValue = 0;
long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

// buttons
int resetPin = 43;
int settPin = 22; 
int val = 0;
int val2 = 0;

//reset-set
double setValue = 0.0;
double resetValue = 0.0;

void setup() { 
  Serial.begin (9600);
  
  pinMode(encoderPin1, INPUT);
  pinMode(encoderPin2, INPUT);
  
  digitalWrite(encoderPin1, HIGH); 
  digitalWrite(encoderPin2, HIGH); 

  attachInterrupt(0, updateEncoder, CHANGE); 
  attachInterrupt(1, updateEncoder, CHANGE);

  //buttons
  pinMode(resetPin, INPUT);
  pinMode(settPin, INPUT);

  pinMode(LED_BUILTIN, OUTPUT);

}
void loop(){
  //Serial.println(encoderValue); //print
  delay(1000); 

  //
val = digitalRead(settPin);
if (val == HIGH){
  set();
  digitalWrite(LED_BUILTIN, HIGH);
}

/*val2 = digitalRead(resetPin);
if (val2 == HIGH){
  //reset
  encoderValue = resetValue;
  Serial.println(encoderValue);
  Serial.print("reset");
  delay(100);
}*/

}

void set(){
  //set the value
  setValue = encoderValue;
  Serial.println(setValue);
  Serial.print("setValue");
  delay(100);
}

 void updateEncoder(){
  int MSB = digitalRead(encoderPin1);
  int LSB = digitalRead(encoderPin2);
  
  int encoded = (MSB << 1) |LSB;
  int sum = (lastEncoded << 2) | encoded;
  
  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;
  
  lastEncoded = encoded;
  }
3
  • what is the problem with your code? ... are you getting errors? Commented Sep 17, 2020 at 14:08
  • Do you use external pulldown resistors? Commented Sep 17, 2020 at 14:16
  • the encoder does not require an interrupt on both signal pins ... enable an interrupt on raising (or falling) on one signal pin ... the state of the other pin at the time of the interrupt signifies the direction of rotation Commented Sep 17, 2020 at 21:13

1 Answer 1

1

thank you for your suggestion. The issue isn't with the code but was with the button. I changed the button and it worked fine. Thanks for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.