GD32f150写一个PWM输出程序
时间: 2023-05-13 11:07:25 浏览: 146
PWM输出程序
好的,以下是一个简单的GD32f150 PWM输出程序的示例代码:
```c
#include "gd32f1x0.h"
void pwm_init(void)
{
/* 使能GPIO时钟 */
rcu_periph_clock_enable(RCU_GPIOA);
/* 配置PA1为复用输出模式 */
gpio_mode_set(GPIOA, GPIO_MODE_AF_PP, GPIO_PUPD_NONE, GPIO_PIN_1);
gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_1);
/* 使能TIMER时钟 */
rcu_periph_clock_enable(RCU_TIMER1);
/* 配置TIMER1为PWM模式 */
timer_oc_parameter_struct timer_ocinitpara;
timer_parameter_struct timer_initpara;
timer_deinit(TIMER1);
timer_struct_para_init(&timer_initpara);
timer_initpara.prescaler = 0; /* 不分频 */
timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
timer_initpara.counterdirection = TIMER_COUNTER_UP;
timer_initpara.period = 1000; /* PWM周期为1ms */
timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
timer_init(TIMER1, &timer_initpara);
timer_oc_struct_para_init(&timer_ocinitpara);
timer_ocinitpara.ocpolarity = TIMER_OC_POLARITY_HIGH;
timer_ocinitpara.outputstate = TIMER_CCX_ENABLE;
timer_ocinitpara.ocidlestate = TIMER_OC_IDLE_STATE_LOW;
timer_ocinitpara.compare = 500; /* PWM占空比为50% */
timer_channel_output_config(TIMER1, TIMER_CH_1, &timer_ocinitpara);
timer_auto_reload_shadow_enable(TIMER1);
timer_enable(TIMER1);
}
int main(void)
{
pwm_init();
while (1) {
/* 程序主循环 */
}
return 0;
}
```
这个程序使用TIMER1的CH1通道输出PWM信号,占空比为50%,周期为1ms。你可以根据需要修改占空比和周期。
阅读全文