Nucleo and HC-SR04 Ultrasonic Sensor example

63

HC-SR04 is an ultrasonic ranging module that provides 2 cm to 400 cm non-contact measurement function. The ranging accuracy can reach to 3mm and effectual angle is < 15°. It can be powered from a 5V power supply.

HC-SR04 Specifications

  • Working Voltage: DC 5V
  • Working Current: 15mA
  • Working Frequency: 40Hz
  • Max Range: 4m
  • Min Range: 2cm
  • Measuring Angle: 15 degree
  • Trigger Input Signal: 10µS TTL pulse
HC-SR04 Ultrasonic Sensor
HC-SR04 Ultrasonic Sensor

Layout

Here is the layout, the Trig is connected to D12 and the Echo is connected to D11. If you change the pins you’ll have to update the code later

Nucleo and HCSR04
Nucleo and HCSR04

Code

In this example we need to import a HCSR04 library into the mBed online compiler, I used this one – https://developer.mbed.org/users/antoniolinux/code/HCSR04/

// Initialize a pins to perform Serial Communication for receive
// the result of the printf on PC (USB Virtual Com)
// I suggest to use TeraTerm on PC.
// TeraTerm configuration must be: 9600-8-N-1 FlowControl None
 
/* EXAMPLE */
#include "mbed.h"
#include "hcsr04.h"
 
//D12 TRIGGER D11 ECHO
HCSR04 sensor(D12, D11); 
int main() 
{
    while(1) 
    {
 
     long distance = sensor.distance();   
      printf("distance  %d  \n",distance);
      wait(1.0); // 1 sec  
 
    }
}

 

Links
HC-SR04 Ultrasonic Module Wave Sensor Ranging Detector Distance Module

NUCLEO-F411RE STM32F411RE Core Board

Share