How do I measure the time between voltage pulses accurately with an Arduino? For DIY EFI project!

Hi,

I'm trying to make a DIY electronic fuel injection system for a gasoline engine. I've got most of the things working but I struggle with trying to measure the time between two analog voltage pulses in order to calculate the current RPM of the engine. The signal I get from the engine looks like this:

When the engine is not running it just outputs a +5V signal. When it is running and the magnet on the flywheel passes the first sensor, it creates the first voltages drop (as you can see this in the picture at 1.). When the magnet on the flywheel passes the second sensor it creates the second voltages drop (which can be seen at 2. in the picture). The two sensors are spaced exactly 35° appart.

My question is; how can I with this signal measure the RPM of the motor using an Arduino? What would a script that could do that look like? I would like to use the two voltage drops (1. and 2. in the picture), spaced only a few milliseconds appart to calculate the RPM. It would also need to be quite accurate because the timing when the fuel injector opens is calculated from the current RPM. Therefore the refresh rate of the RPM counter would also need to be quite high.

I also apologize for any grammar mistakes I probably made. English is not my native language.

The simplest approach to measure those timings is to use input polling (fast digital reads) to determine the falling edges, and store the value of the built in microsecond timer.

This very simple, blocking code works to capture and time two falling edges, assuming input is on Port D, pin 2 (digital pin 2):

while( PIND&4);  //wait for LOW on digital pin 2
unsigned long start = micros();
while ( (PIND&4) == 0); //wait for HIGH
while (PIND&4); //wait for LOW
unsigned long pulse_time = micros()-start;

Use of interrupts is also possible, but for beginners, this creates more problems than it solves.

Take the time between two falling or raising edges. An Arduino can do much work within 12 ms.

For more precision, you can use the Input Capture feature of the UNO, Nano, Mini, Mega, Leonardo, or Micro. That will let you measure rising or falling edges with a precision of 1/16th microseconds. The 'micros()' function is limited to 4-microseconds precision and subject to various interruptions.

Example code for the Uno/Nano/Mini:

// Measures the HIGH width, LOW width, frequency, and duty-cycle of a pulse train
// on Arduino UNO/Nano Pin 8 (ICP1 pin).  

// Note: Since this uses Timer1, Pin 9 and Pin 10 can't be used for
// analogWrite().

void setup()
{
  Serial.begin(115200);
  while (!Serial);

  // For testing, uncomment one of these lines and connect
  // Pin 3 or Pin 5 to Pin 8
  // analogWrite(3, 64);  // 512.00, 1528.00, 2040.00, 25.10%, 490.20 Hz
  // analogWrite(5, 64);  // 260.00, 764.00, 1024.00, 25.39%, 976.56 Hz

  noInterrupts ();  // protected code
  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TIMSK1 = 0;

  TIFR1 |= _BV(ICF1); // clear Input Capture Flag so we don't get a bogus interrupt
  TIFR1 |= _BV(TOV1); // clear Overflow Flag so we don't get a bogus interrupt

  TCCR1B = _BV(CS10) | // start Timer 1, no prescaler
           _BV(ICES1); // Input Capture Edge Select (1=Rising, 0=Falling)

  TIMSK1 |= _BV(ICIE1); // Enable Timer 1 Input Capture Interrupt
  TIMSK1 |= _BV(TOIE1); // Enable Timer 1 Overflow Interrupt
  interrupts ();
}

volatile uint32_t PulseHighTime = 0;
volatile uint32_t PulseLowTime = 0;
volatile uint16_t Overflows = 0;

ISR(TIMER1_OVF_vect)
{
  Overflows++;
}

ISR(TIMER1_CAPT_vect)
{
  static uint32_t firstRisingEdgeTime = 0;
  static uint32_t fallingEdgeTime = 0;
  static uint32_t secondRisingEdgeTime = 0;

  uint16_t overflows = Overflows;

  // If an overflow happened but has not been handled yet
  // and the timer count was close to zero, count the
  // overflow as part of this time.
  if ((TIFR1 & _BV(TOV1)) && (ICR1 < 1024))
    overflows++;

  if (PulseLowTime == 0)
  {
    if (TCCR1B & _BV(ICES1))
    {
      // Interrupted on Rising Edge
      if (firstRisingEdgeTime)  // Already have the first rising edge...
      {
        // ... so this is the second rising edge, ending the low part
        // of the cycle.
        secondRisingEdgeTime = overflows; // Upper 16 bits
        secondRisingEdgeTime = (secondRisingEdgeTime << 16) | ICR1;
        PulseLowTime = secondRisingEdgeTime - fallingEdgeTime;
        firstRisingEdgeTime = 0;
      }
      else
      {
        firstRisingEdgeTime = overflows; // Upper 16 bits
        firstRisingEdgeTime = (firstRisingEdgeTime << 16) | ICR1;
        TCCR1B &= ~_BV(ICES1); // Switch to Falling Edge
      }
    }
    else
    {
      // Interrupted on Falling Edge
      fallingEdgeTime = overflows; // Upper 16 bits
      fallingEdgeTime = (fallingEdgeTime << 16) | ICR1;
      TCCR1B |= _BV(ICES1); // Switch to Rising Edge
      PulseHighTime = fallingEdgeTime - firstRisingEdgeTime;
    }
  }
}

void loop()
{
  noInterrupts();
  uint32_t pulseHighTime = PulseHighTime;
  uint32_t pulseLowTime = PulseLowTime;
  interrupts();

  // If a sample has been measured
  if (pulseLowTime)
  {
    // Display the pulse length in microseconds
    Serial.print("High time (microseconds): ");
    Serial.println(pulseHighTime / 16.0, 2);
    Serial.print("Low time (microseconds): ");
    Serial.println(pulseLowTime / 16.0, 2);

    uint32_t cycleTime = pulseHighTime + pulseLowTime;
    Serial.print("Cycle time (microseconds): ");
    Serial.println(cycleTime / 16.0, 2);

    float dutyCycle = pulseHighTime / (float)cycleTime;
    Serial.print("Duty cycle (%): ");
    Serial.println(dutyCycle * 100.0, 2);

    float frequency = (float)F_CPU / cycleTime;
    Serial.print("Frequency (Hz): ");
    Serial.println(frequency, 2);
    Serial.println();

    delay(1000);  // Slow down output

    // Request another sample
    noInterrupts();
    PulseLowTime = 0;
    interrupts();
  }
}

It’s worth having a look at how other open source projects get timing information - for example Megajolt

Never would have suspected if you'd said nothing. Certainly the best English of anyone claiming it as a second (or not first) language on these fora.

a7

If there are 40 samples in a circle, I need to correctly output the RPM information. do we need to counting 40 time in the ISR ?would you please share how to update the code? any comments or suggestion will be great appreciate.

I posted this code a while ago
my encoder has 400 pulses per revolution


#define ClockPin 3 // Must be pin 2 or 3
//#define DataPin 9 // can be any other pin

      // My Encoder has 400 Clock pulses per revolution
      // note that 150000.0 = (60 seonds * 1000000 microseconds)microseconds in a minute / 400 pulses in 1 revolution)
      // change the math to get the proper multiplier for RPM for your encoder
     // yours has 4 pulses in 1 revolution
      // note that 150000.0 = (60 seonds * 1000000 microseconds)microseconds in a minute / 4 pulses in 1 revolution)
#define Multiplier 15000000.0 // don't forget a decimal place to make this number a floating point number
volatile long count = 0;
volatile long EncoderCounter = 0;
volatile int32_t dTime; // Delt in time
volatile bool DataPinVal;

void onPin2CHANGECallBackFunction(){ 
    static uint32_t lTime; // Saved Last Time of Last Pulse
    uint32_t cTime; // Current Time
    cTime = micros(); // Store the time for RPM Calculations
    
/*
// Encoder Code
    DataPinVal = digitalRead(DataPin);
// We know pin 2 just went high to trigger the interrupt
// depending on direction the data pin will either be high or low
    EncoderCounter += (DataPinVal) ? 1 : -1; // Should we step up or down?
// End Encoder Code
*/
// calculate the DeltaT between pulses
    dTime = cTime - lTime; 
    lTime = cTime;

}


void setup() {
  Serial.begin(115200); //115200
  // put your setup code here, to run once:
  pinMode(ClockPin, INPUT);  
//  pinMode(DataPin, INPUT);
  attachInterrupt(digitalPinToInterrupt(ClockPin),onPin2CHANGECallBackFunction,RISING);
}

void loop() {
//  long Counter;
// bool DataPinValue
  float DeltaTime;
  float SpeedInRPM = 0;
  noInterrupts (); 
// Because when the interrupt occurs the EncoderCounter and SpeedInRPM could be interrupted while they 
// are being used we need to say hold for a split second while we copy these values down. This doesn't keep the 
// interrupt from occurring it just slightly delays it while we maneuver values.
// if we don't do this we could be interrupted in the middle of copying a value and the result get a corrupted value.
//  Counter = EncoderCounter;
// DataPinValue = DataPinVal;
  DeltaTime = dTime;
  interrupts ();
 //   SpeedInRPM = Multiplier / ((DataPinValue) ? DeltaTime: (-1 * DeltaTime)); // Calculate the RPM Switch DeltaT to either positive or negative to represent Forward or reverse RPM
    SpeedInRPM = Multiplier / DeltaTime; // Calculate the RPM Switch DeltaT to either positive or negative to represent Forward or reverse RPM
// use the speed and counter values for whatever you need to do.

  static unsigned long SpamTimer;
  if ( (unsigned long)(millis() - SpamTimer) >= (100)) {
    SpamTimer = millis();
 //   Serial.print(Counter );
 //   Serial.print("\t");
    Serial.print(SpeedInRPM , 3);
    Serial.print(" RPM");
    Serial.println();
    SpeedInRPM = 0; // if no pulses occure in the next 100 miliseconds then we must assume that the motor has stopped
  }
}

Hope this helps

ZHomeSlice

@sheep060

Try the following setup (Fig-1) and the sketch; where, the two falling edges coming from the sensors are interrupting the MCU. The MCU measures the time interval between the two interrupts and then calculates the RPM based on the information given in post #1.

int0int1
Figure-1:

Sketch (Not tested but compiled)

volatile bool flag1, flag2;

void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), ISRZ, FALLING);
  attachInterrupt(digitalPinToInterrupt(3), ISR1, FALLING);
  //----------------
  TCCR1A = 0x00;
  TCCR1B = 0x00;
  TCNT1 = 0x0000;
}

void loop() 
{
  if(flag1 && flag2)
  {
    int rpm = (int)1000*0.5820*TCNT1*0.0625;
    Serial.print("The RPM is: ");
    Serial.println(rpm);
    flag1 = false;
    flag2 = false;
  }
}

void ISRZ()
{
  flag1 = true;
  TCCR1B = 0x01;  //Start timeCounter
}

void ISR1()
{
  if(flag1 == true)
  {
       flag2 = true;
       TCCR1B = 0x00;  //stop timeCounter
  }
}

I like your method @GolamMostafa

Would the following be appropriate alterations?

Changing
int rpm = (int)1000*0.5820*TCNT1*0.0625;
to
int rpm = (int)(36.375 * TCNT1); // 36.375 = 1000*0.5820*0.0625

and adding cli() and sei() to prevent interruptions that could cause TCNT1to change or, does it matter?

cli();  // Stopps interruptions of this code.
rpm = (int)(36.375 * TCNT1);
sei(); // Allows interruptions to resume

I have a question about:

TCCR1B = 0x01;  //Start timeCounter
TCCR1B = 0x00;  //stop timeCounter

What causes the timer1 TCNT1 to start over?
Thanks
ZHomeSlice

1.

I have kept it factored so that 36.75 does not appear as a magic number to the OP.

2.

This is a good/recommended practice while dealing with a critical section.

3.

The TCNT1 is restarted in ISRZ() when the falling edge of Sensor-1 occurs.

4.

5.
Do you think that an averaging of readings is necessary for stable RPM display over a minute? This is missing in my sketch of post #9.

This method may work if the RPM is above 1000. If the RPM is 1000, the time interval between two falling edges is: 5.28 ms. If TCNT1 is running at prescale 1, it will have to count 16000000x.00582 = 93120 which is greater than its capacity of 65535.

would this help?

If we caught the overflow from timer 1 then we could get a much lower rpm

volatile uint16_t timer1OverflowCount = 0;
ISR(TIMER1_OVF_vect) {
    timer1OverflowCount ++;
}

then

int rpm = (int)(36.375 * (timer0_overflow_count << 8) +TCNT1));

void ISRZ()
{
  flag1 = true;
   timer1OverflowCount = 0;
  TCCR1B = 0x01;  //Start timeCounter
}

I'm not that great at the timer stuff but I would like to use your method instead of micros() in my example and other code as it relates to the original post.

ZHomeSlice

===> int rpm = (int)(36.375 * (timer1OverflowCount*65536U +TCNT1));

volatile uint16_t timer1OverflowCount = 0;
volatile bool flag1, flag2;

void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), ISRZ, FALLING);
  attachInterrupt(digitalPinToInterrupt(3), ISR1, FALLING);
  TIMSK1 |= (1 << TOIE1);  //TC1 overflow interrupt is enabled
  //----------------
  TCCR1A = 0x00;
  TCCR1B = 0x00;
  TCNT1 = 0x0000;
}

void loop()
{
  if (flag1 && flag2)
  {
    int rpm = (int)1000 * 0.5820 * (timer1OverflowCount * 65536U + TCNT1) * 0.0625;
    TCNT1 = 0;
    timer1OverflowCount = 0;
    Serial.print("The RPM is: ");
    Serial.println(rpm);
    flag1 = false;
    flag2 = false;
  }
}

void ISRZ()
{
  flag1 = true;
  TCCR1B = 0x01;  //Start timeCounter
}

void ISR1()
{
  if (flag1 == true)
  {
    flag2 = true;
    TCCR1B = 0x00;  //stop timeCounter
  }
}

ISR(TIMER1_OVF_vect)
{
  timer1OverflowCount ++;
}

@GolamMostafa The only thing we are missing is resetting the timer1OverflowCount variable. Did I put it in the correct spot?

//===> int rpm = (int)(36.375 * (timer1OverflowCount*65536U +TCNT1));

volatile uint16_t timer1OverflowCount = 0;
volatile bool flag1, flag2;

void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), ISRZ, FALLING);
  attachInterrupt(digitalPinToInterrupt(3), ISR1, FALLING);
  TIMSK1 |= (1 << TOIE1);  //TC1 overflow interrupt is enabled
  //----------------
  TCCR1A = 0x00;
  TCCR1B = 0x00;
  TCNT1 = 0x0000;
}

void loop()
{
  if (flag1 && flag2)
  {
    int rpm = (int)1000 * 0.5820 * (timer1OverflowCount * 65536U + TCNT1) * 0.0625;
    TCNT1 = 0;
    timer1OverflowCount = 0;
    Serial.print("The RPM is: ");
    Serial.println(rpm);
    flag1 = false;
    flag2 = false;
  }
}

void ISRZ()
{
  flag1 = true;
  timer1OverflowCount = 0; // We need to reset the overflow along with TCNT1
  TCCR1B = 0x01;  //Start timeCounter
}

void ISR1()
{
  if (flag1 == true)
  {
    flag2 = true;
    TCCR1B = 0x00;  //stop timeCounter
  }
}

ISR(TIMER1_OVF_vect)
{
  timer1OverflowCount ++;
}

The reset of timer1OverflowCount should be be done in the loop() function after computing the rpm. See post #14.

@GolamMostafa
I'm digging into timer 1 :slight_smile: I'm not completely familiar with the differences per pulse between the two but comparing the actual Arduino micros() Function with our code I see the following concern:
Another thought about the math... on a 16MHz mpu like the atmega328p every clock tick = 4 microseconds
does your math account for that?
The Micros function has the following in its function to do just that
m = overflow counter
t = timer0 value
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());

ZHomeSlice

1. Clock Tick means the period of one clock pulse which is for 16 MHz UNO Board:
= 1/16000000 = .0625 us

2. Let us carry out the following experiment to very the method by measuring the time interval (500 ms) between the falling edges of signals marked Ch-A and Ch-B in Fig-1. Signals at Ch-A (non-invert) and Ch-B (invert) are of opposite polarity and synchronized, which being generated using TC1 in Fast PWM Mode-14.
int0int1-1HzPWM
Figure-1:

Sketch:

volatile unsigned long timer2OverflowCount = 0;
volatile bool flag1, flag2;
volatile byte myCount = 0;

#define OC1A 9
#define OC1B 10

void setup()
{
  Serial.begin(9600);
  //-------------------------
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), ISRZ, FALLING);
  attachInterrupt(digitalPinToInterrupt(3), ISR1, FALLING);
  TIMSK2 |= (1 << TOIE2);  //TC1 overflow interrupt is enabled
  //----------------
  TCCR2A = 0x00;
  TCCR2B = 0x00;
  TCNT2 = 0x00;
  //-------generating Ch-A and Ch-B signals-------------
  pinMode(OC1A, OUTPUT); //Ch-A
  pinMode(OC1B, OUTPUT); //Ch-B

  TCCR1A = 0x00;   //reset
  TCCR1B = 0x00;   //TC1 reset and OFF
  //fOC1A = clckSys/(N*(1+ICR1)); Mode-14 FPWM; OCR1A controls duty cycle
  // 1 Hz = 16000000/(64*(1+ICR1)) ==> ICR1 = 62499, N = 256

  TCCR1A |= (1 << COM1A1) | (0 << COM1A0);  //Ch-A non-inverting, Mode-14
  TCCR1A |= (1 << COM1B1) | (1 << COM1B0); //Ch-B inverting
  TCCR1A |= (1 << WGM11);
  TCCR1B |= (1 << WGM13) | (1 << WGM12);
  ICR1 = 62499;  //changes frequency as ICR changes
  OCR1A = 31250;   //~= 50% duty cycle
  OCR1B = 31250;
  TCCR1B |= (1 << CS12); //N = 256
  //-------------------
  TCCR2B = 0x01;  //Start timeCounter /1
}

void loop()
{
  if (flag1 && flag2)
  {
    noInterrupts();
    Serial.print("Total Count = ");
    unsigned long totalCount = timer2OverflowCount * 256 + TCNT2;
    Serial.println(totalCount);
    Serial.print("Time between two falling edges = ");
    Serial.print(totalCount*0.0625*0.001, 2);
    Serial.println(" ms");
    Serial.println("================================================");
    TCNT2 = 0;
    timer2OverflowCount = 0;
    interrupts();
    flag1 = false;
    flag2 = false;
  }
}

void ISRZ()
{
  flag1 = true;
  TCCR2B = 0x01; //start N = 1
}

void ISR1()
{
  if (flag1 == true)
  {
    flag2 = true;
    TCCR2B = 0x00;  //stop timeCounter
  }
}

ISR(TIMER2_OVF_vect)
{
  timer2OverflowCount++;
}

Output:

=======================
Total Count = 7999748
Time between two falling edges = 499.98 ms
=======================

3. Change the frequency to 2 Hz and check that the display shows: ~-250 ms.
Output:

================================================
Total Count = 3999748
Time between two falling edges = 249.98 ms
================================================

@GolamMostafa

Thank You :grinning:

The latest example was Extremely helpful!
While @sheep060 's tachometer is different with 2 separate pulses while mine is an encoder with clock and data pins the end result is the same and I can use your latest example to fine-tune my NEW version. I'll shortly start a new post and tag you in it as your assistance has been extremely helpful.
ZHomeSlice