Blockly with HC-SR04 and servo


Senior Member
Hi everyone, I am trying to create a program for a robot which uses an HC-SR04 ultrasonic sensor and an SG90 servo. I've got the HC-SR04 reading values reliably after tweaking the timing and clock speed a bit (values are about 1.5 inches off but that can easily be compensated for using simple arithmetic). The problem is when I introduce the IF structure. The timing gets thrown off and in between readings I get some zero values. Ultimately, I would like to do a sweep with the servo when the distance is less than 2, then store the values in variables and calculate the best path to travel, but the servo is getting false triggered with the zero values. Is there something I can do to fix the timing? I have tried different clock speeds, delays, etc. but none seem to fix the problem. I have attached an image of the Blockly program. When I disable the IF blocks, the program works as intended. When I enable them, I get multiple zero values in between readings.



Senior Member
Could the problem be that the HC-SR04 is not reliable at reading short distances, that these default to zero, or the only values less than 2 are 1 or 0 ?

It might be best to deal with just raw reading values, or converted to millimetre rather than inches.

It could also be something to do with the servo still moving when the distance reading is taken, or there not being a prerequisite 20ms or whatever delay between readings.


Senior Member
Not a Blockly user, but I get conflicts in BASIC whenever I use ULTRA and SERVO commands together.