//#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const byte buttonPins[] = {8, 7, 5, 6}; // LEFT, UP, RIGHT, DOWN
#define ENCODER_CLK 2 //Encoder
#define ENCODER_DT 3 //Encoder
#define ENCODER_SW 9 //Encoder
int counter = 0; // part of encoder code
void setup() {
Serial.begin(9600);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
for (byte i = 0; i < 4; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
randomSeed(analogRead(A0));
// Initialize encoder pins
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_SW, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, FALLING);
}
void readEncoder() {
int dtValue = digitalRead(ENCODER_DT);
if (dtValue == HIGH) {
counter++; // Clockwise
}
if (dtValue == LOW) {
counter--; // Counterclockwise
}
}
// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounter() {
int result;
noInterrupts();
result = counter;
interrupts();
return result;
}
int getParts() {
int result;
noInterrupts();
result = counter / 3;
interrupts();
return result;
}
void resetCounter() {
noInterrupts();
counter = 0;
interrupts();
}
void loop() {
display.clearDisplay();//
drawCounts();
drawParts();
display.display();
buttonPress();
if (digitalRead(ENCODER_SW) == LOW) {
resetCounter();
}
delay(10);
}
bool buttonPress() {
for (byte i = 0; i < 4; i++) {
byte buttonPin = buttonPins[i];
if (digitalRead(buttonPin) == LOW) {
if (i == 2) resetCounter();
return true;
}
}
return false;
}
void drawCounts() {
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(2,2);
display.print(F("Counter: "));
display.println(getCounter());
}
void drawParts() {
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(2,14);
display.print(F("Parts Count: "));
//display.setCursor(2,30);
display.println(getParts());
}