Square wave based on falling edge of alternative pulse of upcoming RPM square wave In my recent project, I have RPM Square wave from vehicle. Now, based on that I want square wave based on falling edge but only alternative pulse of RPM square wave.

I think below image clear more properly. 



Upper yellowish square wave which I need. And below pinkish square wave is RPM square wave.

I made a code for that and it's working fine but when RPM is stable. But when RPM change rapidly then it's not working fine.

const int kPinRPM = 3;        // RPM / Digital Pin 3
const int RPMInterrupt = 1;   // RPM's interrrupt pin
byte engineCylinders = 2;         // Engine cylinders = 4;
byte engineCycles = 4;            // Engine cycle = 2
int refreshInterval = 750;        // Milliseconds between sensor updates
unsigned long previousMillis = 0;
volatile int RPMpulses = 0;
int RPM, Final_RPM;

const int kPinInj = 12;

volatile uint32_t kInjTime = 0;

void setup()
{
  Serial.begin(250000);

  pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
  attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

  pinMode(kPinInj, OUTPUT);  
}

void loop()
{
  if(millis() - previousMillis &gt; refreshInterval)
  {
    previousMillis = millis();
    RPM =  getRPM();
  }

  Serial.println(RPM);

  if((kInjTime &gt; 0) &amp;&amp; ((millis() - kInjTime) &gt;= 10))
  {
    kInjTime = 0;
    digitalWrite(kPinInj, LOW);
  }
}

void countRPM()
{
  RPMpulses++;

  if(RPMpulses % 2 == 0)           // Skip alternative pulse
  {
    kInjTime = millis();
    digitalWrite(kPinInj, HIGH);
  }
}

int getRPM()
{
  Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
  RPMpulses = 0;
  Final_RPM = min(99999, Final_RPM);
}


After SUGGESTION, updating my codes. But it output waveform has some problem. In white circle, you can see that problem.
There are some things you shouldn't be doing within an interrupt service routine (ISR) like countRPM():


Don't call the millis() function. It depends on other interrupts which will be disabled during the execution of your ISR.
Don't call digitalWrite or any other functions
Don't use execution cycles hungry operators like % (modulo). To obtain modulo 2, just use a bit mask for the LSB.


What you should actually be doing within the ISR is just setting/resetting a flag or variable. Then, do all your stuff in the loop() function according the value of the flag or variable.