Spikes using HC-sr04

You would not need to set the pinMode() each iteration of loop but only once in setup().
You may also want to limit your calculation when microseconds is non-zero as this could indicate the case that no ping was received.
You should also be aware that you may well receive stray echoes or even surrounding noise may trigger the input (e.g. my car’s parking sensors sometimes trigger when I’m stood at traffic lights next to a HGV for their noise). Hence you may consider some filtering and some extra delays between two measurements (e.g. 50ms).

2 Likes