赞
踩
先看看结果:
这个是根据上午发的文章的基础上更改的,很简单,只是用了一个定时器,初始化了4个比较器而已,就可以单独的控制每一路PWM的占空比了,好了,把源文件展示一下,完事去接孩子放学。
PWM.c文件:
- #include "stm32f10x.h" // Device header
-
-
-
- void PWM_Init(void)
- {
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
-
- TIM_InternalClockConfig(TIM2);
-
- TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
- TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
- TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
- TIM_TimeBaseInitStruct.TIM_Period = 100-1;
- TIM_TimeBaseInitStruct.TIM_Prescaler = 720-1;
- TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
- TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
-
- TIM_OCInitTypeDef TIM_OCInitStruct;
- TIM_OCStructInit(&TIM_OCInitStruct);
- TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
- TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
- TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
- TIM_OCInitStruct.TIM_Pulse = 0;
-
- TIM_OC1Init(TIM2, &TIM_OCInitStruct);
- TIM_OC2Init(TIM2, &TIM_OCInitStruct);
- TIM_OC3Init(TIM2, &TIM_OCInitStruct);
- TIM_OC4Init(TIM2, &TIM_OCInitStruct);
-
- GPIO_InitTypeDef GPIO_InitStruct;
- GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
- GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 |GPIO_Pin_3;
- GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init(GPIOA, &GPIO_InitStruct);
-
- TIM_Cmd(TIM2, ENABLE);
-
- }
-
-
- // 设置PWM的函数,第一个参数是第几个比较器的意思, 第二个参数是这个比较器的值是多少?
- void SET_PWM(uint16_t num, uint16_t key)
- {
- if(num == 1)
- {
- TIM_SetCompare1(TIM2, key);
- }
- if(num == 2)
- {
- TIM_SetCompare2(TIM2, key);
- }
- if(num == 3)
- {
- TIM_SetCompare3(TIM2, key);
- }
- if(num == 4)
- {
- TIM_SetCompare4(TIM2, key);
- }
- }
-
-
PWM.h文件:
- #ifndef __PWM_H
- #define __PWM_H
-
-
- void PWM_Init(void);
-
- void SET_PWM(uint16_t num, uint16_t key);
-
- #endif
-
main.c主函数文件:
- #include "stm32f10x.h" // Device header
- #include "OLED.h"
- #include "PWM.h"
-
- int main(void)
- {
-
- OLED_Init(); //oled 屏幕初始化
- PWM_Init();
-
-
- SET_PWM(1, 10); //设置通道1的占空比为10%
- SET_PWM(2, 20); //设置通道2的占空比为20%
- SET_PWM(3, 30); //设置通道3的占空比为30%
- SET_PWM(4, 40); //设置通道4的占空比为40%
- while(1)
- {
-
- }
- }
其实整个过程只是增加了一个函数而已:这个函数就是:
好了,自己理解吧。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。