Example Code for Arduino-Encoder Pulse Counting

This project demonstrates how to read pulse signals from a one-way motor encoder and judge the rotation direction. Users can learn how to use Arduino interrupts to capture encoder signals and implement basic pulse counting logic.

Hardware Preparation

  • DFRobot FIT0277 DC Motor: 1 piece (SKU: FIT0277)
  • Arduino Board (e.g., Uno/Nano): 1 piece
  • Jumper Wires: Several

Software Preparation

  • Arduino IDE: Version 1.8.x or later, Download Link
  • No additional libraries are required for this sample.

Wiring Diagram

Diagram for using encoder with Encoder Adapter
Diagram for using encoder without Encoder Adapter

Sample Code

/*
Pay attention to the interrupt pin,please check which microcontroller you use.
http://arduino.cc/en/Reference/AttachInterrupt
*/

//The sample code for driving one way motor encoder
const byte encoder0pinA = 2;//A pin -> the interrupt pin 2
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);//int.0
}

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

  1. Open the Arduino Serial Monitor (baud rate: 57600).
  2. Rotate the motor shaft:
    Forward direction (default): Serial output shows negative pulse counts (e.g., Pulse: -10).
    Reverse direction: Serial output shows positive pulse counts (e.g., Pulse: 15).
  3. The pulse count updates every 100ms.

Tip: Our tests under common environmental sound conditions show that there are differences between individual motors. Although we considered averaging the sound emission values, this was not accurate; therefore, we retained the highest value measured during the tests. The lowest sound emission reached an average of 57 dBA, measured with an indoor ambient noise level of approximately 40 dBA. These tests were not conducted in an acoustic chamber, and no load was applied. For all sound-sensitive projects, the use of a soundproof enclosure for all mechanical parts is recommended.

Was this article helpful?

TOP