新手入门
- 积分
- 7
- 金钱
- 7
- 注册时间
- 2023-9-2
- 在线时间
- 1 小时
|
1金钱
老哥们看看代码吧,我是刚接触stm32不久,我代码的问题在哪里啊,困扰我两天了
#include "stm32f10x.h"
#include "delay.h"
// 定义控制信号的GPIO引脚
#define EN1_PIN GPIO_Pin_0
#define DIR1_PIN GPIO_Pin_1
#define PWM1_PIN GPIO_Pin_8
#define EN2_PIN GPIO_Pin_3
#define DIR2_PIN GPIO_Pin_4
#define PWM2_PIN GPIO_Pin_5
// 定义定时器和通道
#define PWM_TIMER TIM1
#define PWM_TIMER_CH1 TIM_OC1Init
#define PWM_TIMER_CH2 TIM_OC2Init
#define PWM_TIMER_CH3 TIM_OC3Init
#define PWM_TIMER_CH4 TIM_OC4Init
// 定义PWM占空比范围
#define PWM_MIN 0
#define PWM_MAX 99
// 初始化GPIO引脚和定时器
void GPIO_Timer_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
// 使能GPIO和定时器时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
// 配置EN1引脚
GPIO_InitStructure.GPIO_Pin = EN1_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置DIR1引脚
GPIO_InitStructure.GPIO_Pin = DIR1_PIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置PWM1引脚
GPIO_InitStructure.GPIO_Pin = PWM1_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置EN2引脚
GPIO_InitStructure.GPIO_Pin = EN2_PIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置DIR2引脚
GPIO_InitStructure.GPIO_Pin = DIR2_PIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置PWM2引脚
GPIO_InitStructure.GPIO_Pin = PWM2_PIN;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置定时器
TIM_TimeBaseInitStructure.TIM_Prescaler = (SystemCoreClock / 1000000) - 1; // 1us的计数单位
TIM_TimeBaseInitStructure.TIM_Period = 999; // 1ms的周期
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(PWM_TIMER, &TIM_TimeBaseInitStructure);
// 配置PWM通道
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCNPolarity_High;
PWM_TIMER_CH1(PWM_TIMER, &TIM_OCInitStructure);
PWM_TIMER_CH2(PWM_TIMER, &TIM_OCInitStructure);
PWM_TIMER_CH3(PWM_TIMER, &TIM_OCInitStructure);
PWM_TIMER_CH4(PWM_TIMER, &TIM_OCInitStructure);
// 使能定时器
TIM_Cmd(PWM_TIMER, ENABLE);
TIM_CtrlPWMOutputs(TIM1, ENABLE);
}
// 设置电机状态
void SetMotorState1(void)
{
// 设置EN1引脚
GPIO_SetBits(GPIOA, EN1_PIN);
// 设置DIR1引脚
GPIO_SetBits(GPIOA, DIR1_PIN);
// 设置PWM1占空比
TIM_SetCompare1(PWM_TIMER, PWM_MAX/2);
}
int main(void)
{
// 初始化GPIO引脚和定时器
GPIO_Timer_Init();
while (1)
{
// 循环执行其他任务
SetMotorState1();
}
}
|
|