Measure position
#define ENCA 4 // GPIO pin for encoder output A (Yellow wire)
#define ENCB 5 // GPIO pin for encoder output B (White wire)
volatile int posi = 0; // Position variable (shared between ISR and loop)
void readEncoder(); // Function prototype for the ISR
void setup() {
Serial.begin(9600); // Begin serial communication
pinMode(ENCA, INPUT); // Set encoder A pin as input
pinMode(ENCB, INPUT); // Set encoder B pin as input
attachInterrupt(digitalPinToInterrupt(ENCA), readEncoder, RISING); // Attach interrupt to ENCA rising edge
}
void loop() {
// Safely read the position variable with atomic block to prevent interrupts during read
noInterrupts(); // Disable interrupts
int posiCopy = posi; // Copy the volatile variable
interrupts(); // Re-enable interrupts
Serial.println(posiCopy); // Print the current position
delay(100); // Small delay to avoid spamming the serial output
}
// Interrupt Service Routine (ISR) that triggers when ENCA rises
void readEncoder() {
// Read ENCB to determine the direction
if (digitalRead(ENCB) == HIGH) {
posi++; // If ENCB is HIGH, increment position
} else {
posi--; // If ENCB is LOW, decrement position
}
}with classes
Last updated