# Delay() in loop while using interrupts to increment counter

Hey all, I'm measuring the RPM of an engine shaft. I have a hall effect sensor (http://www.digikey.com/product-detail/en/SS451A/480-3587-ND/2505488?itemSeq=142873507&uq=635256434494687772) that I got and a disk with 4 magnets on it that is mounted on the engine shaft.

I wrote the following code. There is a delay of 1 second, during which the interrupt is attached. When that 1 second is over, the delay should stop, the interrupt should be detached and then the RPM is calculated using the incremented counter. My question is, will that Delay() count time correctly if it is constantly interrupted by the interrupt?

The engine spins up to 4000RPM, with 4 magnets crossing over the hall effect sensor every revolution.

Thanks.

``````//RPM variables (all INT)
unsigned int rpm1 = 0; //the actual "RPM" value that gets displayed
volatile unsigned int rpmcount1 = 0; //the counter used in the interrupt function

void setup()
{
pinMode(2, INPUT);
digitalWrite(2, HIGH); //internal pull-up resistor

attachInterrupt(0, rpm_Sensor1, FALLING);

Serial.begin(9600);
}

void loop () {

detachInterrupt(0);

rpm1 = rpmcount1 * 15;  //using 4 magnets on wheel
//****Don't forget to change the value of delay()

Serial.println(rpm1);

rpmcount1 = 0; //restart the RPM counter

attachInterrupt(0, rpm_Sensor1, FALLING);

}

void rpm_Sensor1()
{
rpmcount1++;
}
``````

Yes

Mark

4000RPM with 4 edges per round makes around 270Hz for the interrupt signal. You can calculate the RPM immediately without waiting a second by just measuring the microseconds between two edges.

``````volatile uint16_t rpm1 = 0; //the actual "RPM" value that gets displayed
uint32_t last_micros = 0; //keep the time
void setup()
{
pinMode(2, INPUT);
digitalWrite(2, HIGH); //internal pull-up resistor

attachInterrupt(0, rpm_Sensor1, FALLING);

Serial.begin(9600);
}

void loop () {

Serial.println(rpm1);

}

void rpm_Sensor1()
{
rpm1 = 15000000L / (micros() - last_micros());
last_micros = micros();
}
``````

Depending on your hardware accuracy you might need to average the result over a few cycles.

Pylon, could you explain how you got the following line? Particularly the value 15000000. `rpm1 = 15000000L / (micros() - last_micros());`

phatjo911: Pylon, could you explain how you got the following line? Particularly the value 15000000. `rpm1 = 15000000L / (micros() - last_micros());`

1Rev per second (60RPM) will have 4 pulses per second or one every 250000 microseconds. 250000* 60 =15000000