//使能时钟
rcu_periph_clock_enable(RCU_GPIOE);
//配置引脚复用,无上下拉。
gpio_mode_set(GPIOE, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_9);
gpio_output_options_set(GPIOE, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);
gpio_mode_set(GPIOE, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_11);
gpio_output_options_set(GPIOE, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_11);
//设置复用
gpio_af_set(GPIOE, GPIO_AF_1, GPIO_PIN_9);
gpio_af_set(GPIOE, GPIO_AF_1, GPIO_PIN_11);
GPIO复用 GPIO_AF_1: TIMER0, TIMER1
GPIO_AF_2: TIMER2, TIMER3, TIMER4
GPIO_AF_3: TIMER7, TIMER8, TIMER9, TIMER10
//使能时钟
rcu_periph_clock_enable(RCU_TIMER0);
//设置定时器频率
rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL2);
// 重置 TIMER0 配置
timer_deinit(TIMER0);
// 初始化定时器的参数
tim->Init.prescaler = 72; // 预分频器设置为72,将时钟频率降低到原来的1/72
tim->Init.period = 99; // 自动重装载值设置为99,决定了计数周期
tim->Init.alignedmode = TIMER_COUNTER_EDGE; // 边沿对齐模式
tim->Init.counterdirection = TIMER_COUNTER_UP; // 计数器向上计数
tim->Init.clockdivision = TIMER_CKDIV_DIV1; // 时钟分频因子设置为1
tim->Init.repetitioncounter = 0; // 重复计数器设置为0
// 初始化 TIMER0
timer_init(TIMER0, &tim->Init);
// 配置定时器输出比较(OC)参数
timer_ocintpara.ocpolarity = TIMER_OC_POLARITY_HIGH; // OC 极性高
timer_ocintpara.outputstate = TIMER_CCX_ENABLE; // 使能 OC 输出
timer_ocintpara.ocnpolarity = TIMER_OCN_POLARITY_HIGH; // OCN 极性高
timer_ocintpara.outputnstate = TIMER_CCXN_DISABLE; // 禁用 OCN 输出
timer_ocintpara.ocidlestate = TIMER_OC_IDLE_STATE_LOW; // OC 空闲状态为低
timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW; // OCN 空闲状态为低
// 配置 PWM 通道
timer_channel_output_config(TIMER0, TIMER_CH_0, &timer_ocintpara);
timer_channel_output_config(TIMER0, TIMER_CH_1, &timer_ocintpara);
// 设置 PWM 通道的脉冲值
timer_channel_output_pulse_value_config(TIMER0, TIMER_CH_0, 98);
timer_channel_output_mode_config(TIMER0, TIMER_CH_0, TIMER_OC_MODE_PWM0);
timer_channel_output_shadow_config(TIMER0, TIMER_CH_0, TIMER_OC_SHADOW_DISABLE);
timer_channel_output_pulse_value_config(TIMER0, TIMER_CH_1, 98);
timer_channel_output_mode_config(TIMER0, TIMER_CH_1, TIMER_OC_MODE_PWM0);
timer_channel_output_shadow_config(TIMER0, TIMER_CH_1, TIMER_OC_SHADOW_DISABLE);
// 启用自动重装载预装载
timer_auto_reload_shadow_enable(TIMER0);
// 配置 TIMER 主输出功能
timer_primary_output_config(TIMER0, ENABLE);
// 启用 TIMER0
timer_enable(TIMER0);
rcu_timer_clock_prescaler_config 决定定时器的时钟源是APB频率的2倍还是4倍,不能超过 AHB,GD32F407AHB最大200M。
timer_channel_output_pulse_value_config 的第三个参数通道输出脉冲值要小于自动重新装载值
timer_primary_output_config 启用定时器的主输出功能,用于高级定时器 ,GD32F4的TIMERx(x=0,7),通用定时器和基本定时器不需要设置。
//设置周期和占空比,使能PWM通道
pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL_0, PWM_period, PWM_period/2);
rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL_1, PWM_period, PWM_period/2);
rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL_0);
rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL_1);