I should have a value of 250uS. But the serial monitor is showing differently. its like the micros() are not incrementing or something in between pulses.
i just want the time between the last 2 . So for example there a falling edge just happen, i would like to know the time between the falling edge that just happened and the previous one. Just like my first image, i should always get a result of about 248us
Variables used in both interrupt and non-interrupt context must be qualified as volatile, otherwise the optimiser may assume they don't / cannot change.
Also as noted, you cannot access anything wider than a byte atomically, so you must disable interrupts and copy them in non-interrupt context
The processor has an eight bit data bus, so cannot access 32 bit values in a single instruction cycle.
This means the value of the variable could change while it is being read, if interrupts are not disabled.
That is fine, but it does not answer the question of how you know when the last one occurred. OR are you wanting to know the time between ANY two falling edges?
It has to be between the latest and the previous. If a new one arrive , it has to be between the new one and its previous
Assuming falling edge A,B,C,D,
When falling edge B is detected, i need to have the time between A and B. when falling edge C is detected, i need to have the time between C and B. When falling edge D is detected i need the time between D and C. So on and so forth.
The falling edges dont have a stable frequency (in my image above it was only a test signal). What is important to me is the time between the current to its previous.
This is exactly wrong. An ISR should be a small as possible.
bool z; //Global variable
void isrX(){
z = true;
}
That is untested code and probably wrong, but you get the point.
Somewhere in your loop, you test z
if(z) {
//process the interrupt
z=false;
}
Also, all those Serial.prints take some time which is why you never want Serial.print in an ISR. (And Serial.print itself uses interrupts but your ISR has suspended interrupts).
As mentioned
You need a critical section in the loop to make a. Copy and work on the copy
void loop() {
if (gotAFront) {
noInterrupts();
// critical, time-sensitive code here
uint32_t lastCopy = lastFront;
gotAFront = false;
interrupts();
Do stuff with the copy
}
// other code here
}