帮我用c语言写基于stm32f103zet6单片机的hc-sr04模块的超声波测距的代码
时间: 2023-03-25 19:02:17 浏览: 98
好的,我可以回答这个问题。以下是基于stm32f103zet6单片机的hc-sr04模块的超声波测距的代码:
#include "stm32f10x.h"
#define TRIG_PIN GPIO_Pin_
#define ECHO_PIN GPIO_Pin_1
#define TRIG_PORT GPIOA
#define ECHO_PORT GPIOA
void delay_us(uint32_t us)
{
uint32_t i;
for(i=; i<us*8; i++);
}
void HC_SR04_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TRIG_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
}
float HC_SR04_GetDistance(void)
{
uint32_t time_start, time_stop, time_diff;
float distance;
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
delay_us(2);
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
time_start = TIM2->CNT;
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET);
time_stop = TIM2->CNT;
time_diff = time_stop - time_start;
distance = (float)time_diff / 58.;
return distance;
}
int main(void)
{
float distance;
HC_SR04_Init();
while(1)
{
distance = HC_SR04_GetDistance();
// do something with the distance value
}
}
阅读全文