Example Code for Arduino-Motor Encoder Pulse Detection

Last revision 2026/01/08

This project demonstrates how to interface the FIT0403 Metal DC Geared Motor with Encoder to an Arduino board for detecting motor rotation pulses and direction. Users will learn to use Arduino interrupts to count encoder pulses and determine the motor's rotation direction.

Hardware Preparation

Software Preparation

Wiring Diagram

FIT0403 Metal DC Geared Motor w/Encoder - 12V 122RPM 38Kg.cm Encoder Diagram

Other Preparation Work

For Arduino UNO or Mega2560, connect the encoder's A pin to digital pin 2 (interrupt 0). For Arduino Leonardo or Romeo, connect the encoder's A pin to digital pin 3. Refer to the interrupt port diagram for details.

Sample Code


//The sample code for driving one way motor encoder
const byte encoder0pinA = 2;//A pin -> the interrupt pin 0
const byte encoder0pinB = 4;//B pin -> the digital pin 4
byte encoder0PinALast;
int duration;//the number of the pulses
boolean Direction;//the rotation direction


void setup()
{
  Serial.begin(57600);//Initialize the serial port
  EncoderInit();//Initialize the module
}

void loop()
{
  Serial.print("Pulse:");
  Serial.println(duration);
  duration = 0;
  delay(100);
}

void EncoderInit()
{
  Direction = true;//default -> Forward
  pinMode(encoder0pinB,INPUT);
  attachInterrupt(0, wheelSpeed, CHANGE);
}

void wheelSpeed()
{
  int Lstate = digitalRead(encoder0pinA);
  if((encoder0PinALast == LOW) && Lstate==HIGH)
  {
    int val = digitalRead(encoder0pinB);
    if(val == LOW && Direction)
    {
      Direction = false; //Reverse
    }
    else if(val == HIGH && !Direction)
    {
      Direction = true;  //Forward
    }
  }
  encoder0PinALast = Lstate;

  if(!Direction)  duration  ;
  else  duration--;
}

Result

Open the Arduino Serial Monitor at a baud rate of 57600. You will see the message "Pulse:" followed by the number of encoder pulses detected in each 100ms interval. The pulse count will increase if the motor rotates in the reverse direction and decrease if it rotates forward (based on the code's direction logic).

Additional Information

For more details on the attachInterrupt() function, refer to the Arduino reference: http://arduino.cc/en/Reference/AttachInterrupt

Was this article helpful?

TOP