I am having this problem with the code in the screenshot where it will enter the if statement with the condition counter>temp, but even then what is printed to the serial is:
i
1
0
0
0
So it is acknowledging that counter and temp are equal while it's in the if statement that shouldn't be running if that is the case. I can even add Serial.println(counter>temp) and it will print 0 as well after it just, presumably, determined that was true. I assume I'm missing something obvious, but it's beyond me
int temp = 0;
int counter = 0; //This variable will increase or decrease depending on the rotation of encoder
int counter2 = 0;
void setup() {
Serial.begin (9600);
pinMode(2, INPUT); // internal pullup input pin (D2)
pinMode(3, INPUT); // internal pullup input pin (D3)
//Setting up interrupt
//A rising pulse from encodenren activated ai0()
attachInterrupt(digitalPinToInterrupt(2), ai0, RISING);
//B rising pulse from encodenren activated ai1()
attachInterrupt(digitalPinToInterrupt(3), ai1, RISING);
}
void loop() {
// Send the value of counter
if(counter>temp){
Serial.println ("i");
Serial.println(counter == temp);
Serial.println (counter);
Serial.println(temp);
Serial.println(counter>temp);
temp = counter;
}
//delay(1000);
}
void ai0() {
// ai0 is activated if DigitalPin D2 is going from LOW to HIGH
// Check pin 2 to determine the direction
//Serial.println(2);
if(digitalRead(2)==LOW) {
counter++;
}else{
counter--;
}
}
void ai1() {
// ai0 is activated if DigitalPin D3 is going from LOW to HIGH
// Check with pin 3 to determine the direction
if(digitalRead(3)==LOW) {
counter--;
}else{
counter++;
}
}
I might be wrong, but these inputs declared this way do NOT have pullups, hence are noise-responsive.
Combine that with making them interrupts, and counter has a high probability of having a non-zero value by the time the if clause comes along. With nothing declared volatile, I think it's an unsolvable riddle, really, but others may differ.
Yeah, I switched them with external pullups and didn't change the comments while debugging. Switching to volatile declarations doesn't remedy the situation alone, but changing the pins to internal pullups does seem to make it stop