// TFT Display Includes
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
// Define TFT Pins
#define TFT_DC 48
#define TFT_CS 53
// Define Rotary Encoder Pins
#define CLK 2
#define DT 3
#define SW 4
// Define Button Pins
#define UPIN 5
#define RPIN 6
#define LPIN 8
#define DPIN 7
const byte buttonPins[] = {UPIN, DPIN, LPIN, RPIN, SW};
// Initialize TFT
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// Initialize Encoder Variables
int counter = 0;
int counterOld = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir = "";
unsigned long lastButtonPress = 0;
// Time Variables
unsigned int t_ms = 0; // Time in ms
int t_buttonBuffer = 300; // Buffer between when buttons are read
int t_encBuffer = 0; // Buffer between when encoder is read
unsigned int t_buttonOld = 0; // Time when button was last read
unsigned int t_encOld = 0; // Time when button was last read
void setup() {
// Begin Serial Communication
Serial.begin(115200);
// Setup Rotary Encoder Pins
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
// Setup Button Pins
for (int i = 0; i < 5; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
// Begin TFT
tft.begin();
tft.setRotation(1);
}
void loop() {
t_ms = millis();
// Read Button Presses
if (t_ms - t_encOld > t_encBuffer) { // If t_encBuffer time has elapsed
// 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 (digitalRead(DT) != currentStateCLK) {
counter --;
} else {
// Encoder is rotating CW so increment
counter ++;
}
Serial.print("\nCounter: ");
Serial.println(counter);
}
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
}
int readButtons() {
if (t_ms - t_buttonOld > t_buttonBuffer) { // If t_buttonBuffer time has elapsed since last check
t_buttonOld = t_ms; // Update last checked time
for (int i = 0; i < 5; i++) { // For each button
if (!digitalRead(buttonPins[i])) { // Read if button is pressed (LOW)
return i+1;
}
}
}
}