How do I control the speed of my servo based on the rate of water flowing through my water flow sensor?

Hi there,

Thanks for taking the time to help me out!

On the Arduino program, I’m trying to control the speed of my micro servo so that it rotates 180 degrees based on how much water is flowing through my water sensor.

I currently have “delay” to control the speed but I don’t think this will work in sync with water flowing through my sensor. Do you have any suggestions of particular code I can use to make this work?

Here is what I have at the moment:

#include <Servo.h>

Servo servo_test;        //initialize a servo object for the connected servo

int angle = 0;

volatile double waterFlow;

void setup() {
  Serial.begin(9600);  //baudrate
  waterFlow = 0;
  attachInterrupt(0, pulse, RISING);  //DIGITAL Pin 2: Interrupt 0

  servo_test.attach(9);      // attach the signal pin of servo to pin9 of arduino

void loop() {

 const int angleIncrement = 1;
const int incrementDelay = waterFlow;
for (int angle = 0; angle < 180; angle += angleIncrement) { // single "degree" increments
 servo_test.write (angle);
 delay (incrementDelay);

  for (angle = 180; angle >= 1; angle -= 10) // command to move from 180 degrees to 0 degrees
    servo_test.write(angle);              //command to rotate the servo to the specified angle


void pulse()   //measure the quantity of square wave
  waterFlow += 1.0 / 450.0;

Thanks for your help!


Hi Declan!

As far as I know the Servo.h library does not support servo speed on a fixed limit servo, you can only write the position (0-180) that you want the servo to move to. There is a servo library you can use where you can set the position and speed that the servo moves. Should be pretty easy to incorporate into your code. Here is the link!

I hope that helps! Be sure to share your finished project once its completed!