材料:
(1)stm32f407zgt6最小系统开发板
(2)l298n电机驱动模块1个
(3)四个电机
(4)JDY-31蓝牙模块
一、组装
(1)L298N电机驱动模块与stm32开发板接线如下图:
(2)蓝牙接线:
VCC接stm32开发板的3.3v~5v,GND接stm32开发板的GND,TXD接stm32开发板的PA10引脚,RXD接stm32开发板的PA9引脚。
二、主要程序
1、STM32CUBEMX配置如下:
(1)引脚配置:
说明:
1)定义2个电机的引脚,都是GPIOB
2)motor11和motor12分别为电机(1)的两个引脚
3)motor21和motor22分别为电机(2)的两个引脚
(2)配置RCC时钟:
(3) 时钟的配置:
(4)UART配置:
1)选择所需UART
2)选择Mode为异步通讯方式(常用)
3)设置基础参数:波特率为115200 Bits/s;传输数据长度为8 Bit;奇偶检验无;停止位1;接收和发送都使能 。
注意 CubeMX默认打开的引脚确实为最常用的引脚,但有时与电路板并不相符。
三、程序
main.c
while (1)
{
HAL_UART_Receive(&huart1,&rx,1,HAL_MAX_DELAY);
if(rx=='o')
{
car_go_straight();//前进
}
else if(rx=='f')
{
car_go_after();//后退
}
else if(rx=='l')
{
car_go_left();//左转
}
else if(rx=='r')
{
car_go_right();//右转
}
else
{
car_go_ahead();//停止
}
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
如果发送个字符“o”小车就会前进,发送个字符“f”小车就会后退,发送个字符“l”小车就会左转,发送个字符“r”小车就会右转,发送其他字符小车就停止 。
main.h
#include "main.h"
电机程序:
Motor.c
#include "motor.h"
//前进
void car_go_straight(void)
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_RESET);
}
//右转
void car_go_right(void)
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_SET);
}
//左转
void car_go_left(void)
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_RESET);
}
//停止
void car_go_ahead(void)
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_RESET);
}
//后退
void car_go_after(void)
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_SET);
}
Motor.h
#ifndef __MOTOR_H_
#define __MOTOR_H_
#include "main.h"
void car_go_straight(void);
void car_go_right(void);
void car_go_left(void);
void car_go_ahead(void);
void car_go_after(void);
#endif
4、手机端调试软件
APP:SPP蓝牙串口