piratadelestrecho:
from time to time the sensor gets a 0 value
This seems to be an issue inherent to this family of sensors. I have worked with two HC-SR04s and one HY-SRF05, and each of them sometimes throws anomalous results. I have applied a "digital filter" to compensate for this behavior. Basically, wait for N similar results in a row before trusting the value. The sensors do lie occasionally, and your code should compensate for that.