Stm32蓝牙小车HAL库(CubeMx配置)

一、硬件配置

配件:

    7.4V锂电池 两个马达 L298n电机驱动模块 JDY-31蓝牙模块 stm32f407zgt6单片机

1.作品实图

(正面) (反面)

2.L298n电机驱动模块

1、单片机在CubeMx上配置四个引脚连接逻辑输入四个引脚

2、将两个马达分别引出两条线接输出A和输出B,同时接跳线帽使能通道A和通道B

3、接入7-12V电源在12V供电口(可以在此处作开关处理,将电池正极连接开关一端,开关另一端接入12V供电),使电源转换为5v接入单片机(单片机最高5v),为单片机供电

4、将供电GND和5V供电接入单片机

3.JDY-31蓝牙模块

这部分不作多解释,详细可以查看手册。

二、软件配置

软件:

    Stm32CubeMx Keil5

1.Stm32CubeMx配置引脚

这里配置PA1-A4四个引脚作马达引脚,A1-A2马达1,A3-A4马达2


2.串口通信

这里波特率需要和蓝牙波特率相同,否则无法实现数据发送

三、软件代码

代码如下(示例):

1.马达模块

Motor.c

一个电机2个引脚,一正一负驱动,通过对引脚赋值高低电平进行方向控制。

#include "Motor.h"
#include "gpio.h"
#include "main.h"


void Lower(){
	HAL_GPIO_WritePin(Motor1_1_GPIO_Port,Motor1_1_Pin,GPIO_PIN_RESET);
	HAL_GPIO_WritePin(Motor1_2_GPIO_Port,Motor1_2_Pin,GPIO_PIN_SET);

	HAL_GPIO_WritePin(Motor2_1_GPIO_Port,Motor2_1_Pin,GPIO_PIN_RESET);
	HAL_GPIO_WritePin(Motor2_2_GPIO_Port,Motor2_2_Pin,GPIO_PIN_SET); 
}

void Upper(){
	HAL_GPIO_WritePin(Motor1_1_GPIO_Port,Motor1_1_Pin,GPIO_PIN_SET);
	HAL_GPIO_WritePin(Motor1_2_GPIO_Port,Motor1_2_Pin,GPIO_PIN_RESET);

	HAL_GPIO_WritePin(Motor2_1_GPIO_Port,Motor2_1_Pin,GPIO_PIN_SET);
	HAL_GPIO_WritePin(Motor2_2_GPIO_Port,Motor2_2_Pin,GPIO_PIN_RESET); 
}


void Left(){
	HAL_GPIO_WritePin(Motor1_1_GPIO_Port,Motor1_1_Pin,GPIO_PIN_RESET);
	HAL_GPIO_WritePin(Motor1_2_GPIO_Port,Motor1_2_Pin,GPIO_PIN_SET);

	HAL_GPIO_WritePin(Motor2_1_GPIO_Port,Motor2_1_Pin,GPIO_PIN_SET);
	HAL_GPIO_WritePin(Motor2_2_GPIO_Port,Motor2_2_Pin,GPIO_PIN_RESET); 
}


void Right(){
	HAL_GPIO_WritePin(Motor1_1_GPIO_Port,Motor1_1_Pin,GPIO_PIN_SET);
	HAL_GPIO_WritePin(Motor1_2_GPIO_Port,Motor1_2_Pin,GPIO_PIN_RESET);

	HAL_GPIO_WritePin(Motor2_1_GPIO_Port,Motor2_1_Pin,GPIO_PIN_RESET);
	HAL_GPIO_WritePin(Motor2_2_GPIO_Port,Motor2_2_Pin,GPIO_PIN_SET); 
}

void Stop(){
	HAL_GPIO_WritePin(Motor1_1_GPIO_Port,Motor1_1_Pin,GPIO_PIN_RESET);
	HAL_GPIO_WritePin(Motor1_2_GPIO_Port,Motor1_2_Pin,GPIO_PIN_RESET);

	HAL_GPIO_WritePin(Motor2_1_GPIO_Port,Motor2_1_Pin,GPIO_PIN_RESET);
	HAL_GPIO_WritePin(Motor2_2_GPIO_Port,Motor2_2_Pin,GPIO_PIN_RESET); 
}

Motor.h

#ifndef _MOTOR_H_
#define _MOTOR_H_

void Upper(void);
void Lower(void);
void Left(void);
void Right(void);
void Stop(void);

#endif

2.main.c

uint8_t Receive;
while (1)
{
	HAL_UART_Receive(&huart1,&Receive,1,HAL_MAX_DELAY);//等待蓝牙发送数据
	if(Receive == w)
		Upper();
	else if(Receive == s)
		Lower();
	else if(Receive == a)
		Left();
	else if(Receive == d)
		Right();
	else
		Stop();
}

四、手机蓝牙APP

在手机蓝牙APP上开启编辑模式,修改按钮发送数据,连接蓝牙后就可以发送数据实现控制

经验分享 程序员 微信小程序 职场和发展