OpenMV H7 and HC-SR04

I’m trying to connect the HC-SR04 Sensor to a robot for distance calculation. I keep getting that the distance is 0.0 cm for some reason. The code is below. VCC is connected to 5V, GND to GND, TRIG to P9 and ECHO to P4.

import sensor, image, time, car, pyb, utime
from pid import PID
from pyb import Pin, Timer

def dist() :
    trig = Pin('P9', Pin.OUT_PP) #change as needed
    echo = Pin('P4', Pin.IN, Pin.PULL_DOWN)
    pulse_start = 0
    pulse_end = 0
    pulse_dur = 0
    while echo == 0:
        pulse_start = pyb.millis()

    print("Pulse start: ",pulse_start,"ms")
    while echo == 1:
        pulse_end = pyb.elapsed_millis(pulse_start)

    pulse_dur = pulse_end - pulse_start
    print("Pulse_dur: ", pulse_dur,"ms")

    pulse_dur = float(pulse_dur)

    distance = (pulse_dur * 34300) / 2

    #distance = round(distance, 2)
    return distance

desired_dist = 15 #centimeters roughly 6 inches
dist_pid = PID(p =1, i = .5, d = .25, imax = 100)

while(1) :
    actual_dist = dist()                             #find distance
    print("Distance: ", actual_dist, "cm")
    dist_error = desired_dist - actual_dist          # calc error
    print("Error: ", dist_error, "cm")
    dist_output = dist_pid.get_pid(dist_error, 1)    #use pid
    if dist_output > 100:
        dist_output = 100
    print("PWM: ", dist_output, "%"), dist_output)                #drive the car

Hi, you’d have to give us some pointer to issues with our code. We can’t debug a random sensor we don’t have driver support for.

Is there a specific thing going wrong?

There isn’t anything specific that I can tell, just curious why this code which was translated from Arduino to work with the H7. Don’t have access to an oscilloscope to verify that the outputs and inputs to the sensor are functioning correctly, but the code should work from what I can tell.

:slight_smile: All code should work. Please try to debug it line by line and let me know when you have a particular question about something not working like you expect.

Do you connect it to an external 5V output ? The camera doesn’t have a 5V output, also if the sensor’s I/O is 5V it won’t work.