ky040 encoder test sketch on i2c lcd
hello have been playing around encoder , 20-04 i2c fed lcd trying both work there have read lot of old posts on subject small amount of learning have ( best way learn put together)
the problem cannot see encoder counts ok counter clockwise clockwise shows 0-1-0 , on
i think problem lies incrementing decrementing count ?? think, take please , enlighten me thanks
code: [select]
#include <liquidcrystal_i2c.h>
// lcd defaults
#define i2c_addr 0x27 // define i2c address 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 generating interrupts using clk signal
const int pindt = 3; // used reading dt signal
const int pinsw = 4; // used 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 executed when high low transition detected on clk
volatile boolean clk = digitalread(pinclk);
volatile boolean dt = digitalread(pindt);
= ((!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 connected pin 2 on arduino uno
serial.begin(9600);
serial.println("start");
lcd.setbacklightpin(backlight_pin,positive);
lcd.setbacklight(high);
lcd.begin(20,4); // cuzz have 20x4 display
lcd.clear(); // rid of garbage 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 pressed
encposition = 0; // if yes, reset counter zero
serial.print("reset");
encchanged = true;
}
oldsw = sw;
if (encchanged) { // if rotation detected
encchanged = false; // not repeat if loop until new rotation detected
serial.print("count = ");
serial.println(encposition);
analogwrite(pinled, encposition);
lcd.setcursor(12,1);
lcd.print(encposition);
}
}
i don't know problem isr should never have delay(...) statement in it.
1) delay(...) depends upon interrupts disabled while in isr.
2) isr should execute possible. delay(..) slows down isr , prevents executing possible.
ditto serial.print(...) , cousins.
1) delay(...) depends upon interrupts disabled while in isr.
2) isr should execute possible. delay(..) slows down isr , prevents executing possible.
ditto serial.print(...) , cousins.
Arduino Forum > Using Arduino > Programming Questions > ky040 encoder test sketch on i2c lcd
arduino
Comments
Post a Comment