Example Code for Arduino-Encoder

Last revision 2026/01/07

This article provides a comprehensive guide on using encoders with Arduino, specifically in the context of Vortex robots. It covers hardware and software requirements, wiring diagrams, and offers sample code for practical application, alongside troubleshooting tips to optimize the setup process.

Hardware Preparation

Software Preparation

Wiring Diagram

Other Preparation Work

  1. Unscrew the screw and open the USB programming port.
  2. Turn on Vortex power switch, and plug in the Micro usb cable, it will install the driver automatically if you have installed Arduino IDE. If not, you can find it in the driver file in Arduino IDE folder-->Drivers folder.
  3. There is a switch close to the USB port, make sure the trigger is close to the USB side. This is MP3 switch, we'll teach you how to add new song in the following chapter.
  4. Open your Arduino IDE, select "Arduino UNO" and right "COM port" in Arduino IDE, now you can enjoy coding.

Sample Code

/***************************************************
 Vortex V1.0 (Small robots like bread)
 <https://www.dfrobot.com.cn/goods-1199.html>
 ***************************************************
 This example show how to use encoder sensor.
 Created 2016-2-3
 By Andy zhou <[email protected]>
 version:V1.0
 ****************************************************/
/***********Notice and Trouble shooting***************
 1.Connection and Diagram can be found here
 <http://wiki.dfrobot.com.cn/index.php?title=(SKU:ROB0116)_Vortex%E5%8F%AF%E7%BC%96%E7%A8%8B%E6%9C%BA%E5%99%A8%E4%BA%BA#.E6.A0.B7.E4.BE.8B.E4.BB.A3.E7.A0.81>
 2.This code is tested on vortex V1.0.
 ****************************************************/
#define pinInputLeft 0
#define pinInputRight 1
long leftPul,rightPul;
void leftCallBack(){
  leftPul++;
}
void rightCallBack(){
  rightPul++;
}
void initDdevice(){
    pinMode(5,OUTPUT);
    pinMode(6,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(10,OUTPUT);
    attachInterrupt(pinInputLeft,leftCallBack,CHANGE);
    attachInterrupt(pinInputRight,rightCallBack,CHANGE);
    sei();
}
void motorDebug(){
  digitalWrite(5,HIGH);
  digitalWrite(6,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);
}
void printPul(){
  Serial.print(leftPul);
  Serial.print(" ");
  Serial.println(rightPul);
  leftPul = 0;
  rightPul = 0;
}
void setup() {
  initDdevice();
  Serial.begin(9600);
  motorDebug();
}
void loop() {
  printPul();
  delay(500);
}

Result

Was this article helpful?

TOP