本帖最后由 MianQi 于 2021-3-17 18:15 编辑
这是main.c:
(我直接从工作空间中粘过来地,因为我发现有些从论坛里拷贝或者下载的代码在工作空间中要做局部的修改才能用,主要是语法上的小错)
/********************************** (C) COPYRIGHT *******************************
* File Name : main.c
* Author : WCH
* Version : V1.0.0
* Date : 2020/09/29
* Description : Main program body.
*******************************************************************************/
#include "debug.h"
#include "led.h"
#include "key.h"
#include "timer.h"
int main(void)
{
u8 t=0;
static u16 ChannelPulse = 0;
static u8 direction = 0;
USART_Printf_Init(115200);
Delay_Init(); //延时函数初始化
LED_Init(); //LED初始化
KEY_Init(); //按键初始化
TIM1_PWMOut_Init(); //PWM输出初始化
TIM_CtrlPWMOutputs(TIM1, DISABLE );
printf("SystemClk:%d\r\n",SystemCoreClock);
while(1)
{
t=KEY_Scan(0); //得到键值
switch(t)
{
case KEY0_PRESS:
TIM_CtrlPWMOutputs(TIM1, ENABLE ); //控制电机开
GPIO_ResetBits(GPIOA,GPIO_Pin_0); //LED1指示当前开关状态,LED1亮电机开,LED1灭电机关
break;
case KEY1_PRESS:
TIM_CtrlPWMOutputs(TIM1, DISABLE ); //控制电机关
GPIO_SetBits(GPIOA,GPIO_Pin_0);
break;
case KEY2_PRESS:
ChannelPulse += 50; //增加占空比,提高电机转速
ChannelPulse = ARR < ChannelPulse ? ARR : ChannelPulse; // 检查占空比的合法性
if(direction%2==0)
{
TIM_SetCompare1(TIM1,ChannelPulse);
TIM_SetCompare4(TIM1,0);
}
else
{
TIM_SetCompare4(TIM1,ChannelPulse);
TIM_SetCompare1(TIM1,0);
}
break;
case KEY3_PRESS:
ChannelPulse -= 50; //减小占空比,降低电机速度
ChannelPulse = ARR < ChannelPulse ? ARR : ChannelPulse; // 检查占空比的合法性
if(direction%2==0)
{
TIM_SetCompare1(TIM1,ChannelPulse);
TIM_SetCompare4(TIM1,0);
}
else
{
TIM_SetCompare4(TIM1,ChannelPulse);
TIM_SetCompare1(TIM1,0);
}
break;
case KEY4_PRESS:
if(direction%2==0) //切换电机转速,即设置两路PWM输出
{
TIM_SetCompare1(TIM1,0);
TIM_SetCompare4(TIM1,0);
Delay_Ms(200);
TIM_SetCompare4(TIM1,ChannelPulse);
TIM_SetCompare1(TIM1,0);
GPIO_ResetBits(GPIOA,GPIO_Pin_1); //LED2指示当前旋转方向,LED2灭表示正向旋转,LED2亮表示反向旋转
printf("DIR:%d\r\n",direction);
direction++;
}
else
{
TIM_SetCompare1(TIM1,0);
TIM_SetCompare4(TIM1,0);
Delay_Ms(200);
TIM_SetCompare1(TIM1,ChannelPulse);
TIM_SetCompare4(TIM1,0);
GPIO_SetBits(GPIOA,GPIO_Pin_1);
printf("DIR:%d\r\n",direction);
direction++;
}
break;
default:
Delay_Ms(10);
}
}
}
|