Measuring duration of a pulse?

I am trying to use an ultrasonic sensor with the maix bit, but I’m not sure how to measure the duration of the pulse sent back by the sensor. Does anyone have any suggestions?

The gpiohs pins can trigger an interrupt with a level change. You can have one interrupt at the start of the puls that starts a timer and a second interrupt at the end of the pulse that stops the timer.

edit:
Although the basic idea is OK it is not so easy to implement in the standalone SDK. Are you using the SDK or are you using MaixPy? I am not very familiar with MaxPy but if there is a timer available you may be able to start it when a pin gets a certain value and stop it when it changes value. You could use active polling for that.

I think I have made something you could use if you use the standalone SDK, see here.

It is meant for measuring the period, pulse length and duty cycle of PWM signals. If a PWM signal of period 1 ms and pulse width of 0.5 ms is used (duty cycle is 0.5), the output looks like this:

period=830 pulse_width=410 duty_cycle=0.493976
period=835 pulse_width=405 duty_cycle=0.485030
period=830 pulse_width=410 duty_cycle=0.493976
period=836 pulse_width=410 duty_cycle=0.490431
period=830 pulse_width=410 duty_cycle=0.493976

This means it actually comes up a bit short (it should have given a period of 1000 and a pulse width of 500, both measured in microseconds).

It can also be used to measure the width of a pulse without assuming a PWM signal, see main.cpp. When the input signal is a pulse of 10ms, 5 seconds silence, then a pulse of 25ms and then again 5 seconds of no pulses, the output looks like this:

Pulse width = 20833
Pulse width = 8179
Pulse width = 20456
Pulse width = 8181
Pulse width = 20835
Pulse width = 8333

Again, the measured times are a bit too short (it should have been alternating 25000 and 10000 microseconds). I am sure you can compensate or calibrate for this.

SEE NEXT POST!

1 Like

Of course the standalone SDK has a proper clock, you just have to look for it in the right place. The file ‘sysctl.h’ shows you can access a clock that produces micro seconds: sysctl_get_time_us()
I have updated the github code.

I’ve been using MaixPy so far, I suspect this is going to be something where I need to use the standalone SDK. I’m going to give your interrupt idea a try though, and see what I get from it. Thanks!

I haven’t looked at MaixPy yet, but micropython has interrupts for gpio pins and has a clock. So, in principle it should be possible if MaixPy has the same or similar functionality.