当前位置:   article > 正文

基于STM32的超声波避障小车

基于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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/46341
推荐阅读
相关标签
  

闽ICP备14008679号