#include <Arduino.h>
// Define the pin numbers for the rotary encoder and button
const int ENCODER_CLK_PIN = 16; // Connect the CLK pin here
const int ENCODER_DT_PIN = 17; // Connect the DT pin here
const int BUTTON_PIN = 18; // Connect the button pin here
// Variables to track the encoder's state
int lastClkState = LOW;
int currentPosition = 0;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50; // Adjust debounce delay as necessary
void setup() {
Serial.begin(115200); // Initialize serial communication
// Set up the pins as input
pinMode(ENCODER_CLK_PIN, INPUT);
pinMode(ENCODER_DT_PIN, INPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // Use internal pull-up resistor
// Read the initial state of the CLK pin
lastClkState = digitalRead(ENCODER_CLK_PIN);
Serial.println("Encoder Test Initialized");
}
void loop() {
// Read the current state of the CLK pin
int currentClkState = digitalRead(ENCODER_CLK_PIN);
// Detect changes in the CLK state
if (currentClkState != lastClkState) {
// Determine the direction
int dtState = digitalRead(ENCODER_DT_PIN);
if (dtState != currentClkState) {
currentPosition++; // Clockwise
Serial.println("Rotated Clockwise");
} else {
currentPosition--; // Counterclockwise
Serial.println("Rotated Counterclockwise");
}
// Output the current position
Serial.print("Current Position: ");
Serial.println(currentPosition);
}
// Update the last CLK state
lastClkState = currentClkState;
// Handle button press with debounce
int buttonState = digitalRead(BUTTON_PIN);
if (buttonState == LOW && (millis() - lastDebounceTime) > debounceDelay) {
lastDebounceTime = millis(); // Reset debounce timer
Serial.println("Button Pressed!");
}
delay(5); // Small delay to stabilize reading
}