I am writing the code for an ultrasonic sensor for my diy car for an Arduino Pro Mini. I am using interrupts to obtain the two micros() of the echo pin of the HC-SR04. But I can't do calculations with it.
The problem is not with maths, instead with programming errors and poor structure.
Use of interrupts is completely unnecessary for this application, and introduces problems with event sequencing and variable mangling (for example, a multibyte variable can be changed by the interrupt, halfway through being accessed by the main code).
Variables shared between interrupt and non-interrupt code MUST be declared volatile (echo_end).
Or it will fail at wrap-around. The subtraction is the key step.
You are not sampling the ISR variables in a critical section:
noInterrupts() ;
unsigned long start = echo[0] ;
unsigned long end = echo[1] ;
interrupts() ;
This will give you unmanged and matching values of the two timestamps. Your existing
code is reading each several times while interrupts are still flying about - so you'll get
junk readings even without the mangling issue.
jremington:
The problem is not with maths, instead with programming errors and poor structure.
Use of interrupts is completely unnecessary for this application, and introduces problems with event sequencing and variable mangling (for example, a multibyte variable can be changed by the interrupt, halfway through being accessed by the main code).
Variables shared between interrupt and non-interrupt code MUST be declared volatile (echo_end).
Thanks for your reply.
The problem I encountered when not using interrupts is that the ultrasonic sensor sometimes will return a pulse of a few thousand milliseconds long if the sound wave cannot be received properly. If I were to not use interrupts, it would stop other processes of my car for that period of time and I would lose control of it from my remote.
P.S. There are other parts of my program that I have excluded since they are irrelevant to this problem, thus I have accidentally deleted the void loop(), sorry for that.
Yom092090:
The problem I encountered when not using interrupts is that the ultrasonic sensor sometimes will return a pulse of a few thousand milliseconds long if the sound wave cannot be received properly.
pulseIn() is blocking indeed, if no pulse is received it times out after 1 second. You should never get longer than that.
Use the third parameter: the timeout. Set it to a sensible length (e.g. if you never expect to measure more than 1 meter, set it to the time it takes for sound to travel 2-3 meters).