Example Code for Arduino-Motor Encoder Pulse Reading
The sample code for driving one way motor encoder. When the motor turns forward, the digital output value is > 0. When the motor reverses direction, digital output < 0. The faster the motor's speed, the greater the value of the number.
Hardware Preparation
- DFRduino UNO x1
- DC power supply x1
- L298 x1
Software Preparation
- Arduino IDE Download Arduino IDE
Wiring Diagram

This tutorial is intended to use the encoder, Select D2 pin and D3 pin, Wherein D2 as an interrupt port, D3 as an input pin. In practice, two pins need to ensure that one of pins must be an interrupt pin, and the other definable (see the interrupt port with different board).
Other Preparation Work
Interrupt Port with Different Board
Notice: attachInterrupt()

- When using an Arduino UNO and Interrupt 0 (INT.0), connect digital pin D2 on the board.
- The following code applies to Arduino UNO and Mega 2560 only.
- If you are using an Arduino Leonardo, use digital pin D3 instead of D2.
Sample Code
//The sample code for driving one way motor encoder
const byte encoder0pinA = 2;//A pin -> the interrupt pin 0
const byte encoder0pinB = 3;//B pin -> the digital pin 3
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
Explanation: Here you can see serial data. When the motor turns forward, the digital output value is > 0. When the motor reverses direction, digital output < 0. The faster the motor's speed, the greater the value of the number.

Was this article helpful?
