#include <LiquidCrystal.h>
#include <LcdProgressBar.h>
#define LCD_RS 12
#define LCD_EN 11
#define LCD_D4 10
#define LCD_D5 9
#define LCD_D6 8
#define LCD_D7 7
int currentStateCLK;
int lastStateCLK;
int sensitivity;
int btnPin=6; //GPIO #3-Push button on encoder
int DT=5; //GPIO #4-DT on encoder (Output B)
int CLK=4; //GPIO #5-CLK on encoder (Output A)
byte  lcdNumCols = 16; // -- number of columns in the LCD
LiquidCrystal lcd = LiquidCrystal(LCD_RS, LCD_EN, LCD_D4, LCD_D5, LCD_D6, LCD_D7);
LcdProgressBar lpg(&lcd, 1, lcdNumCols);


void setup() {
  //-- Only useful for debugging purpose
  Serial.begin(9600);
  pinMode(CLK,INPUT_PULLUP);
  pinMode(DT,INPUT_PULLUP);
  //-- initializing the LCD
  lcd.begin(2, lcdNumCols);
  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print("Sensitivity");
      
  delay(100);

  //-- initializing the progress bar
  initLpg();
}

void readRotar(){
	// Read the current state of CLK
	currentStateCLK = digitalRead(CLK);

	// If last and current state of CLK are different, then pulse occurred
	// React to only 1 state change to avoid double count
	if (currentStateCLK != lastStateCLK  && currentStateCLK == 1){
		// If the DT state is different than the CLK state then
		// the encoder is rotating CCW so decrement
		if (digitalRead(DT) != currentStateCLK) {
			//move right
      sensitivity+=1;
      Serial.println("right");
      Serial.println(sensitivity);
        
		} else {
			//move left
      Serial.println("left");
      Serial.println(sensitivity);
			sensitivity-=1;
		}
	}

	// Remember last CLK state
	lastStateCLK = currentStateCLK;

	// Read the button state
}

//-- initializing  the progress bar
void initLpg()
{
  //-- Set min and max values
  lpg.setMinValue(0);
  lpg.setMaxValue(10);
  //-- Draw it: the frame
  lpg.draw(0);
  sensitivity = 1;
}

void loop() {
  //-- draw progress bar
  lpg.draw(sensitivity);
  if (sensitivity >= 11) {
    //---  Duration's over: delay and start again!
    initLpg();
  }
  readRotar();
}