直流馬達驅動_PWM加減速(STM32F4 CubeMX)

一、前期準備
單片機:STM32F407VET6
開發環境:MDK5.14
庫函數:STM32Cube_FW_F4_V1.16.0
直流電機模塊:淘寶有售
在這裏插入圖片描述在這裏插入圖片描述
二、實驗效果
1)按鍵KEY1按下,正轉->反轉->停止,循環下去;
2)按鍵KEY2按下,PWM增加5%,一直加到100%;
3)按鍵KEY3按下,PWM減小5%,一直減到0%。
4)PWM波爲20K,正轉啓動要到30%,反轉啓動要到50%,

三、驅動原理
直流有刷電機的驅動十分簡單,通電即可轉動。運用H橋可以直接驅動電機正反轉。
在這裏插入圖片描述
當Q1、Q4導通,電機正轉;Q2、Q3導通電機反轉。驅動電路使用淘寶上的H橋模塊
在這裏插入圖片描述
邏輯輸入的IN1、IN2爲OUT1與OUT2的控制腳。IN1、IN2電平相反時候,電機實現正反轉;IN1、IN2電平相同時,電機停轉。

CubeMX TIM2配置如下:
在這裏插入圖片描述
需要完整工程的請加QQ:1002521871,驗證:呵呵!

四、驅動代碼
motor.h

#ifndef __MOTOR_H__
#define	__MOTOR_H__
#include "stm32f4xx_hal.h"
#include "user_gpio.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"

#define		KEY1	PEin(10)
#define		KEY2	PEin(11)
#define		KEY3	PEin(12)

extern uint8_t PWMCapture1,PWMCapture2;
extern uint8_t MoterMode;

extern void Moter_StartPWM(void);
extern void Motor_Test(void);
#endif

motor.c

#include "motor.h"

extern TIM_HandleTypeDef htim2;
uint8_t PWMCapture1  = 30, PWMCapture2 = 30;
uint8_t MoterMode = 0;

void Moter_StartPWM(void)
{
	HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
	HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);
	
	__HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_1, 100);
	__HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_2, 100);
}

void Motor_Test(void)
{
	if (KEY1 == 0)			//正轉
	{
		HAL_Delay(5);
		if (KEY1 == 0)
		{
			while(KEY1 == 0);
			MoterMode ++;
		}
	}
	
	switch(MoterMode)
	{
		case 1:		//正轉
			PWMCapture2 = 0;
			__HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_2, PWMCapture2);
			
			if (KEY2 == 0)			
			{
				HAL_Delay(5);
				if (KEY2 == 0)
				{
					while(KEY2 == 0);
					PWMCapture1 += 5;
					if (PWMCapture1 >= 100)		//Duty Cycle Max = 100%
					{
						PWMCapture1 = 100;
					}
					printf("CH1 Duty Cycle = %02d%%\r\n", PWMCapture1);
				}
			} 
			
			if (KEY3 == 0)			
			{
				HAL_Delay(5);
				if (KEY3 == 0)
				{
					while(KEY3 == 0);
					PWMCapture1 -= 5;
					if (PWMCapture1 <= 5)		//Duty Cycle Min = 5%
					{
						PWMCapture1 = 5;
					}
					printf("CH1 Duty Cycle = %02d%%\r\n", PWMCapture1);
				}
			} 
			
			__HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_1, PWMCapture1);
			break;
		case 2:		//反轉
			PWMCapture1 = 0;
			__HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_2, PWMCapture2);
			
			if (KEY2 == 0)			
			{
				HAL_Delay(5);
				if (KEY2 == 0)
				{
					while(KEY2 == 0);
					PWMCapture2 += 5;
					if (PWMCapture2 >= 100)		//Duty Cycle Max = 100%
					{
						PWMCapture2 = 100;
					}
					printf("CH2 Duty Cycle = %02d%%\r\n", PWMCapture2);
				}
			} 
			
			if (KEY3 == 0)			
			{
				HAL_Delay(5);
				if (KEY3 == 0)
				{
					while(KEY3 == 0);
					PWMCapture2 -= 5;
					if (PWMCapture2 <= 5)		//Duty Cycle Min = 5%
					{
						PWMCapture2 = 5;
					}
					printf("CH2 Duty Cycle = %02d%%\r\n", PWMCapture2);
				}
			} 
			
			__HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_2, PWMCapture2);
			break;
		default:
			MoterMode = 0;
			break;
	}
}

由於作者能力有限,有不妥之處歡迎指正,郵箱[email protected]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章