How to use software interrupt if an event occurs?

I have started learning Arduino less than a month ago, so I am quite new to this.
I am using an Arduino Mega & my application is -

I am using a 250 ppr incremental rotary encoder (I have used the Encoder.h library and used interrupts 2 & 3). I am using another sensor (trigger input) using hardware interrupt pin 18.

When the sensor output to my Arduino goes high, I want to note the encoder position at that point (position) & then after a certain amount of pulses (interval = 40 pulses), turn a digital output on for 10ms.

The following code is working, however, the output is missed sometimes, when the encoder is slightly fast.

#include <Encoder.h>
volatile long readVal;
int interval = 40;
int ip = 18;
volatile long position;

Encoder myEnc(2, 3);

void setup() {

  Serial.begin(9600);
  pinMode(ip, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(18), trigger, RISING);
}

void loop() {
  readVal = myEnc.read();
  Serial.println(readVal);

  if (readVal - position == interval) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(10);
    digitalWrite(LED_BUILTIN, LOW);
  }
}

void trigger() {
  position = readVal;
}

I wanted to know if I can get the Arduino to generate an internal interrupt when the "readVal - position" actually exactly equals the interval value. This would help me trigger my camera (through the digital output) at the exact same position every time.

Any help is very much appreciated. Thank you.

next time please post code that complies.

Not tested and not verified but a different concept then what was posted. I commented out the code that will not compile because of not posting the entire code.

//#include
volatile bool intTriggered = false;
bool lampOn = false;
long readVal;
int interval = 40;
int ip = 18;
long position;
unsigned long onTimeLamp = 10;
unsigned long lampPastTime = millis();

//Encoder myEnc(2, 3);

void setup() 
{
  Serial.begin(9600);
  pinMode(ip, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(18), trigger, RISING);
} //void setup()
////
void loop()
{
  if (intTriggered )
  {
    //readVal = myEnc.read();
    position = readVal;
    Serial.println(readVal);
    intTriggered = false;
    lampOn = true;
    if (readVal - position == interval)
    {
      digitalWrite(LED_BUILTIN, HIGH);
      lampPastTime = millis();
    }
  }
  if ( (millis() - lampPastTime) >= onTimeLamp )
  {
    digitalWrite(LED_BUILTIN, LOW);
  }
} //vloid loop()
////
void trigger()
{
  //position = readVal;
  if ( intTriggered == false )
  {
    intTriggered = true;
  }
} //void trigger

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.