Hello everyone, to learn to use the bsp I’m trying to develop various libraries for sensors. I’m trying to use an HC-SR04. It needs a 10us pulse on the trigger pin, and I’m using the example from the sifive-welcome project.
The problem is that the delay is not timed right, in fact if I try to delay 1s, it misses it by 2 to 5ms.
I’m using the given frequency of 32768Hz and this function to delay:
void wait_for_timer() {
// clear global timer isr flag
timer_isr_flag = 0;
// Set timer
metal_cpu_set_mtimecmp(cpu, (metal_cpu_get_mtime(cpu) + RTC_FREQ));
// Enable Timer interrupt
metal_interrupt_enable(tmr_intr, tmr_id);
// wait till timer triggers and isr is hit
while (timer_isr_flag == 0){};
timer_isr_flag = 0;
}
Make sure you run ALL the code (including the timing code) at least once before you do any actual timing, otherwise you’ll be affected by the very slow loading of code from SPI flash into the icache.
Wow, I seem to be working on the exact same problem on the exact same day as you! Also working on an HC-SR04. As far as I have figured out, I think the real-time clock won’t work, as it has a frequency of 32,768 Hz (or a period of ~30 microseconds), which is much too slow for getting a 10 microsecond pulse or for measuring the duration of the echo pulse.
These are other resources in this forum that may be of (minor) help:
I’m trying to use PWM as suggested by @Jim, you should try too. The only problem is that I can’t figure out how the PWM gpios are set. pwm2_0 should be GPIO_10 or pin 16, as per datasheet, but Thruthfully it seems to be GPIO_13 or pin 19