On it's own, the rotary encoder works. However when I try to pair it with the LCD, it doesn't seem to function. Nothing prints and I have no idea why. Any ideas?
Rotary Encoder Code:
#include <Encoder.h>
Encoder myEnc(4, 3);
long oldPos = -999;
int rotaryPos;
int pos;
int mod(int dividend, int divisor) {
return dividend < 0 ? ((dividend + 1) % divisor) + divisor - 1 : dividend % divisor;
}
double increment(double inc) {
return 4 / inc;
}
void setup() {
Serial.begin(9600);
}
void loop() {
long newPos = myEnc.read();
if (oldPos != newPos && newPos % 4 == 0) {
oldPos = newPos;
pos = newPos;
//pos = pos / 4;
rotaryPos = pos / increment(1);
Serial.println(mod(rotaryPos, 4));
}
}
Rotary Encoder paired with LCD:
#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
#include <Encoder.h>
U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/13, /* data=*/11, /* CS=*/10, /* reset=*/8);
Encoder myEnc(4, 3);
long oldPos = -999;
int rotaryPos;
int pos;
int mod(int dividend, int divisor) {
return dividend < 0 ? ((dividend + 1) % divisor) + divisor - 1 : dividend % divisor;
}
double increment(double inc) {
return 4 / inc;
}
void drawButton(int x, int y, int width, int height, int radius, bool highlight) {
if (highlight == true) {
u8g2.drawRFrame(x, y, width, height, radius);
}
}
void setup() {
Serial.begin(9600);
u8g2.begin();
u8g2.drawFrame(0, 0, 128, 64);
}
void loop() {
// put your main code here, to run repeatedly
u8g2.firstPage();
do {
drawButton(10, 3, 108, 13, 5, rotaryPos == 0 ? true : false);
u8g2.setFont(u8g2_font_6x10_tf);
u8g2.drawStr(20, 13, "PLACE HOLDER");
drawButton(10, 18, 108, 13, 5, true);
u8g2.setFont(u8g2_font_6x10_tf);
u8g2.drawStr(25, 28, "Turkish March");
drawButton(10, 33, 108, 13, 5, true);
u8g2.setFont(u8g2_font_6x10_tf);
u8g2.drawStr(38, 43, "Fur Elise");
drawButton(10, 48, 108, 13, 5, true);
u8g2.setFont(u8g2_font_6x10_tf);
u8g2.drawStr(26, 58, "Amazing Grace");
} while (u8g2.nextPage());
long newPos = myEnc.read();
if (oldPos != newPos && newPos % 4 == 0) {
oldPos = newPos;
pos = newPos;
//pos = pos / 4;
rotaryPos = pos / increment(1);
Serial.println(mod(rotaryPos, 4));
}
}
I've tried movie the rotary encoder code inside and outside of the do...while loop, but nothing happens. Any ideas?