A rotary encoder is an electro-mechanical device that converts the angular position or motion of a shaft into analog or digital output signals. Rotary encoders are widely used in various applications, including industrial controls, robotics, position sensing, and user input devices like volume controls and navigational menus.
Pin Number | Name | Description |
---|---|---|
1 | VCC | Power supply (3.3V to 5V) |
2 | GND | Ground connection |
3 | OUTA | Output A - Quadrature output 1 |
4 | OUTB | Output B - Quadrature output 2 |
5 | SW | Switch (push button) |
// Define the pins for the rotary encoder
const int encoderPinA = 2; // Output A
const int encoderPinB = 3; // Output B
const int buttonPin = 4; // Push button switch
volatile int lastEncoded = 0;
volatile long encoderValue = 0;
void setup() {
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
pinMode(buttonPin, INPUT_PULLUP);
// Set up interrupts for the encoder pins
attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), updateEncoder, CHANGE);
}
void loop() {
// Use encoderValue for your application
}
void updateEncoder() {
int MSB = digitalRead(encoderPinA); // Most significant bit
int LSB = digitalRead(encoderPinB); // Least significant bit
int encoded = (MSB << 1) | LSB; // Converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; // Adding it to the previous encoded value
if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue++;
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue--;
lastEncoded = encoded; // Store this value for next time
}
Q: Can I use a rotary encoder with an Arduino without external libraries?
A: Yes, you can use interrupts as shown in the example code, or you can poll the encoder in the loop()
function.
Q: How do I know if my rotary encoder is incremental or absolute? A: Incremental encoders provide relative position with no fixed start or end point, while absolute encoders provide a unique position for each angle of the shaft. Check the datasheet of your specific encoder to determine its type.
Q: What is the purpose of the push-button on some rotary encoders? A: The push-button can be used as a user input, often to select an option after scrolling through a menu with the encoder.