新手入门
- 积分
- 11
- 金钱
- 11
- 注册时间
- 2017-3-12
- 在线时间
- 4 小时
|
3金钱
不知道是不是这里不该用延时函数,该写中断延时函数,麻烦大神解答下,第一次提问好紧张,谢谢啦
代码如下:
void TIM2_PWM_Init(u32 arr,u32 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource0,GPIO_AF_TIM2);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4|GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA,GPIO_Pin_4);
GPIO_ResetBits(GPIOA,GPIO_Pin_5);
TIM_TimeBaseStructure.TIM_Prescaler=psc;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period=arr;
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructurE);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM2,ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
int main(void)//首先将占空比设为0,然后设为20%,延时10s过后设为70%占空比。 实际运行时电机在20%占空比处会循环三次,转30s(刚好是设置的10s的三倍),然后切换成70%占空比
{
u16 pwmval=1000;
delay_init(168);
TIM2_PWM_Init(1000-1,84-1);
TIM_SetCompare1(TIM2,pwmval);
delay_us(100);
pwmval=800;
TIM_SetCompare1(TIM2,pwmval);
delay_ms(10000);
pwmval=300;
TIM_SetCompare1(TIM2,pwmval);
/*delay_ms(1000);
pwmval=1000;
TIM_SetCompare1(TIM2,pwmval);*/ 如果多出这三句,程序原本意图是20%占空比转10s,70%占空比转1s然后停下。实际情况是慢10s快1s,慢10s快1s,慢10s快1s(也是刚好三个循环)然后停下
}
|
|