[GD32L233C-START Review] 3. PWM to achieve breathing light
[Copy link]
Related articles:
[GD32L233C-START Review] 1. GD32L233C-START with obvious advantages and disadvantages (unboxing)
[GD32L233C-START Review] 2. Non-blocking way to light up, blink, blink, blink...
1. Hardware connection
2. PWM channel
It can be seen that PC6 corresponds to the CH0 channel of TIME2.
3. Implementation method
By adjusting the duty cycle and increasing it, the LED gradually becomes brighter, creating a breathing light effect visually.
4. Core code
(1) PWM initialization
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) Change the duty cycle
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. Phenomenon
6. Oscilloscope measurement waveform
|