Hello have been playing around with encoder and 20-04 i2c fed LCD trying to get both to work I am almost there have read a lot of old posts on the subject with my small amount of learning that i have ( best way to learn is put it together)
the problem i cannot see is the encoder counts OK counter clockwise but clockwise it shows only 0-1-0 and so on
i think the problem lies with incrementing decrementing the count ?? I think, could someone take a look please and enlighten me thanks
#include <LiquidCrystal_I2C.h>
// LCD defaults
#define I2C_ADDR 0x27 // Define I2C Address where the PCF8574A is
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);
const int PinCLK = 2; // Used for generating interrupts using CLK signal
const int PinDT = 3; // Used for reading DT signal
const int PinSW = 4; // Used for the push button switch
const int PinLED = 13;
int SW;
int oldSW;
volatile boolean encChanged;
volatile long encPosition = 0;
volatile boolean up;
void isr() { // Interrupt service routine is executed when a HIGH to LOW transition is detected on CLK
volatile boolean CLK = digitalRead(PinCLK);
volatile boolean DT = digitalRead(PinDT);
up = ((!CLK && DT) || (CLK && !DT));
if (!up)
encPosition++;
else
encPosition--;
if (encPosition < 0) encPosition = 0;
encChanged = true;
delay(10);
}
void setup() {
pinMode(PinCLK, INPUT);
pinMode(PinDT, INPUT);
pinMode(PinSW, INPUT_PULLUP);
pinMode(PinLED, OUTPUT);
SW = HIGH;
oldSW = HIGH;
attachInterrupt(0, isr, FALLING); // interrupt 0 is always connected to pin 2 on Arduino UNO
Serial.begin(9600);
Serial.println("Start");
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
lcd.setBacklight(HIGH);
lcd.begin(20,4); // Cuzz we have a 20x4 display
lcd.clear(); // Get rid of any garbage that might appear on startup
lcd.print("KY040 encoder test ");
lcd.setCursor(0,1);
lcd.print("Rotated");
}
void loop() {
SW = digitalRead(PinSW);
if ( SW == LOW && oldSW == HIGH) { // check if pushbutton is pressed
encPosition = 0; // if YES, then reset counter to ZERO
Serial.print("Reset");
encChanged = true;
}
oldSW = SW;
if (encChanged) { // do this only if rotation was detected
encChanged = false; // do NOT repeat IF loop until new rotation detected
Serial.print("Count = ");
Serial.println(encPosition);
analogWrite(PinLED, encPosition);
lcd.setCursor(12,1);
lcd.print(encPosition);
}
}