I need your help regarding a problem I am facing while measuring wind speed. In my sketch I get a reading every 20 counts which the magnet goes past the sensor. I need to change it in order to get a reading every 20 seconds. How can I do it with minimum changes to the sketch?

volatile byte revolutions;

float rpmilli;
float speed;

unsigned long timeold=0;

void setup()
  attachInterrupt(digitalPinToInterrupt(2), rpm_fun, RISING);

  revolutions = 0;
  rpmilli = 0;
  timeold = 0;

void loop()
  if (revolutions >= 20) { 
    //Update RPM every 20 counts, increase this for better RPM resolution,
    //decrease for faster update

    // calculate the revolutions per milli(second)
    rpmilli = ((float)revolutions)/(millis()-timeold);

    timeold = millis();
    revolutions = 0;

    // WHEELCIRC = 2 * PI * radius (in meters)
    // speed = rpmilli * WHEELCIRC * "milliseconds per hour" / "meters per kilometer"

    // simplify the equation to reduce the number of floating point operations
    // speed = rpmilli * WHEELCIRC * 3600000 / 1000
    // speed = rpmilli * WHEELCIRC * 3600

    speed = rpmilli * 0.6597 * 3600;

    Serial.print(rpmilli * 60000);
    Serial.print(" Speed:");
    Serial.println(" kph");

void rpm_fun()

1 Answer 1


You can use the millis() function to measure time intervals and do things regularly in these intervals. Refer to the BlinkWithoutDelay example, that comes with the Arduino IDE, or to one of the many tutorials for the millis() function on the web.

Basically you will need to do the following:

  1. Declare a timestamp variable to hold the time when the data was displayed last time (in global scope):

     unsigned long timestamp = 0;
  2. Declare the interval, that you want the display to happen in:

     #define DISPLAY_INTERVAL  20000
  3. In your if statement check if the time difference between now and the timestamp is bigger than the interval

     if(millis() - timestamp > DISPLAY_INTERVAL){

    Note that you should do millis() comparisons always this way (by calculating the difference), so that the rollover of millis() will not affect the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.