#include "hc_sr04.h"
float Distance;
void hcgpio_init(void)
{
GPIO_InitTypeDef gpio_struct;
NVIC_InitTypeDef nvic_struct;
EXTI_InitTypeDef exti_struct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOA |
RCC_APB2Periph_AFIO, ENABLE);
gpio_struct.GPIO_Pin = GPIO_Pin_0;
gpio_struct.GPIO_Mode = GPIO_Mode_Out_PP;
gpio_struct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC,&gpio_struct);
gpio_struct.GPIO_Pin = GPIO_Pin_1;
gpio_struct.GPIO_Mode = GPIO_Mode_IPD;
gpio_struct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC,&gpio_struct);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC,GPIO_PinSource1);
exti_struct.EXTI_Line = EXTI_Line1;
exti_struct.EXTI_Mode = EXTI_Mode_Interrupt;
exti_struct.EXTI_Trigger = EXTI_Trigger_Rising;
exti_struct.EXTI_LineCmd = ENABLE;
EXTI_Init(&exti_struct);
nvic_struct.NVIC_IRQChannel = EXTI1_IRQn;
nvic_struct.NVIC_IRQChannelCmd = ENABLE;
nvic_struct.NVIC_IRQChannelPreemptionPriority = 2;
nvic_struct.NVIC_IRQChannelSubPriority = 2;
NVIC_Init(&nvic_struct);
}
void EXTI1_IRQHandler(void)
{
delay_us(10);
if(EXTI_GetITStatus(EXTI_Line1) !=RESET)
{
TIM_SetCounter(TIM2,0);
TIM_Cmd(TIM2,ENABLE);
while(GPIO_ReadInputDataBit(GPIOC,GPIO_Pin_1)); //μè′yμíμçÆ½
TIM_Cmd(TIM2,DISABLE);
Distance=TIM_GetCounter(TIM2)*340/200.0;
if(Distance>0)
{
printf("Distance:%f cm\r\n",Distance);
}
EXTI_ClearITPendingBit(EXTI_Line1);
}
}
void hc_sr04(void)
{
GPIO_SetBits(GPIOC,GPIO_Pin_0);
delay_us(20);
GPIO_ResetBits(GPIOC,GPIO_Pin_0);
}
#include "hc_time.h"
void hctime_init(void)
{
TIM_TimeBaseInitTypeDef time_struct;
NVIC_InitTypeDef nvic_struct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 ,ENABLE);
time_struct.TIM_Period = 5000;
time_struct.TIM_Prescaler = 7199;
time_struct.TIM_CounterMode = TIM_CounterMode_Up;
time_struct.TIM_ClockDivision = 0;
//tim2
TIM_TimeBaseInit(TIM2,&time_struct);
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
TIM_ITConfig(TIM2,TIM_IT_Trigger,ENABLE);
nvic_struct.NVIC_IRQChannel = TIM2_IRQn;
nvic_struct.NVIC_IRQChannelCmd = ENABLE;
nvic_struct.NVIC_IRQChannelPreemptionPriority = 1;
nvic_struct.NVIC_IRQChannelSubPriority = 0;
NVIC_Init(&nvic_struct);
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
}
}
|