#include #include #include #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 32 // OLED display height, in pixels #define OLED_RESET -1 #define SCREEN_ADDRESS 0x3C Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); const int encoderAPin = 2; const int encoderBPin = 3; // Define the pin for the reset button const int resetButtonPin = 4; // Variables to store the current and previous state of the encoder int encoderALast = LOW; int encoderValue = 0; int encoderDirection = 0; void setup() { pinMode(encoderAPin, INPUT); pinMode(encoderBPin, INPUT); attachInterrupt(digitalPinToInterrupt(encoderAPin), updateEncoder, CHANGE); // Set up the reset button pinMode(resetButtonPin, INPUT_PULLUP); // Enable internal pull-up resistor // Initialize the display if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) { Serial.println(F("SSD1306 allocation failed")); for (;;) { // Don't proceed if the display initialization fails } } // Clear the display buffer display.clearDisplay(); display.display(); // Start the serial communication Serial.begin(9600); } void loop() { // Check if the encoder value or direction has changed static int lastEncoderValue = 0; static int lastEncoderDirection = 0; if (encoderValue != lastEncoderValue || encoderDirection != lastEncoderDirection) { // Clear the display buffer display.clearDisplay(); // Print the encoder value on the display display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.setCursor(0, 0); display.print("Value: "); display.println(encoderValue); // Display the direction (Clockwise or Counterclockwise) display.setCursor(0, 10); display.print("Direction: "); if (encoderDirection == 1) { display.println("Clockwise"); } else if (encoderDirection == -1) { display.println("Counterclockwise"); } else { display.println("None"); } // Update the display display.display(); // Update the last recorded values lastEncoderValue = encoderValue; lastEncoderDirection = encoderDirection; } // Check if the reset button is pressed if (digitalRead(resetButtonPin) == LOW) { // Reset the encoder value to 0 encoderValue = 0; encoderDirection = 0; delay(200); // Debounce delay to avoid multiple resets } // Your main code here } void updateEncoder() { int encoderAState = digitalRead(encoderAPin); int encoderBState = digitalRead(encoderBPin); if ((encoderALast == LOW) && (encoderAState == HIGH)) { if (encoderBState == LOW) { encoderValue++; encoderDirection = 1; // Clockwise rotation } else { encoderValue--; encoderDirection = -1; // Counterclockwise rotation } } encoderALast = encoderAState; }