#include <Wire.h>
#include <U8g2lib.h> // U8g2 library for drawing on OLED display
// Define the pins for the rotary encoder
#define ENCODER_CLK 33 // Connect to the CLK (A) pin of the rotary encoder
#define ENCODER_DT 25 // Connect to the DT (B) pin of the rotary encoder
#define ENCODER_SW 26 // Connect to the SW (Button) pin of the rotary encoder
// Initialize the U8g2 display object (assuming I2C communication)
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R2, U8X8_PIN_NONE, U8X8_PIN_NONE); // SH1107 or SSD1306, adjust for your screen
int lastState = LOW;
int position = 0; // Current position of the rotary encoder
int buttonState = LOW;
int lastButtonState = LOW;
void setup() {
Serial.begin(115200); // Start serial communication for debugging
// Set the pins for the encoder as input
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_SW, INPUT_PULLUP); // If you have a button
lastState = digitalRead(ENCODER_CLK); // Read the initial state of CLK pin
// Initialize the OLED display
u8g2.begin(); // Begin the u8g2 library
u8g2.setContrast(255); // Set display contrast/brightness
}
void loop() {
int currentState = digitalRead(ENCODER_CLK);
int currentButtonState = digitalRead(ENCODER_SW);
// Check if the encoder's CLK pin state has changed
if (currentState != lastState) {
// Determine the direction based on the state of the DT pin
if (digitalRead(ENCODER_DT) == LOW) {
position++; // Increment the position (clockwise)
Serial.println("Rotated clockwise ⏩");
} else {
position--; // Decrement the position (counter-clockwise)
Serial.println("Rotated counterclockwise ⏪");
}
// Print the current position (steps) to the Serial Monitor
Serial.print("Current Position: ");
Serial.println(position);
// Update the OLED display with the current position
u8g2.clearBuffer(); // Clear the display buffer
u8g2.setFont(u8g2_font_ncenB08_tr); // Choose a font
u8g2.setCursor(0, 0); // Set cursor position
u8g2.print("Position: ");
u8g2.print(position); // Display the current position value
u8g2.sendBuffer(); // Draw the buffer to the display
lastState = currentState; // Update the last state to the current state
}
// Button press logic (if using a button)
if (currentButtonState == LOW && lastButtonState == HIGH) {
Serial.println("Button Pressed!");
// You can add additional actions for button press here
}
lastButtonState = currentButtonState; // Update the button state
delay(10); // Small delay to debounce the input
}
// NOTES:
// SH1107 OLED SCREEN
// IIC connection of the OLED display and Arduino UNO
// +5V > +5V
// GND > GND
// SCL (serial clock) > A5 or SCL
// SDA (serial data) > A4 or SDA
Loading
grove-oled-sh1107
grove-oled-sh1107