/* ----------------------------------------------------------
* Encoder_Demo.ino
* How to use Rotary Encoder KY-040 in Arduino
* to set a counter value. The incremental value
* can be changed by pressing the encoder button
* with the change value in units, tens, hundreds and thousands
*
* By : Rilles Eko Prianto
* ----------------------------------------------------------
*/
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
int pinA = 2;
int pinB = 4;
int pinBtn = 3;
int bzr(8);
volatile int counter = 0;
volatile byte sA, sB = 0;
volatile byte fired = 0;
volatile byte tekan = 0;
byte step = 0;
void setup() {
pinMode(pinA, INPUT);
pinMode(pinB, INPUT);
pinMode(pinBtn, INPUT_PULLUP);
pinMode(bzr, OUTPUT);
digitalWrite(bzr,0);
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(pinA), hitung, CHANGE);
attachInterrupt(digitalPinToInterrupt(pinBtn), tombol, RISING);
sA = digitalRead(pinA);
// Serial.println("Arduino ready....");
lcd.init();
// turn on the backlight
lcd.backlight();
lcd.setCursor(0,0);
lcd.print(" HELLO, WELCOME");
lcd.setCursor(0,1);
lcd.print(" TO ARDUINO");
delay(1000);
lcd.clear();
// 0123456789012345
lcd.print("CNT: ");
lcd.print(counter);
}
void loop() {
if (fired) {
// Serial.println(counter);
lcd.setCursor(5,0);
lcd.print(" ");
lcd.setCursor(5,0);
lcd.print(counter);
fired = 0;
}
if (tekan){
step++;
bell();
if (step>3) step = 0;
delay(50);
tekan = 0;
}
}
void tombol(){
tekan = 1;
}
void hitung(){
// detachInterrupt(digitalPinToInterrupt(pinA));
byte stateA = digitalRead(pinA);
byte stateB = digitalRead(pinB);
if (stateA != sA && stateA==LOW){
fired = 1;
switch (step) {
case 0:
if (stateA != stateB) counter++; else counter--;
break;
case 1:
if (stateA != stateB) counter+= 10; else counter-= 10 ;
break;
case 2:
if (stateA != stateB) counter+= 100; else counter-= 100 ;
break;
case 3:
if (stateA != stateB) counter+= 1000; else counter-= 1000 ;
break;
}
counter = constrain(counter, 0, 3000);
}
sA = stateA ;
// attachInterrupt(digitalPinToInterrupt(pinA), hitung, CHANGE);
}
void bell(){
tone(bzr, 4000);
delay(40);
noTone(bzr);
}