基于STM32的超声波避障小车

超声波避障小车原理就是通过给超声波模块超过10us的高电平信号,自动发送8个40KHZ的方波,来检测是不是有信号的返回,如果有信号的返回,那么就判断为前方有障碍物,并且通过舵机云台,来实现180度的旋转,检测左右两边是否的有障碍物,从而进行避障的功能。

说完原理,接下来就是根据各部件的原理来进行编程,我的超声波避障小车主要涉及了超声波HC-SR04模块,L298N电机驱动模块,舵机sg90模块。
首先是最基本的电机驱动模块的相关代码:

#include "bsp_motor.h"
#include "delay.h"
#include <math.h>

void TIM4_PWM_Motor(unsigned int arr,unsigned int psc)
{
   	
	GPIO_InitTypeDef					GPIO_InitStuct;
	TIM_TimeBaseInitTypeDef		TIM_TimeBaseInitStuct;
	TIM_OCInitTypeDef					TIM_OCInitStuct;
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB, ENABLE);
	
	
	GPIO_InitStuct.GPIO_Pin=GPIO_Pin_7;						//左电机控制
	GPIO_InitStuct.GPIO_Mode=GPIO_Mode_Out_PP;
	GPIO_InitStuct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStuct);
	
	GPIO_InitStuct.GPIO_Pin=GPIO_Pin_8;						//左电机PWM
	GPIO_InitStuct.GPIO_Mode=GPIO_Mode_AF_PP;
	GPIO_InitStuct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStuct);
	
	GPIO_InitStuct.GPIO_Pin=GPIO_Pin_9;						//右电机PWM
	GPIO_InitStuct.GPIO_Mode=GPIO_Mode_AF_PP;
	GPIO_InitStuct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStuct);
		
	GPIO_InitStuct.GPIO_Pin=GPIO_Pin_4;						//右电机方向控制
	GPIO_InitStuct.GPIO_Mode=GPIO_Mode_Out_PP;
	GPIO_InitStuct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStuct);
	
	TIM_TimeBaseInitStuct.TIM_ClockDivision=0;
	TIM_TimeBaseInitStuct.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInitStuct.TIM_Period=arr;
	TIM_TimeBaseInitStuct.TIM_Prescaler=psc;
	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStuct);
	
	TIM_OCInitStuct.TIM_OCMode = TIM_OCMode_PWM2; 
	TIM_OCInitStuct.TIM_OutputState = TIM_OutputState_Enable; 
	TIM_OCInitStuct.TIM_Pulse = 0; 
	TIM_OCInitStuct.TIM_OCPolarity = TIM_OCPolarity_High; 
	TIM_OC3Init(TIM4, &TIM_OCInitStuct);  
	TIM_OC4Init(TIM4, &TIM_OCInitStuct);  
	
	TIM_CtrlPWMOutputs(TIM4,ENABLE);	
  
	TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable);  
	TIM_OC4PreloadConfig(TIM4, TIM_OCPreload_Enable); 
	
 	TIM_Cmd(TIM4, ENABLE);
}

void car_run(unsigned char ucChannel,signed char cSpeed)
{
   
		short PWM;	
   	PWM = 7201 - fabs(cSpeed)*72;
	switch(ucChannel)
	{
   
		case 0://右轮
			TIM_SetCompare3(TIM4,PWM);
			if (cSpeed>0) 
				GPIO_ResetBits(GPIOA,GPIO_Pin_4);
			else if(cSpeed<0) 
				GPIO_SetBits
  • 44
    点赞
  • 572
    收藏
    觉得还不错? 一键收藏
  • 36
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 36
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值