GD32F450 - PWM输出(LED呼吸灯)
Jgcoder 2022-11-01 21:22:00
GD32F450
GD32
说明
GD32F450 - PWM输出(LED呼吸灯)
# 演示案例
- 通过PWM来展示呼吸灯的效果
# 步骤
- 实现PWM的基本步骤
- 配置通道引脚 GPIO
- 配置定时器
- 配置输出结构体
- 配置定时器输出通道
- 配置定时器输出通道占空比
- 定时器自动重载影子使能
# 代码:
void app_pwm_init(void){
timer_parameter_struct timer_initpara; // 定义定时器结构体
timer_oc_parameter_struct timer_ocintpara; //定时器比较输出结构体
//配置GPIO引脚
rcu_periph_clock_enable(RCU_GPIOA); //开启时钟
gpio_mode_set(GPIOA,GPIO_MODE_AF,GPIO_PUPD_NONE,GPIO_PIN_5); //设置GPIO模式
gpio_output_options_set(GPIOA,GPIO_OTYPE_PP,GPIO_OSPEED_50MHZ,GPIO_PIN_5); //设置GPIO输出模式和速度
gpio_af_set(GPIOA,GPIO_AF_1,GPIO_PIN_5); //配置 IO 为定时器的通道,GPIO的复用
rcu_periph_clock_enable(RCU_TIMER1); //开启定时器时钟
rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4); // 配置定时器时钟
timer_deinit(TIMER1); // 复位定时器
timer_initpara.prescaler = 200-1; //预分频值(0~65535) PSC_CLK= 200MHZ / 200 = 1MHZ
timer_initpara.alignedmode = TIMER_COUNTER_EDGE; // 边缘对齐
timer_initpara.counterdirection = TIMER_COUNTER_UP; // 向上计数
timer_initpara.period = 10000 -1; // 周期 T = 10000 * 1MHZ = 10ms f = 100HZ
/* 在输入捕获的时候使用 数字滤波器使用的采样频率之间的分频比例 */
timer_initpara.clockdivision = TIMER_CKDIV_DIV1; // 分频因子
/* 只有高级定时器才有 配置为 x,就重复 x+1 次进入中断 */
timer_initpara.repetitioncounter = 0; // 重复计数器 0-255
timer_init(TIMER1,&timer_initpara); // 初始化定时器
//配置输出结构体
timer_ocintpara.ocpolarity = TIMER_OC_POLARITY_HIGH; //通道输出的极性,低电平有效还是高电平有效
timer_ocintpara.outputstate = TIMER_CCX_ENABLE; //通道输出状态,使能 TIMER_CCX_ENABLE,使能 PWM 输出到端口
//配置定时器输出功能
timer_channel_output_config(TIMER1,TIMER_CH_0,&timer_ocintpara);
// 配置定时器输出通道占空比
// 设置输出脉冲值为 5000-1,设置的定时器的周期为 10000-1,则占空比为 5000 / 10000 = 50%。
timer_channel_output_pulse_value_config(TIMER1,TIMER_CH_0,0);
timer_channel_output_mode_config(TIMER1,TIMER_CH_0,TIMER_OC_MODE_PWM0); // 配置定时器通道输出比较模式
timer_channel_output_shadow_config(TIMER1,TIMER_CH_0,TIMER_OC_SHADOW_DISABLE); // 配置定时器通道输出影子寄存器
// 定时器自动重载影子使能
timer_auto_reload_shadow_enable(TIMER1);
timer_enable(TIMER1); //使能定时器
}
void App_pam_led(void){
static uint16_t value = 0;
static uint8_t direct = 0;
if(direct == 0){
value += 300;
if(value > 10000)
direct = 1; // 改变方向
}else{
value -= 300;
if(value <= 0)
direct = 0; // 改变方向
}
timer_channel_output_pulse_value_config(TIMER1,TIMER_CH_0,value); // 配置定时器通道输出脉冲值
delay_1ms(50);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 效果展示
算了吧 这个视频转GIF的效果不太理想
转载请注明出处且带本文链接:https://www.daodaoyouli.com