|
主函数: int main(void) {
delay_init(); //延时函数初始化
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
uart_init(115200); //串口初始化为115200
usart2_init(); //duoji
LED_Init(); //LED端口初始化
Ultrasonic_init();//超声波的初始化
time_Init();//计数器2的初始化
while(1)
{
PanDuan();
delay_ms(100);
LED0=!LED0;
delay_ms(100);
}
}
超声波设置部分(主要看中断函数部分就行):
void Ultrasonic_init()
{
GPIO_InitTypeDef GPIO_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
EXTI_InitTypeDef EXTI_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO,ENABLE);
/*超声波发射端配置*/ //TX->Trig
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB,&GPIO_InitStruct);
/*超声波接收端配置*///RX->Echo
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPD;
GPIO_Init(GPIOB,&GPIO_InitStruct);
/*选择GPIO管脚作为外部中断线路*/
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource1);
/*外部中断优先级的配置*/
NVIC_InitStruct.NVIC_IRQChannel=EXTI1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority=0;
NVIC_Init(&NVIC_InitStruct);
/*外部中断的配置*/
EXTI_InitStruct.EXTI_Line = EXTI_Line1;
EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Rising;
EXTI_InitStruct.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStruct);
EXTI_ClearITPendingBit(EXTI_Line1);//清除中断的挂起位
}
void Ultrasonic_start()
{
GPIO_ResetBits(GPIOB,GPIO_Pin_0);
GPIO_SetBits(GPIOB,GPIO_Pin_0);
delay_us(20);
GPIO_ResetBits(GPIOB,GPIO_Pin_0);
}
void EXTI1_IRQHandler()
{
if(EXTI_GetITStatus(EXTI_Line1)!=RESET)
{ EXTI_ClearITPendingBit(EXTI_Line1);
//LED0=1;
TIM_SetCounter(TIM2,0);
TIM_Cmd(TIM2,ENABLE);
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1));
TIM_Cmd(TIM2,DISABLE);
distance=TIM_GetCounter(TIM2)*1.7;
}
}
重头戏——舵机部分:
void PanDuan(void){
if((int)distance<40)
{
if((int)distance<20)
{
//后退
}
while(1)
{
DuojiZhong();
delay_ms(150);
DuojiZuo();
delay_ms(150);
Ultrasonic_start();
distance_left=distance;
DuojiYou();
delay_ms(150);
Ultrasonic_start();
distance_right=distance;
DuojiZhong();
delay_ms(150);
if((int)distance_left<30&&(int)distance_right>30)
{
//右转+直行
}
else if((int)distance_right<30&&(int)distance_left>30)
{
//左转+直行
}
else if((int)distance_right<=30&&(int)distance_left<=30)
{
//停车
}
else
{
//左转+直行
}
DuojiZhong();
delay_ms(150);
Ultrasonic_start();
if(distance>40) break;
}
}
else
{
//直行
DuojiZhong();
delay_ms(150);
Ultrasonic_start();
}
if((int)distance<=450&&(int)distance>=2)
{printf("distance: %f cm\r\n", distance); //用Zigbee发送distance
//LED0=!LED0;
//delay_ms(100);
}
}
求救,只能相应一次,卡在舵机设置部分,咋办呀???
|
|