Run code for x amount of time

I am currently working on a project where I am building an anemometer. I need the code to run for 30 seconds once a N.O. momentary push button is pressed. I was able to develop the anemometer code with some help online, but the 30 second code running has stumped me. Any help is appreciated. Below is the anemometer code:

const int pulsePin = 8; // Input signal to pin 8
int pulseHigh;
int pulseLow;
float pulseTotal;
float frequency;
int fpm; //Float gives decimal, can be changed to int for whole number.
void setup()
Serial.begin(9600); //Begins serial monitor, can use serial plotter.

void loop()
pulseHigh = pulseIn(pulsePin, HIGH);
pulseLow = pulseIn(pulsePin, LOW);

pulseTotal = pulseHigh + pulseLow; // Time period of the pulse in u_seconds.
frequency = 1000000 / pulseTotal; // Frequency in hertz.
fpm = (2.29 * frequency) + 36.4; // Converts frequency to FPM reading, equation from mfg .pdf ; adjusted for hardware used 3.195–>2.29 .

if (fpm < 260) fpm = 0 ; //Elimnates a mjaority of “ghost readings”.
if (fpm > 10000) fpm = “Above Read Range” ; //Limits read range to not overload sensor.

Serial.println(" fpm");
delay(500); // 1/2 second interval in print readings, not sample rate.

I don't understand what you mean by code running for 30 seconds.

The code in an Arduino runs all the time. You can write your program in such a way that something happens for a period of time and then stops happening. But the code does not stop.

What should happen for 30 seconds?

Have a look at how millis() is used to manage timing in Several Things at a Time.

And see Using millis() for timing. A beginners guide if you need more explanation.


I am going to suggest that Robin2 is right. The code runs as long as the Arduino is powered.

I am also going to suggest that you are not describing your requirement accurately.

Perhaps, what you mean is that when the button is pushed, you want to count pulses for 30 seconds to get a good average. At the end of 30 seconds stop counting, perform the math to turn the number of pulses into a wind speed and display that resulting wind speed somewhere.
Then start looking for the next button push.

I am just guessing. This is your project and only you know the actual goal. Whether my guess is accurate or not, please do work on giving us a better understanding of what you want.

if (button is pressed and not counting)
  counting = true
  timeStarted = millis()

if (counting)
  if(millis() - timeStarted > countDuration)
    counting = false

I don't immediately see the value of averaging wind speed over a period as long as 30 seconds. The wind speed can change up and down a lot in that period of time and because the energy in the wind varies with the square of the speed you will probably be missing a lot of useful information.