Example Code for Arduino-Adjust Gain Coefficient
Last revision 2026/01/15
This article guides users through adjusting the gain coefficient of a rotary encoder using Arduino, including hardware setup, software installation, and sample code implementation.
Hardware Preparation
- DFRduino UNO R3 (or similar) x 1
- Rotary Encoder Module (I2C) x 1
- Jumper wires
Software Preparation
- Arduino IDE
- Download and install the Rotary Encoder Module Library. (About how to install the library?)
Wiring Diagram

Other Preparation Work
Ensure the rotary encoder's I2C address is set to 0x54 via the DIP switches on the back of the module.I2C Setting Method
Sample Code
/*!
* @file setSensor.ino
* @brief This demo shows how to adjust gain factor of the encoder
* @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
* @license The MIT License (MIT)
* @author [qsjhyy]([email protected])
* @version V1.0
* @date 2021-09-15
* @url https://github.com/DFRobot/DFRobot_VisualRotaryEncoder
*/
#include <DFRobot_VisualRotaryEncoder.h>
/**
* Instantiate an object to drive our sensor;
* Set address according to encoder DIP switch:
* | 1 | 2 | ADDR |
* |---|---|------|
* | 0 | 0 | 0x54 |
* | 0 | 1 | 0x55 |
* | 1 | 0 | 0x56 |
* | 1 | 1 | 0x57 |
*/
DFRobot_VisualRotaryEncoder_I2C sensor(/*i2cAddr = */0x54, /*i2cBus = */&Wire);
void setup()
{
Serial.begin(115200);// Init serial port
// initialize the sensor
while( NO_ERR != sensor.begin() ){
Serial.println("Communication with device failed, please check connection");
delay(3000);
}
Serial.println("Begin ok!");
/**
* Set the current gain factor of the encoder, accuracy value to rotate one detent
* Accuracy range:1~51,the minimum is 1 (light up one LED about every 2.5 turns), the maximum is 51 (light up one LED every one detent rotation)
* gainValue range[1, 51], the setting is invalid when out of range.
*/
sensor.setGainCoefficient(10);// The currently set accuracy value: 10
/**
* Get the current gain factor of the encoder, accuracy value to rotate one detent
* Accuracy range:1~51,the minimum is 1 (light up one LED about every 2.5 turns), the maximum is 51 (light up one LED every one detent rotation)
* return value range: 1-51
*/
uint8_t gainCoefficient = sensor.getGainCoefficient();
Serial.print("Encoder current gain coefficient: ");
Serial.println(gainCoefficient);
Serial.println();
delay(1000);
}
void loop()
{
/**
* Get the encoder current count value
* return value range: 0-1023
*/
uint16_t encoderValue = sensor.getEncoderValue();
Serial.print("The encoder current counts: ");
Serial.println(encoderValue);
Serial.println();
delay(1000);
}
Result

Was this article helpful?
