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.