写一个stm32F103C8T6超声波测距代码
时间: 2023-12-07 21:05:45 浏览: 65
基于STM32F103C8T6超声波测距源码及接线(已调).zip
以下是一个简单的超声波测距代码,基于STM32F103C8T6的定时器和外部中断实现:
```c
#include "stm32f10x.h"
#define TRIG_PIN GPIO_Pin_0
#define TRIG_PORT GPIOA
#define ECHO_PIN GPIO_Pin_1
#define ECHO_PORT GPIOA
uint16_t distance = 0;
void TIM2_IRQHandler(void) {
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) {
// 超时未检测到回波,停止计时
TIM_Cmd(TIM2, DISABLE);
TIM_SetCounter(TIM2, 0);
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
void EXTI1_IRQHandler(void) {
if (EXTI_GetITStatus(EXTI_Line1) != RESET) {
if (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN)) {
// 上升沿,开始计时
TIM_SetCounter(TIM2, 0);
TIM_Cmd(TIM2, ENABLE);
} else {
// 下降沿,计算距离
uint16_t cnt = TIM_GetCounter(TIM2);
distance = cnt / 58; // 距离单位为厘米
TIM_Cmd(TIM2, DISABLE);
TIM_SetCounter(TIM2, 0);
}
EXTI_ClearITPendingBit(EXTI_Line1);
}
}
void init_gpio(void) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置TRIG引脚为输出模式
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);
// 配置ECHO引脚为输入模式
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
}
void init_tim(void) {
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock / 1000000 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
NVIC_EnableIRQ(TIM2_IRQn);
}
void init_exti(void) {
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource1);
EXTI_InitStructure.EXTI_Line = EXTI_Line1;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void delay_us(uint16_t us) {
uint16_t i, j;
for (i = 0; i < us; i++) {
for (j = 0; j < 10; j++);
}
}
int main(void) {
init_gpio();
init_tim();
init_exti();
while (1) {
// 发送10us的触发脉冲
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
delay_us(2);
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
// 延时等待回波
delay_us(500);
// 读取距离值
printf("distance: %d cm\r\n", distance);
}
}
```
以上代码仅供参考,具体实现方式可能会因为硬件和环境等因素而有所变化。
阅读全文