Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- To use the Pololu N20 Magnetic Encoder for Micro Metal Gearmotors, you'll need an Arduino to read the encoder's outputs and a motor driver to control the gearmotor. In this example, I'll use an MX1919-DIP motor driver mentioned earlier.
- Here's an example code to control the speed and direction of the motor using the MX1919-DIP driver and read the encoder counts from the Pololu N20 Magnetic Encoder:
- This code rotates the motor clockwise at full speed for 2 seconds, reads and prints the encoder counts, stops for 1 second, rotates the motor counterclockwise at half speed for 2 seconds, reads and prints the encoder counts again, and then stops for 1 second. The cycle will then repeat.
- Connect the MX1919-DIP's PWM and DIR inputs to the Arduino's digital pins 3 and 2, respectively, and the encoder's outputs (A and B) to digital pins 4 and 5. Make sure to provide an appropriate power supply to the driver's motor voltage and ground pins, and connect the motor to the driver's output terminals.
- Remember to install the Encoder library (https://github.com/PaulStoffregen/Encoder) to your Arduino IDE before uploading the code.
- */
- #include <Encoder.h>
- // Motor control pins
- const int pwmPin = 3;
- const int dirPin = 2;
- // Encoder pins
- const int encoderPinA = 4;
- const int encoderPinB = 5;
- // Create an Encoder object
- Encoder myEncoder(encoderPinA, encoderPinB);
- void setup() {
- // Motor control pin setup
- pinMode(pwmPin, OUTPUT);
- pinMode(dirPin, OUTPUT);
- // Encoder pin setup
- pinMode(encoderPinA, INPUT_PULLUP);
- pinMode(encoderPinB, INPUT_PULLUP);
- // Start serial communication
- Serial.begin(9600);
- }
- void loop() {
- // Rotate the motor clockwise at full speed
- digitalWrite(dirPin, HIGH);
- analogWrite(pwmPin, 255);
- delay(2000);
- // Stop the motor and print encoder counts
- analogWrite(pwmPin, 0);
- long encoderCounts = myEncoder.read();
- Serial.print("Encoder counts: ");
- Serial.println(encoderCounts);
- myEncoder.write(0); // Reset encoder count
- delay(1000);
- // Rotate the motor counterclockwise at half speed
- digitalWrite(dirPin, LOW);
- analogWrite(pwmPin, 127);
- delay(2000);
- // Stop the motor and print encoder counts
- analogWrite(pwmPin, 0);
- encoderCounts = myEncoder.read();
- Serial.print("Encoder counts: ");
- Serial.println(encoderCounts);
- myEncoder.write(0); // Reset encoder count
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement