Advertisement
microrobotics

Pololu Optical Encoder for Micro Metal Motor

Apr 21st, 2023
813
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Here's an example code for reading the encoder counts from a Pololu Optical Encoder for Micro Metal Motor using an Arduino:
  3.  
  4. Note that you may need to modify the pin numbers and interrupt settings depending on your specific setup. Additionally, be sure to connect the encoder channels A and B to the corresponding pins on the Arduino and connect the encoder power supply to the Vin and GND pins on the Pololu board.
  5. */
  6.  
  7.  
  8. const int ENCODER_PIN_A = 2; // encoder channel A pin
  9. const int ENCODER_PIN_B = 3; // encoder channel B pin
  10.  
  11. volatile long encoderCount = 0; // current encoder count
  12. volatile int lastEncoderA = LOW; // last state of encoder channel A
  13.  
  14. void setup() {
  15.   // Set up the encoder pins
  16.   pinMode(ENCODER_PIN_A, INPUT_PULLUP);
  17.   pinMode(ENCODER_PIN_B, INPUT_PULLUP);
  18.  
  19.   // Attach interrupt service routine to encoder channel A
  20.   attachInterrupt(digitalPinToInterrupt(ENCODER_PIN_A), updateEncoderCount, CHANGE);
  21. }
  22.  
  23. void loop() {
  24.   // Example usage: print the current encoder count
  25.   Serial.println(encoderCount);
  26. }
  27.  
  28. void updateEncoderCount() {
  29.   // Read the current state of encoder channel A and B
  30.   int encoderA = digitalRead(ENCODER_PIN_A);
  31.   int encoderB = digitalRead(ENCODER_PIN_B);
  32.  
  33.   // Update the encoder count based on the change in encoder channel A and B
  34.   if (encoderA != lastEncoderA) {
  35.     if (encoderB != encoderA) {
  36.       encoderCount++;
  37.     } else {
  38.       encoderCount--;
  39.     }
  40.   }
  41.  
  42.   // Save the current state of encoder channel A for the next iteration
  43.   lastEncoderA = encoderA;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement