Serial printing() in interrupt code with interrupts OFF is kind of asking for trouble.
Paul
You have a FALLING interrupt. Why do you expect that a digitalRead() of the interrupt pin inside the ISR will be anything other than 0?
@Paul_KD7HB suggested I do that. I’m not sure I get what you’re saying. But then I’m very new to this.
I don't think so. The fact that the interrupt occurred proven that your interrupt code is being executed is all you need. When that part of the code is done, interrupts are enabled to wait for the next time the signal on the pin will go LOW.
Paul
Code that checks pins is said to be polling (asking, reading) for data.
Interrupt code acts when data arrives.
Your code does... both.
If you are going to be using interrupts, this tutorial is one of the best there is https://gammon.com.au/interrupts
Some general principles are:
Any variables changed within the ISR (interrupt service routine) need to be declared as volatile. Accessing the value of variables which are larger than one byte (255) require protection so they are not read while changing. Serial printing or any thing requiring other interrupts(like delay()) should not be done inside an ISR because interrupts are suspended inside the ISR.
Accordingly, your program can be changed as follows. It's not clear to me if your variables want to be signed or unsigned.
const int sensor = 23;
volatile int perf = 0;
volatile int var = 0;
volatile int frame_counting = 0;
volatile boolean newFrame = false;
void setup() {
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(sensor), count, FALLING);
}
void count() {
// if(digitalRead(sensor) > var)
//{
//var = 1;
perf++;
if ((perf % 4) == 0) {
frame_counting++;
newFrame = true;
}
//Serial.print(frame_counting);
//Serial.print(" frame");
//Serial.println(" detected.");
}
//}
//if (digitalRead(sensor) == 0) {
// var = 0;
//}
//delay(1);
//}
void loop() {
if (newFrame)
{
newFrame = false;
noInterrupts();
int copyFrameCounting = frame_counting;
interrupts();
Serial.print(copyFrameCounting);
Serial.print(" frame");
Serial.println(" detected.");
}
}
Thanks very much @cattledog for the code explanation /modification and the link. Really appreciate it.
Will read up on this while in the dentist chair ![]()
You've come a long way.