HCSR04 Ultrasonic Sensor Driver

Publisher:rocky96Latest update time:2017-01-13 Source: eefocusKeywords:HCSR04 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

HC_SR04 is a widely used ultrasonic ranging module. The module diagram is as follows


The module has four pins, namely VCC GND TRIG ECHO, where VCC GND is the power supply pin

TRIG is the ranging trigger pin, ECHO is the ranging input pin

The drive mode of this module is

The control port sends a high level of more than 10US, and then you can wait for the high level output at the receiving port. Once there is an output, you can start the timer. When this port becomes a low level, you can read the timer value, which is the time of this distance measurement, and then you can calculate the distance. By continuously measuring in this way, you can reach the value of your mobile measurement.

 

The module works as follows

(1) Use IO to trigger the ranging and provide a high-level signal of at least 10us;

(2) The module automatically sends 8 40khz square waves and automatically detects whether there is a signal return;

(3) When a signal is returned, a high level is output through IO. The duration of the high level is the time from the ultrasonic wave being emitted to the ultrasonic wave being returned.

(4 Calculate the test distance Test distance = (high level time * sound speed (340M/S))/2;

 

According to the working principle, we can choose two modes to drive

1. Use the interrupt + timer method, define ECHO as both the rising and falling edges can trigger interrupts. After trig is triggered, echo high level will interrupt and turn on the timer, echo low level will turn off the timer and count the timer count value

2. Use normal IO+timer mode, wait for echo response after triggering, turn on the timer when responding, and turn off the timer until echo returns to low, and get the time

 

1: This module should not be connected with power on. If it is to be connected with power on, connect the Gnd end of the module first. Otherwise, it will affect

Modules work.

2: When measuring distance, the area of ​​the object to be measured should be no less than 0.5 square meters and should be as flat as possible. Otherwise, the test results will be affected.

 

The detailed driver code is as follows

Hcsr04.c

  1. #include "hcsr04.h"  

  2.   

  3.   

  4. #define HCSR04_PORT GPIOB  

  5. #define HCSR04_CLK RCC_APB2Periph_GPIOB  

  6. #define HCSR04_TRIG GPIO_Pin_5  

  7. #define HCSR04_ECHO GPIO_Pin_6  

  8.   

  9. #define TRIG_Send PBout(5)  

  10. #define ECHO_Reci PBin(6)  

  11.   

  12. u16 msHcCount = 0; //ms count  

  13.   

  14. void Hcsr04Init(u32 NVIC_PriorityGroup,u32 PreemptionPriority,u32 SubPriority)  

  15. {  

  16.     u32 NVICtemp = 0; //Variables for NVIC controller  

  17.     TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; //Generate a structure for timer settings  

  18.     GPIO_InitTypeDef GPIO_InitStructure;  

  19.     RCC_APB2PeriphClockCmd(HCSR04_CLK, ENABLE);  

  20.       

  21.     NVICtemp = NVIC_EncodePriority(NVIC_PriorityGroup, PreemptionPriority, SubPriority); //Interrupt priority variable decoding  

  22.       

  23.     //IO initialization  

  24.     GPIO_InitStructure.GPIO_Pin =HCSR04_TRIG; //Send level pin  

  25.     GPIO_InitStructure.GPIO_Speed ​​= GPIO_Speed_50MHz;  

  26.     GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //Push-pull output  

  27.     GPIO_Init(HCSR04_PORT, &GPIO_InitStructure);  

  28.     GPIO_ResetBits(HCSR04_PORT,HCSR04_TRIG);  

  29.       

  30.     GPIO_InitStructure.GPIO_Pin = HCSR04_ECHO; //Return level pin  

  31.     GPIO_InitStructure.GPIO_Speed ​​= GPIO_Speed_50MHz;  

  32.     GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //Pull-down input  

  33.     GPIO_Init(HCSR04_PORT, &GPIO_InitStructure);      

  34.     //Timer initialization using basic timer TIM6  

  35.       

  36.     RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE); //Enable the corresponding RCC clock  

  37.     //Configure the timer infrastructure structure  

  38.     TIM_TimeBaseStructure.TIM_Period = 1000; //Set the value of the auto-reload register period to load the activity at the next update event. Count to 1000 for 1ms  

  39.     TIM_TimeBaseStructure.TIM_Prescaler = (72-1); //Set the prescaler value used as the TIMx clock frequency divisor 1M counting frequency 1US counting  

  40.     TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM up counting mode  

  41.     TIM_TimeBaseInit(TIM6, &TIM_TimeBaseStructure); //Initialize the time base unit of TIMx according to the parameters specified in TIM_TimeBaseInitStruct  

  42.       

  43.     TIM_ClearFlag(TIM6, TIM_FLAG_Update); //Clear the update interrupt to avoid an interrupt being generated immediately after the interrupt is enabled  

  44.     TIM_ITConfig(TIM6,TIM_IT_Update,ENABLE); //Enable timer update interrupt  

  45.     NVIC_SetPriority(TIM6_IRQn,NVICtemp); //Set interrupt priority  

  46.     NVIC_EnableIRQ(TIM6_IRQn); //Enable the corresponding interrupt  

  47.       

  48. }  

  49. static void OpenTimerForHc() //Open the timer  

  50. {  

  51.     TIM_SetCounter(TIM6,0); //Clear count  

  52.     msHcCount = 0;  

  53.     TIM_Cmd(TIM6, ENABLE); //Enable TIMx peripherals  

  54. }  

  55.   

  56. static void CloseTimerForHc() //Close the timer  

  57. {  

  58.     TIM_Cmd(TIM6, DISABLE); //Enable TIMx peripherals  

  59. }  

  60.   

  61.   

  62. //Timer 6 interrupt service routine  

  63. void TIM6_IRQHandler(void) //TIM3 interrupt  

  64. {  

  65.     if (TIM_GetITStatus(TIM6, TIM_IT_Update) != RESET) //Check whether TIM3 update interrupt occurs  

  66.     {  

  67.         TIM_ClearITPendingBit(TIM6, TIM_IT_Update ); //Clear TIMx update interrupt flag   

  68.         msHcCount++;  

  69.     }  

  70. }  

  71.   

  72. u32 GetEchoTimer(void)  

  73. {  

  74.     u32 t = 0;  

  75.     t = msHcCount*1000; //Get MS  

  76.     t += TIM_GetCounter(TIM6); //Get US  

  77.     return t;  

  78. }  

  79.   

  80. //Get ultrasonic distance measurement data once. There needs to be a period of time between two distance measurements to cut off the echo signal.  

  81. void Hcsr04GetLength(u32* length)  

  82. {  

  83.     u32 t = 0;  

  84.     float lengthTemp;  

  85.     TRIG_Send = 1; //Send port high level output  

  86.     DelayUs(10);  

  87.     TRIG_Send = 0;  

  88.     while(ECHO_Reci == 0); //Wait for the receiving port to output high level  

  89.     OpenTimerForHc(); //Open the timer  

  90.     while(ECHO_Reci == 1);  

  91.     CloseTimerForHc(); //Close the timer  

  92.     t = GetEchoTimer(); //Get time, resolution is 1US  

  93.     lengthTemp = ((float)t/58);//cm  

  94.     *length = (u32)lengthTemp;   

  95. }  




Hcsr04.h

  1. #ifndef __HCSR04_H  

  2. #define __HCSR04_H  

  3. #include "stm32f10x.h"  

  4. #include "delay.h"  

  5. #include "ioremap.h"  

  6. #include "common.h"  

  7.   

  8.   

  9.   

  10.   

  11.   

  12. //Ultrasonic module initialization  

  13. void Hcsr04Init(u32 NVIC_PriorityGroup,u32 PreemptionPriority,u32 SubPriority);  

  14.   

  15. //Ultrasonic module once distance acquisition  

  16. //Return 0 Success  

  17. //Return 1 if failed  

  18. void Hcsr04GetLength(u32* length);  

  19.   

  20. #endif  



Keywords:HCSR04 Reference address:HCSR04 Ultrasonic Sensor Driver

Previous article:RDA5820 radio chip driver
Next article:USB custom HID device implementation-STM32

Recommended ReadingLatest update time:2024-11-16 17:47

Comparison of main technical routes of new energy vehicle drive motors
The "Big Three Electrics" drive system of new energy vehicles includes a drive motor, a motor controller, and a reducer. The main function of the drive motor is to provide power for new energy vehicles and convert the electrical energy of the power battery into mechanical energy. Its main components include a stator
[Embedded]
Comparison of main technical routes of new energy vehicle drive motors
Design of analog display drive system based on LPC2478 LCD controller
introduction Currently, ARM is increasingly used in embedded systems. This article uses NXP's 32-bit LPC2478. The rich resources of LPC2478 are suitable for application in the industrial field. The chip has relatively low cost and power consumption. It is an ARM7 chip with an internal LCD controller. In the industrial
[Microcontroller]
Design of analog display drive system based on LPC2478 LCD controller
Simple serial port driver for STM32F103 (query mode)
When learning each module, usually only the simplest functions are used at the beginning. Here we will give a basic serial port receiving and transmitting driver for STM32F103. To use the serial port, you need to set the baud rate, data format, etc. of the serial port. The example given here uses USART1, whose clock is
[Microcontroller]
Analysis of LED drive circuit design methods
LED has many advantages such as environmental protection, long life, and high photoelectric efficiency. In recent years, its application in various industries has developed rapidly. The driving circuit of LED has become a key factor in product application. In theory, the service life of LED is more than 100,000 hour
[Power Management]
Introduction to the Evolutionary LED String Offline Driver
For LED driving, the constant current method is better than the constant voltage method. In the circuit proposed in this article, the constant voltage regulator commonly used for LEDs is replaced with a constant current source. In addition, a starting current limiter is used to suppress large inrush currents, and the
[Power Management]
Introduction to the Evolutionary LED String Offline Driver
LED driver design without electrolytic capacitor
Many countries are actively developing LED lighting technology. In order for high-brightness LEDs to achieve long life and minimize light decay, temperature control is the key. Therefore, compared with other light sources, LED lamps require a relatively large heat sink. In order to achieve ideal heat dissipati
[Power Management]
LED driver design without electrolytic capacitor
Design and development of 48 V high power electric drive system
Recently, Vitesco Technology has developed a 48 V high-power electric drive system suitable for hybrid vehicles. This high-power technology enables electric vehicles to comply with the Worldwide Light Vehicle Test Procedure (WLTP) and reduce CO2 emissions by about 20%. In addition to the drive unit, this system also u
[Automotive Electronics]
Design and development of 48 V high power electric drive system
M16 1602 driver
/***************************/ /*Header file name: LCD driver */ /* Target : m16 */ /* Crystal: 8.0000Mhz */ #ifndef _LCD_H_ #define _LCD_H_ #include "DELAY.H" /*------AVR and LCD connection information----------------------------------------- PA_2 - RS PA_3 - EN PA_4 - D4 PA_5 - D5 PA_6 - D6 PA_7 - D7 6 wires --------
[Microcontroller]
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号