Please help, I am trying to rewrite the following code for an Ultrasonic writing and reading directly to the ports and bypassing the usage of PulseIn. Reason is, I have a time critical application and do not want the program to pause or wait for a state change of a pin.
Not really sure what you're doing, but for this you might have problems:
delayMicroseconds(2);
"This function works very accurately in the range 3 microseconds and up. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times."
You could attach a simple interrupt to the pin.
The interrupt service routine would simply save the value of "micros" when the trailing edge of the echo pulse is detected.
AWOL:
You could attach a simple interrupt to the pin.
The interrupt service routine would simply save the value of "micros" when the trailing edge of the echo pulse is detected.
Interesting, will I have to use pin 2 or 3 or can I used the existing pin 4?
On an Atmega328 you would normally use pins 2 or 3. Also the attachInterrupt method has a delay of about 3.5 uS before the interrupt routine is entered, due to the number of registers being saved.
PORTD = ~(1<<5);
You know you are changing all 8 bits (ports) here, right? Is that the intention? That is Arduino pins 2, 3, 4, 5, 6, 11, 12, 13.