623
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
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
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/
[codesyntax lang=”cpp”]
// 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 } }
[/codesyntax]
Links
HC-SR04 Ultrasonic Module Wave Sensor Ranging Detector Distance Module
NUCLEO-F411RE STM32F411RE Core Board