当前位置:网站首页>[stm32f130rct6] idea and code of ultrasonic ranging module
[stm32f130rct6] idea and code of ultrasonic ranging module
2022-07-25 02:54:00 【Jingle cat that can use magic】
Catalog
【 Hardware description 】
STM32F103 Kernel development board , Ultrasonic module HC-SR04

chart 1 HC-SR04 Physical drawing of ultrasonic module
【 Theoretical explanation 】
The ultrasonic module used in the process is HC-SR04 modular . There are four pins , Namely Echo、Trig、VCC、GND.Trig Trigger end : It is to trigger the pin of ultrasonic ranging ;Echo Receiving signal end : The ultrasonic returns to a high level , And we calculate the distance through the duration of high level .
Ultrasonic principle :(1) use IO Trigger ranging , At least give 10us High level signal ;(2) Automatic module sending 8 individual 40khz The square wave , Automatically detects if a signal is returned ;(3) Return with signal , adopt IO Output a high level , The duration of the high level is the time from the ultrasonic wave is emitted to the time it returns .
The test distance = ( High level time * The speed of sound (340 M/S ) ) / 2

chart 2 HC-SR04 Ultrasonic sequence diagram
【 software design 】
Timer initialization
This use TIM3、TIM5 To be responsible for data acquisition of ultrasonic module . Before the program enters while Before the cycle , Need to be right TIM3、TIM5 To initialize , Because the configuration of the two timers are similar , So just show one .
/**************************************************************************
The functionality : Timer 5 Channel input capture initialization
Entrance parameters : Entrance parameters :arr: Auto reload value psc: Clock presplitting frequency
return value : nothing
**************************************************************************/
void TIM5_Cap_Init(u16 arr, u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
// Can make TIM5 The clock
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB |
RCC_APB2Periph_GPIOC, ENABLE); // Can make GPIO The clock
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //PA Input
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // Output
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; //2M
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // Output
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; //2M
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // Output
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; //2M
GPIO_Init(GPIOC, &GPIO_InitStructure);
// Initialize the timer 5
TIM_TimeBaseStructure.TIM_Period = arr; // Set the counter to automatically reload
TIM_TimeBaseStructure.TIM_Prescaler = psc; // Preassigned frequency counter
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; // Set the clock split :TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM Upcount mode
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure); // according to TIM_TimeBaseInitStruct The parameter specified in TIMx Unit of time base
// initialization TIM5 Input capture parameter
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1; // Select input
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; // Rising edge capture
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; // Configure the input divider , Regardless of the frequency
TIM_ICInitStructure.TIM_ICFilter = 0x00; // Configure input filter Don't filter
TIM_ICInit(TIM5, &TIM_ICInitStructure);
// initialization TIM5 Input capture parameter
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2; // Select input
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; // Rising edge capture
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; // Configure the input divider , Regardless of the frequency
TIM_ICInitStructure.TIM_ICFilter = 0x00; // Configure input filter Don't filter
TIM_ICInit(TIM5, &TIM_ICInitStructure);
// initialization TIM5 Input capture parameter
TIM_ICInitStructure.TIM_Channel = TIM_Channel_3; // Select input
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; // Rising edge capture
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; // Configure the input divider , Regardless of the frequency
TIM_ICInitStructure.TIM_ICFilter = 0x00; // Configure input filter Don't filter
TIM_ICInit(TIM5, &TIM_ICInitStructure);
// initialization TIM5 Input capture parameter
TIM_ICInitStructure.TIM_Channel = TIM_Channel_4; // Select input
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; // Rising edge capture
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; // Configure the input divider , Regardless of the frequency
TIM_ICInitStructure.TIM_ICFilter = 0x00; // Configure input filter Don't filter
TIM_ICInit(TIM5, &TIM_ICInitStructure);
// Interrupt group initialization
NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn;
//TIM interrupt
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
// Take precedence 0 level
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
// From the priority 2 level
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
//IRQ The channel is energized
NVIC_Init(&NVIC_InitStructure);
// according to NVIC_InitStruct The parameter specified in NVIC register
TIM_ITConfig(TIM5, TIM_IT_Update | TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4, ENABLE); // Allow update interrupt , Allow capture interrupt
TIM_Cmd(TIM5, ENABLE); // Enable timer
}Ultrasonic ranging function
The program here only shows timers 5 Channel 1
u16 TIM5CH1_CAPTURE_STA, TIM5CH1_CAPTURE_VAL, TIM5CH2_CAPTURE_STA, TIM5CH2_CAPTURE_VAL;
u16 TIM5CH3_CAPTURE_STA, TIM5CH3_CAPTURE_VAL, TIM5CH4_CAPTURE_STA, TIM5CH4_CAPTURE_VAL;
u16 TIM3CH1_CAPTURE_STA, TIM3CH1_CAPTURE_VAL, TIM3CH2_CAPTURE_STA, TIM3CH2_CAPTURE_VAL;
u16 TIM3CH3_CAPTURE_STA, TIM3CH3_CAPTURE_VAL, TIM3CH4_CAPTURE_STA, TIM3CH4_CAPTURE_VAL;
/**************************************************************************
The functionality : Ultrasonic receiving echo function
Entrance parameters : nothing
return value : nothing
**************************************************************************/
void Read_Distane(void)
{
TRIPA = 1; // High level trigger
delay_us(15); // Time delay
TRIPA = 0; // Low level
if (TIM5CH1_CAPTURE_STA & 0X80) // Successfully captured a high level
{
Distance_A = TIM5CH1_CAPTURE_STA & 0X3F;
Distance_A *= 65536; // Total overflow time
Distance_A += TIM5CH1_CAPTURE_VAL; // Get the total high level time
Distance_A = Distance_A * 170 / 1000; // Turn it into mm In units of , According to the speed of sound propagation in the air 340m/s
TIM5CH1_CAPTURE_STA = 0; // Enable the next capture
}
TRIPB = 1; // High level trigger
delay_us(15); // Time delay
TRIPB = 0; // Low level
if (TIM5CH2_CAPTURE_STA & 0X80) // Successfully captured a high level
{
Distance_B = TIM5CH2_CAPTURE_STA & 0X3F;
Distance_B *= 65536; // Total overflow time
Distance_B += TIM5CH2_CAPTURE_VAL; // Get the total high level time
Distance_B = Distance_B * 170 / 1000; // Turn it into mm In units of , According to the speed of sound propagation in the air 340m/s
TIM5CH2_CAPTURE_STA = 0; // Enable the next capture
}
TRIPC = 1; // High level trigger
delay_us(15); // Time delay
TRIPC = 0; // Low level
if (TIM5CH3_CAPTURE_STA & 0X80) // Successfully captured a high level
{
Distance_C = TIM5CH3_CAPTURE_STA & 0X3F;
Distance_C *= 65536; // Total overflow time
Distance_C += TIM5CH3_CAPTURE_VAL; // Get the total high level time
Distance_C = Distance_C * 170 / 1000; // Turn it into mm In units of , According to the speed of sound propagation in the air 340m/s
TIM5CH3_CAPTURE_STA = 0; // Enable the next capture
}
TRIPD = 1; // High level trigger
delay_us(15); // Time delay
TRIPD = 0; // Low level
if (TIM5CH4_CAPTURE_STA & 0X80) // Successfully captured a high level
{
Distance_D = TIM5CH4_CAPTURE_STA & 0X3F;
Distance_D *= 65536; // Total overflow time
Distance_D += TIM5CH4_CAPTURE_VAL; // Get the total high level time
Distance_D = Distance_D * 170 / 1000; // Turn it into mm In units of , According to the speed of sound propagation in the air 340m/s
TIM5CH4_CAPTURE_STA = 0; // Enable the next capture
}
}Timer interrupt function
/**************************************************************************
The functionality : Ultrasonic echo pulse width reading interrupt
Entrance parameters : nothing
return value : nothing
**************************************************************************/
void TIM5_IRQHandler(void)
{
u16 tsr;
tsr = TIM5->SR;
/ Channel 1 ///
if ((TIM5CH1_CAPTURE_STA & 0X80) == 0) // It has not been successfully captured
{
if (tsr & 0X01) // overflow
{
if (TIM5CH1_CAPTURE_STA & 0X40) // The high level has been captured
{
if ((TIM5CH1_CAPTURE_STA & 0X3F) == 0X3F) // The high level is too long
{
TIM5CH1_CAPTURE_STA |= 0X80; // The tag was successfully captured once
TIM5CH1_CAPTURE_VAL = 0XFFFF;
}
else
TIM5CH1_CAPTURE_STA++;
}
}
if (tsr & 0x02) // Capture 1 Capture event
{
if (TIM5CH1_CAPTURE_STA & 0X40) // Capture a drop edge
{
TIM5CH1_CAPTURE_STA |= 0X80; // Mark successfully captures a high level pulse width
TIM5CH1_CAPTURE_VAL = TIM5->CCR1; // Get the current capture value .
TIM5->CCER &= ~(1 << 1); //CC1P=0 Set to rising edge capture
}
else // Has not yet started , The first time to capture the rising edge
{
TIM5CH1_CAPTURE_STA = 0; // Empty
TIM5CH1_CAPTURE_VAL = 0;
TIM5CH1_CAPTURE_STA |= 0X40; // The tag captures the rising edge
TIM5->CNT = 0; // The counter is cleared
TIM5->CCER |= 1 << 1; //CC1P=1 Set to drop edge capture
}
}
}
/ Channel 2 ///
if ((TIM5CH2_CAPTURE_STA & 0X80) == 0) // It has not been successfully captured
{
if (tsr & 0X01) // overflow
{
if (TIM5CH2_CAPTURE_STA & 0X40) // The high level has been captured
{
if ((TIM5CH2_CAPTURE_STA & 0X3F) == 0X3F) // The high level is too long
{
TIM5CH2_CAPTURE_STA |= 0X80; // The tag was successfully captured once
TIM5CH2_CAPTURE_VAL = 0XFFFF;
}
else
TIM5CH2_CAPTURE_STA++;
}
}
if (tsr & 0x04) // Capture 2 Capture event
{
if (TIM5CH2_CAPTURE_STA & 0X40) // Capture a drop edge
{
TIM5CH2_CAPTURE_STA |= 0X80; // Mark successfully captures a high level pulse width
TIM5CH2_CAPTURE_VAL = TIM5->CCR2; // Get the current capture value .
TIM5->CCER &= ~(1 << 5); //CC1P=0 Set to rising edge capture
}
else // Has not yet started , The first time to capture the rising edge
{
TIM5CH2_CAPTURE_STA = 0; // Empty
TIM5CH2_CAPTURE_VAL = 0;
TIM5CH2_CAPTURE_STA |= 0X40; // The tag captures the rising edge
TIM5->CNT = 0; // The counter is cleared
TIM5->CCER |= 1 << 5; //CC1P=1 Set to drop edge capture
}
}
}
/ Channel III ///
if ((TIM5CH3_CAPTURE_STA & 0X80) == 0) // It has not been successfully captured
{
if (tsr & 0X01) // overflow
{
if (TIM5CH3_CAPTURE_STA & 0X40) // The high level has been captured
{
if ((TIM5CH3_CAPTURE_STA & 0X3F) == 0X3F) // The high level is too long
{
TIM5CH3_CAPTURE_STA |= 0X80; // The tag was successfully captured once
TIM5CH3_CAPTURE_VAL = 0XFFFF;
}
else
TIM5CH3_CAPTURE_STA++;
}
}
if (tsr & 0x08) // Capture 3 Capture event
{
if (TIM5CH3_CAPTURE_STA & 0X40) // Capture a drop edge
{
TIM5CH3_CAPTURE_STA |= 0X80; // Mark successfully captures a high level pulse width
TIM5CH3_CAPTURE_VAL = TIM5->CCR3; // Get the current capture value .
TIM5->CCER &= ~(1 << 9); //CC1P=0 Set to rising edge capture
}
else // Has not yet started , The first time to capture the rising edge
{
TIM5CH3_CAPTURE_STA = 0; // Empty
TIM5CH3_CAPTURE_VAL = 0;
TIM5CH3_CAPTURE_STA |= 0X40; // The tag captures the rising edge
TIM5->CNT = 0; // The counter is cleared
TIM5->CCER |= 1 << 9; //CC1P=1 Set to drop edge capture
}
}
}
/ Channel 4 ///
if ((TIM5CH4_CAPTURE_STA & 0X80) == 0) // It has not been successfully captured
{
if (tsr & 0X01) // overflow
{
if (TIM5CH4_CAPTURE_STA & 0X40) // The high level has been captured
{
if ((TIM5CH4_CAPTURE_STA & 0X3F) == 0X3F) // The high level is too long
{
TIM5CH4_CAPTURE_STA |= 0X80; // The tag was successfully captured once
TIM5CH4_CAPTURE_VAL = 0XFFFF;
}
else
TIM5CH4_CAPTURE_STA++;
}
}
if (tsr & 0x10) // Capture 4 Capture event
{
if (TIM5CH4_CAPTURE_STA & 0X40) // Capture a drop edge
{
TIM5CH4_CAPTURE_STA |= 0X80; // Mark successfully captures a high level pulse width
TIM5CH4_CAPTURE_VAL = TIM5->CCR4; // Get the current capture value .
TIM5->CCER &= ~(1 << 13); //CC1P=0 Set to rising edge capture
}
else // Has not yet started , The first time to capture the rising edge
{
TIM5CH4_CAPTURE_STA = 0; // Empty
TIM5CH4_CAPTURE_VAL = 0;
TIM5CH4_CAPTURE_STA |= 0X40; // The tag captures the rising edge
TIM5->CNT = 0; // The counter is cleared
TIM5->CCER |= 1 << 13; //CC1P=1 Set to drop edge capture
}
}
}
TIM5->SR = 0; // Clears the interrupt flag bit
}The main function
int main(void)
{
delay_init(); // Delay function initialization
MY_NVIC_PriorityGroupConfig(2); // Set interrupt grouping
JTAG_Set(SWD_ENABLE); // open SWD Interface You can use the of the motherboard SWD Interface debugging
QuDong_Init(); // Initialize the drive port
uart_init(115200); // A serial port 1 initialization
CAN_Config(); // initialization can, In interrupt reception CAN Data packets */
MiniBalance_PWM_Init(3599, 0); //PWM The highest frequency 20K
TIM2_Cap_Init(0XFFFF, 72 - 1); // Timer 2 Input capture Open the channel TIM2_CH3 TIM2_CH4
TIM6_Int_Init(100 - 1, 7200 - 1); // Timer 6 initialization 10ms interrupt
TIM5_Cap_Init(0XFFFF, 72 - 1); // Ultrasonic wave begins to melt Default comment Ultrasonic wiring Reference resources timer.h file
TIM3_Cap_Init(0XFFFF, 72 - 1); // Ultrasonic wave begins to melt Default comment Ultrasonic wiring Reference resources timer.h file
printf(" Start !\r\n");
v_mc = (int)get_mc(0.2); // Enter the speed value Pulse frequency corresponding to conversion bit
L = 6.0;
/*** Hardware adaptation ***/
TIM_SetCompare1(TIM4, 0);
TIM_SetCompare2(TIM4, 0);
delay_ms(250);
while (1)
{
TIM_SetCompare1(TIM4, sv_L);
TIM_SetCompare2(TIM4, sv_R * 1.013);
if (TIM2_CH3Structure.Capture_FinishFlag == 1)
{
printf("Frequency_L = %d Hz ", TIM2_CH3Structure.value);
printf("V_L = %f M/s\r\n", get_v(TIM2_CH3Structure.value));
TIM2_CH3Structure.Capture_FinishFlag = 0;
}
if (TIM2_CH4Structure.Capture_FinishFlag == 1)
{
printf("Frequency_R = %d Hz ", TIM2_CH4Structure.value);
printf("V_R = %f M/s\r\n", get_v(TIM2_CH4Structure.value));
TIM2_CH4Structure.Capture_FinishFlag = 0;
}
else
{
printf("Wave is not exist or Cature is incomplete.\n");
}
A = Distance_A; //y
C = Distance_C; //*y
D = Distance_D; //y
c = Distance_c; //*y
B = Distance_B; //*y
a = Distance_a; //*n
b = Distance_b; //y
d = Distance_d; //y
printf(" Away from the front :%d ", b);
printf(" Distance to the rear :%d ", C);
printf(" Distance left :%d ", B);
printf(" To the right :%d\r\n", c);
delay_ms(1000);
}
}
void TIM6_IRQHandler(void) // TIM6 10ms interrupt
{
if (TIM_GetITStatus(TIM6, TIM_IT_Update) != RESET) // Check the specified TIM6 Whether the interruption occurs or not
{
// Ultrasonic ranging & Avoiding obstacles
Read_Distane();
Read_Distane2();
if (b < 600)
{
GPIO_ResetBits(GPIOC, GPIO_Pin_1 | GPIO_Pin_0); // Lower the brake
}
else
{
GPIO_SetBits(GPIOC, GPIO_Pin_1 | GPIO_Pin_0);
if (TIM2_CH3Structure.value <= v_mc)
{
sv_L = (int)(float)(Velocity_PI(TIM2_CH3Structure.value, v_mc) / -20000.0 * 3600.0);
}
if (TIM2_CH4Structure.value <= v_mc)
{
sv_R = (int)(float)(Velocity_PI(TIM2_CH4Structure.value, v_mc) / -20000.0 * 3600.0);
}
}
}
TIM_ClearITPendingBit(TIM6, TIM_IT_Update); // eliminate TIM6 Interrupt pending bit of
}Here we are , The basic ideas and procedures of the ultrasonic module have been listed .
I'm a rookie , Everyone's encouragement is the driving force for me to continue to create , If you think it's good , Welcome to your attention , give the thumbs-up , Collection , forward , thank you !

边栏推荐
- Vulntarget vulnerability shooting range -vulntarget-b
- Flutter apple native Pinyin keyboard input exception on textfield | Pinyin input process callback problem
- Creating elements of DOM series
- Threat report in June: new bank malware malibot poses a threat to mobile banking users
- Details of C language compilation preprocessing and comparison of macros and functions
- Redis unauthorized access vulnerability recurrence (www.hetianlab.com)
- Flink's study notes
- Learning record 10
- [jailhouse article] certify the uncertified rewards assessment of virtualization for mixed criticality
- JS written test question -- realize the flat function of array
猜你喜欢

Introduction to web security telent testing and defense

C language: Structure -- a detailed explanation of memory byte alignment

Tp5.1 paging (with parameter transfer)

YouTube Download and (batch) Download

String class

If there is a segment in the encryption field, are you "bronze" or "King"?

Operator explanation - C language
![[C language] program compilation (preprocessing)](/img/94/175a84d89b1f16987e529eb029cbbc.png)
[C language] program compilation (preprocessing)

Visualization of correlation coefficient matrix

What should I do when the interface encounters jsonstring
随机推荐
Permanently mount the image steps
Coal industry supply chain centralized mining system: digitalization to promote the transformation and upgrading of coal industry
[C language] program compilation (preprocessing)
[jailhouse article] certify the uncertified rewards assessment of virtualization for mixed criticality
Go common standard library -time
Threat report in June: new bank malware malibot poses a threat to mobile banking users
New key points of ES6
Tp5.0 background admin access
Three ways to solve your performance management problems
JS written test question -- prototype, new, this comprehensive question
Edit mathematical formulas in markdown
Ten year structure and five-year Life-03 trouble as a technical team leader
Rotating frame target detection mmrotate v0.3.1 training hrsc2016 data set (II)
JS foundation -- object static method
Case analysis of building exhibition service management system with low code development platform
Physical experiment simulation
6. Object storage
Wechat sports field reservation of applet completion works applet graduation design (8) graduation design thesis template
Dynamic programming -- Digital DP
Sword finger offer 11. rotate the minimum number of the array