Library 30- Measure distance with HC-SR04 and STM32F4

I have at least 10 HC-SR04 sensors at home so I decided to made a library for it. This sensor can measure distance between 2cm and 4meters. It can produce about 40 measurements per second. His working angle is about 15degrees,

On the start, you have to send 10us starting pulse at TRIGGER pin. After that, on ECHO pin high pulse is returned in relation to the distance. Large distance means large high signal.

You have to give sensor some time after you make a conversion. If not, some measurements may be currupted.

Sensor can be used in a lot of projects, like autonomous robot or something like that.

Library

Features

  • Measure distance with HC-SR04 sensor
    • Number of sensors depends on available GPIO pins on STM32F4 device package
  • Checks if sensor is connected

Dependencies

  • CMSIS
    • STM32F4xx
    • STM32F4xx RCC
    • STM32F4xx GPIO
  • TM
    • TM DELAY
    • TM GPIO
    • defines.h

Functions and structure

Two simple functions are used to work with sensor.

Example

Example was tested on my all 3 STM32F4 boards. Everytime same result.

Project is available on my Github account, download library below.

Icon
TM STM32F4 HC-SR04 Library

tilz0R

Owner of this site. Also electronic enthusiasts, web developer, 3D printer fan, handball player and more. Big fan of STM32F4 devices. In anticipation of the new Discovery board for STM32F7 lines.

You may also like...

Read before commenting!

Before you make a new comment, make sure you agree with things listed below:

  • - Read post to make sure if it is already posted what you are asking for,
  • - Make sure you have the latest version of libraries used in your project,
  • - Make a clean and grammatically correct written message,
  • - Report as many details as possible, including what have you done so far,
  • - Do NOT post any code here. Use Pastebin,
  • - Do NOT post any error codes here. Use Pastebin,
  • - Specify STM32Fxxx family and used Discovery/EVAL/Nucleo or custom made board,
  • - Make sure your clock is set correct for PLL,
  • - If you are using my HAL drivers, please check this post how to start.
Comment will be deleted on breaking these rules without notification!
  • phivu

    Hi Tilen,

    I’m programming ultrasonic sensor “Ultra Sonic range measurement module” from seeedstudio which is familiar to your sensor, excepting only a signal pin for echo and trigger. The website code for arduino is here: http://www.seeedstudio.com/wiki/index.php?title=Ultra_Sonic_range_measurement_module. I have just finished my code but unfortunately it cannot run. please can you download and check with your sensor for my code a little.

    Thanks.

  • Electronics Engineer

    hello Tilen,
    I want to know if this library works also with coocox CoIDE because i try to work with it but i found some errors

    • Hello,

      of course it works. Just write here your errors.
      Use pastebin.com for large strings.

      • Electronics Engineer

        hello,

        here are my errors

        http://pastebin.com/GsN3fRV8#

        • Hi,

          well this is not because of library.
          It’s because of you have two main functions or similar.

          • Electronics Engineer

            hello,
            thank you sir and excuse because this my very first time with the stm32f4

  • Electronics Engineer

    hello
    i want to know if this library works also with US-015 ultrasonic sensor
    please help

  • Electronics Engineer

    hello
    i want to know if this library works also with the US-015 ultrasonic sensor
    please help

    • I don’t know, but you can open datasheet and compare it with HCSR04 device.

      • Electronics Engineer

        ok, thank you sir

  • Victor

    Hello!
    I just wanted to know if you have a code similar to what I have to do.
    In my project I’m measuring distances with ultrasonic transducers, a transmitter and a receiver but separated one from the other. I just programmed the transmitter to make pulses of 40kHz during 1 ms, then wait for a few seconds and then again 1 ms pulses… I wanted to program the board so it reads data from the receiver when the pulses are arriving (ADC), use an interrupt so I can run a program to calculate de distance, and then wait for the next pulses.

    Any help will be grateful.
    Thank you

  • KroshkaRU

    Hi Majerle

    Please fix
    /* Initialize distance sensor1 on pins; TRIGGER: PD0, ECHO: PC1 */

    if (!TM_HCSR04_Init(&HCSR04, GPIOD, GPIO_PIN_0, GPIOC, GPIO_PIN_1)) {

    It MUST be

    /* Initialize distance sensor1 on pins; TRIGGER: PD0, ECHO: PC1 */

    if (!TM_HCSR04_Init(&HCSR04, GPIOC, GPIO_PIN_1, GPIOD, GPIO_PIN_0 ))

    I do not know how it works on your devices but I spent 4 hour to look for it and probably it helps somebody else.

    • My mistake. Thanks for reporting this.
      Actually I had correct wired on testings, but I fail with writing comments 😉

  • S.N.

    Note that the HC SR04 will not provide good reliable readings when powered at 3.3V. It needs 5V!

  • OutlanderLN

    Hi , first I’d like to thank you for your effort
    well , I’m working on stm32f411RE nucleo and I realy need a driver for the hc sr04 but I’m not being able to adapt the one provided here to the new features … Hal and so on
    thank you for your response

  • Wuerqiola

    Hello, if I want to test ultrasound code, as long as the program examples used like it?

    • I don’t understand your question.

      • Wuerqiola

        Sorry, I mean above Sample ultrasound test can do?

        • I’m sure you wanna ask if above example works. Yes it does.
          Next time post in english with some sense or you won’t receive response.

          • Wuerqiola

            I’m sorry, I used Google Translate, can not clearly express what I mean, thank you for your reply.

  • ehsan

    sir am trying to run the above example but am getting error in following libraries
    stm32f4xx_hal_flash.c
    stm32f4xx_hal_pwr.h
    stm32f4xx_hal.h
    so please help me to resolve it
    and where to use above hc-sr04 functions given above while running above example
    and please give me complete project file of above example , i need it very badly..

  • rooben

    Hi dear Tilen
    Thank you for useful tutorials, its a great job
    In the library (HC SRF04) i think there is a problem, for example if we generate 10Hz pulse with 30% duty cycle and try to measure pulsewidth with the library results will be wrong, because as frequency is low, in library micro is waiting for high state of input pin ( just before while loop) and as frequency is low (related to cortex frequency 168Mhz) micro is hanging and results are far from reality!!!
    time = 0;
    /* Wait till signal is low */
    while (TM_GPIO_GetInputPinValue(HCSR04->ECHO_GPIOx, HCSR04->ECHO_GPIO_Pin)) {
    /* Increase time */
    time++;
    /* Delay 1us */
    Delay(1);
    }

    /* Convert us to cm */
    HCSR04->Distance = (float)time * HCSR04_NUMBER;
    i think we should insert if function before while loop like this :
    if (TM_GPIO_GetInputPinValue(HCSR04->ECHO_GPIOx, HCSR04->ECHO_GPIO_Pin)) {
    time = 0;
    /* Wait till signal is low */
    while (TM_GPIO_GetInputPinValue(HCSR04->ECHO_GPIOx, HCSR04->ECHO_GPIO_Pin)) {
    /* Increase time */
    time++;
    /* Delay 1us */
    Delay(1);
    }
    }
    /* Convert us to cm */
    HCSR04->Distance = (float)time * HCSR04_NUMBER;

  • Cheir

    Hi everybody,Hi Tilen,

    I’m looking for a Project to connect Stm32F3 & HC SR04 sensor,can someone help me ?