【GD32L233C-START】3、pwm实现呼吸灯

2022-02-09 09:06:40 浏览数 (1)

1、硬件连接

2、PWM通道

可以看出,PC6对应的是TIME2的CH0通道。

3、实现方法

通过调节占空比,递增占空比,led逐渐变亮,视觉上是呼吸灯的效果。

4、核心代码

(1)pwm初始化

代码语言:javascript复制
void PwmInit(void)
{	
    rcu_periph_clock_enable(RCU_GPIOC);
    /* TIMER1 GPIO */
    gpio_mode_set(GPIOC, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_6 );
    gpio_output_options_set(GPIOC, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_6);
    gpio_af_set(GPIOC, GPIO_AF_1, GPIO_PIN_6);

    //64000000/6400=10k
	//TIMER2CLK = SystemCoreClock/6400 = 0.01MHz, the period is 1s(100/10000).=0.01s=10ms=100hz

    timer_oc_parameter_struct timer_ocinitpara;
    timer_parameter_struct timer_initpara;

    /* enable the peripherals clock */
    rcu_periph_clock_enable(RCU_TIMER2);

    /* deinit a TIMER */
    timer_deinit(TIMER2);
    /* initialize TIMER init parameter struct */
    timer_struct_para_init(&timer_initpara);
    /* TIMER2 configuration */
    timer_initpara.prescaler        = 6399;
    timer_initpara.alignedmode      = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection = TIMER_COUNTER_UP;
    timer_initpara.period           = 99;
    timer_initpara.clockdivision    = TIMER_CKDIV_DIV1;
    timer_init(TIMER2, &timer_initpara);

    /* initialize TIMER channel output parameter struct */
    timer_channel_output_struct_para_init(&timer_ocinitpara);
    /* configure TIMER channel output function */
    timer_ocinitpara.outputstate    = TIMER_CCX_ENABLE;
    timer_ocinitpara.ocpolarity     = TIMER_OC_POLARITY_HIGH;
    timer_channel_output_config(TIMER2, TIMER_CH_0, &timer_ocinitpara);
    timer_channel_output_pulse_value_config(TIMER2, TIMER_CH_0, 99);
    /* CH0 configuration in OC timing mode */
    timer_channel_output_mode_config(TIMER2, TIMER_CH_0, TIMER_OC_MODE_PWM0);
    /* enable a TIMER */
    timer_enable(TIMER2);
}

(2)更改占空比

代码语言:javascript复制
void PwmOut(void)
{
	static uint32_t tick=0;
	static  uint8_t out=1;
	
	if(SystemGetTick()-tick>200)
	{
		tick=SystemGetTick();
		out=out 10;
		
		if(out>100)
		{
			out=1;
		}
		timer_channel_output_pulse_value_config(TIMER2, TIMER_CH_0, out-1);
	}
}

5、现象

6、示波器测量波形

0 人点赞