Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- The Pololu Romi Encoder Pair Kit is designed to measure the rotation speed and direction of the motors on the Romi Chassis. The encoders consist of two parts: a magnetic disc with 12 equally spaced magnetic poles and a magnetic encoder sensor. To read the encoder values, you can use an Arduino and interrupts.
- Here's an example code to read the encoder values from a Pololu Romi Encoder Pair Kit:
- This code is for an Arduino Mega. If you are using an Arduino Uno or similar boards, you'll need to use pins 2 and 3 for both encoders, as they have only two interrupt pins. In that case, you will need to modify the interrupt service routine to handle both encoders.
- Before using this code, make sure to connect the encoder output pins to the appropriate interrupt pins on your Arduino board. Also, connect the ground and Vcc pins of the encoders to the ground and appropriate voltage supply on your Arduino board.
- Upload the code to your Arduino, and open the Serial Monitor. The encoder counts for both the left and right motors will be displayed. These counts can be used to calculate the rotation speed and direction of the motors, and can be helpful in applications like odometry, speed control, and position control.
- */
- // Encoder pins connected to the Arduino interrupt pins
- const int encoderPinA1 = 2; // Left motor encoder A pin
- const int encoderPinB1 = 3; // Left motor encoder B pin
- const int encoderPinA2 = 18; // Right motor encoder A pin (Interrupt pin on Arduino Mega)
- const int encoderPinB2 = 19; // Right motor encoder B pin (Interrupt pin on Arduino Mega)
- // Encoder counts
- volatile long leftEncoderCount = 0;
- volatile long rightEncoderCount = 0;
- // Interrupt service routines
- void leftEncoderISR() {
- if (digitalRead(encoderPinA1) == digitalRead(encoderPinB1)) {
- leftEncoderCount++;
- } else {
- leftEncoderCount--;
- }
- }
- void rightEncoderISR() {
- if (digitalRead(encoderPinA2) == digitalRead(encoderPinB2)) {
- rightEncoderCount--;
- } else {
- rightEncoderCount++;
- }
- }
- void setup() {
- Serial.begin(9600);
- // Set encoder pins as inputs
- pinMode(encoderPinA1, INPUT);
- pinMode(encoderPinB1, INPUT);
- pinMode(encoderPinA2, INPUT);
- pinMode(encoderPinB2, INPUT);
- // Enable pull-up resistors
- digitalWrite(encoderPinA1, HIGH);
- digitalWrite(encoderPinB1, HIGH);
- digitalWrite(encoderPinA2, HIGH);
- digitalWrite(encoderPinB2, HIGH);
- // Attach interrupts
- attachInterrupt(digitalPinToInterrupt(encoderPinA1), leftEncoderISR, CHANGE);
- attachInterrupt(digitalPinToInterrupt(encoderPinA2), rightEncoderISR, CHANGE);
- }
- void loop() {
- // Print the encoder counts to the serial monitor
- Serial.print("Left Encoder: ");
- Serial.print(leftEncoderCount);
- Serial.print("\tRight Encoder: ");
- Serial.println(rightEncoderCount);
- delay(500);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement