A rotary encoder is an electromechanical device that converts the angular position or motion of a shaft or axle to an analog or digital code. Unlike potentiometers, rotary encoders provide full rotation without limits. They are commonly used in applications that require precise control over parameters such as volume, selection, or navigation in user interfaces, as well as in robotics and industrial controls for monitoring movement.
Pin Number | Name | Description |
---|---|---|
1 | Vcc | Power supply (3.3V to 5V) |
2 | GND | Ground connection |
3 | A | Output A - Quadrature output 1 |
4 | B | Output B - Quadrature output 2 |
5 | SW | Pushbutton switch (active low, optional) |
// Define the pins connected to the encoder
const int pinA = 2; // Encoder output A
const int pinB = 3; // Encoder output B
const int buttonPin = 4; // Encoder button pin
volatile int encoderPos = 0; // Variable to store the encoder position
bool lastEncoded = LOW; // Last encoded signal from pin A
// Interrupt service routine for encoder A change
void doEncoderA(){
bool currentEncoded = digitalRead(pinA);
if (digitalRead(pinB) != currentEncoded) {
encoderPos++;
} else {
encoderPos--;
}
lastEncoded = currentEncoded;
}
// Interrupt service routine for encoder B change
void doEncoderB(){
bool currentEncoded = digitalRead(pinA);
if (digitalRead(pinB) == currentEncoded) {
encoderPos++;
} else {
encoderPos--;
}
}
void setup() {
pinMode(pinA, INPUT);
pinMode(pinB, INPUT);
pinMode(buttonPin, INPUT_PULLUP); // Enable internal pull-up
// Attach the interrupt service routines to the encoder pins
attachInterrupt(digitalPinToInterrupt(pinA), doEncoderA, CHANGE);
attachInterrupt(digitalPinToInterrupt(pinB), doEncoderB, CHANGE);
}
void loop() {
// The main program can read encoderPos to determine the current position
// or use the button state for additional functionality.
}
Q: Can I use a rotary encoder for continuous rotation? A: Yes, rotary encoders are designed for continuous rotation without limits.
Q: How do I determine the direction of rotation? A: The direction can be determined by the sequence of the A and B outputs. If A leads B, for instance, the encoder is rotating in one direction; if B leads A, it's the opposite direction.
Q: What is the purpose of the SW pin? A: The SW pin is connected to a pushbutton switch built into the encoder. It can be used as a select button or for any other input purpose.
Q: How do I increase the resolution of my encoder? A: The resolution is fixed based on the encoder's design. To achieve higher resolution, you would need to use an encoder with a higher PPR specification.