An encoder is an electronic device that converts motion, whether it's rotary or linear, into an electrical signal that can be read by a control system. This conversion allows for precise monitoring of position, speed, and direction. Encoders are widely used in robotics, industrial controls, automotive applications, and any system where precise motion control is required.
Pin Number | Name | Description |
---|---|---|
1 | Vcc | Power supply input, typically 5V or 3.3V |
2 | GND | Ground connection |
3 | A | Output channel A, provides a square wave signal |
4 | B | Output channel B, provides a square wave signal 90° out of phase with channel A |
5 | Z | (Optional) Index pulse, provides a single pulse per revolution |
// Define the encoder pins
const int encoderPinA = 2; // Channel A
const int encoderPinB = 3; // Channel B
// Variables to store encoder state
volatile int encoderPos = 0;
bool encoderALast = LOW;
bool encoderBLast = LOW;
void setup() {
pinMode(encoderPinA, INPUT_PULLUP); // Set encoder pins as inputs
pinMode(encoderPinB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(encoderPinA), readEncoder, CHANGE); // Interrupt on change
Serial.begin(9600); // Start serial communication at 9600 baud
}
void loop() {
// Main loop code here
}
// Interrupt service routine for reading the encoder
void readEncoder() {
bool encoderA = digitalRead(encoderPinA);
bool encoderB = digitalRead(encoderPinB);
if (encoderA != encoderALast) { // If the A signal has changed
if (encoderB != encoderA) { // If B is different from A, it's a CW rotation
encoderPos++;
} else { // If B is the same as A, it's a CCW rotation
encoderPos--;
}
}
encoderALast = encoderA; // Update the last state of A
Serial.println(encoderPos); // Print the position
}
Q: Can I use an encoder with a higher voltage rating on a 5V system? A: Yes, but ensure that the encoder's output signal levels are compatible with your system's logic levels.
Q: How do I determine the direction of rotation? A: By comparing the phase relationship of channels A and B, you can determine the direction of rotation. If A leads B, it's typically clockwise (CW); if B leads A, it's counterclockwise (CCW).
Q: What is the purpose of the Z channel? A: The Z channel provides a single pulse per revolution and can be used for precise position control or for finding a reference position.