Hi,
I'm working on a project that uses a rotary encoder as input. I'm planning on using it later to interface to a menu.
For now, I'm just getting it to count up and down and detect when the button is pressed. I'm using hardware debouncing on the encoder based on this VIDEO
Sometimes when I reset the arduino and rotate the encoder clockwise (which should have the effect of increasing the value being printed to the lcd) the first value is -1, or it does not change from 0.
It seems all subsequent encoder movements read correctly, its just the first reading that's the problem.
Here is my code:
#define BUTTON_PIN 7
#include <LiquidCrystal.h>
int pulses, A_SIG = 0, B_SIG = 1;
int value = 0, lastPulses = 0;
boolean pulseChange = false;
boolean buttonState = false;
boolean lastButtonState = false;
LiquidCrystal lcd(8, 13, 9, 10, 11, 12);
void setup() {
attachInterrupt(0, A_RISE, RISING);
attachInterrupt(1, B_RISE, RISING);
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT);
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
delay(1000);
lcd.clear();
}//setup
void loop() {
lcd.setCursor(0, 0);
if (pulseChange == true) {
pulseChange = false; // if clockwise, increment counter
if (pulses > lastPulses) {
value++;
}
else if (pulses < lastPulses) { // if counterclockwise, decrement counter
value--;
}
lcd.print("Value = ");
lcd.print(value);
lastPulses = pulses; // save this for next time around
}
buttonState = digitalRead(BUTTON_PIN);
if (buttonState != lastButtonState)
Serial.println(buttonState);
lcd.setCursor(0, 0);
lcd.print("Encoder = ");
lcd.print(value);
lcd.setCursor(0, 1);
lcd.print("Button : ");
lcd.print(buttonState);
lastButtonState = buttonState;
}
void A_RISE() {
detachInterrupt(0);
A_SIG = 1;
if (B_SIG == 0)
pulses++;//moving forward
pulseChange = true;
if (B_SIG == 1)
pulses--;//moving reverse
pulseChange = true;
//Serial.println(pulses);
attachInterrupt(0, A_FALL, FALLING);
}
void A_FALL() {
detachInterrupt(0);
A_SIG = 0;
if (B_SIG == 1)
pulses++;//moving forward
if (B_SIG == 0)
pulses--;//moving reverse
//Serial.println(pulses);
attachInterrupt(0, A_RISE, RISING);
}
void B_RISE() {
detachInterrupt(1);
B_SIG = 1;
if (A_SIG == 1)
pulses++;//moving forward
if (A_SIG == 0)
pulses--;//moving reverse
//Serial.println(pulses);
attachInterrupt(1, B_FALL, FALLING);
}
void B_FALL() {
detachInterrupt(1);
B_SIG = 0;
if (A_SIG == 0)
pulses++;//moving forward
if (A_SIG == 1)
pulses--;//moving reverse
//Serial.println(pulses);
attachInterrupt(1, B_RISE, RISING);
}