Example Code for Arduino - Dispense Fixed Volume of Liquid
To use the DFRobot Peristaltic Pump V2, first prepare the hardware including DFRduino UNO+IO Expansion Board and the pump. Then, download and install Arduino IDE and the DFRobot_PeristalticPump_V2 library. The example code demonstrates how to set up and control the pump to draw a specified volume of liquid, with real-time volume updates via the Serial Monitor. It's like programming a precise liquid dispenser for your projects.
You can set the peristaltic pump to draw XX mL of liquid. This function delivers high accuracy after calibration, so it is recommended to use it after calibration.
Hardware Preparation
- DFRduino UNO+IO Expansion Board (SKU:DFR0216-2) ×1
- Gravity: Peristaltic Pump V2(SKU:DFR1216)×1
- Gravity Sensor Cable(Comes with Peristaltic Pump V2)
Software Preparation
- Download Arduino IDE: Click to download Arduino IDE
- Download DFRobot_PeristalticPump_V2 library:DFRobot_PeristalticPump_V2
- Arduino IDE V1.8.19 (or below) can extract the .zip library downloaded from GitHub into the “libraries” folder located in the Arduino IDE installation directory.
- Arduino IDE V2.0.0 (or above) can directly search for the "DFRobot_PeristalticPump_V2" library in the Library Manager and install it.
Example Code
#include "DFRobot_PeristalticPump_V2.h"
#if defined(ESP32)
int servoPin = 17;
#else
int servoPin = 9;
#endif
DFRobot_PeristalticPump_V2 pump(servoPin);
uint8_t volumePumpFlag = 1;
float runTime = 0.0f;
void onVolumePumpCallback(float volume, bool finished)
{
if (finished) {
Serial.print(F("Final volume(ml): "));
Serial.println(volume, 4);
} else {
Serial.print(F("Current volume(ml): "));
Serial.println(volume, 4);
}
}
void setup()
{
Serial.begin(115200);
pump.begin();
pump.setVolumePumpCallback(onVolumePumpCallback, 50);
Serial.println(F("volumePump demo (call once)."));
Serial.println(F("Run calPump.ino first to store flowRate in EEPROM."));
}
void loop()
{
// Update pump status; this must be called repeatedly in loop().
pump.updatePumpStatus();
/**
* Note:
* 1. Use volumePump() to run the pump for a target volume.
* 2. Parameter 1: target pumped volume in milliliters (ml).
* 3. Parameter 2: pointer to a float for the expected run time (s).
* 4. Return true: task started successfully.
* 5. Return false: start failed.
* - A task may already be running. Wait until it finishes, or call stopPump().
* - Calibration data may be invalid. Run calPump.ino to recalibrate flow rate.
*/
if (volumePumpFlag) {
volumePumpFlag = 0;
Serial.println(F("Start: volumePump 100 ml"));
if (pump.volumePump(100, &runTime)) {
Serial.print(F("Expected run time(s): "));
Serial.println(runTime, 2);
} else {
Serial.println(F("volumePump start failed."));
}
}
}
Result
The peristaltic pump will draw the specified volume of liquid. The pumped liquid volume will be printed in the Serial Monitor.

Was this article helpful?
