基于GD32F303RCT6芯片 通过PWM与DMA结合硬件控制呼吸灯,用C语言写一份代码
时间: 2023-05-26 21:01:14 浏览: 105
A:
```c
#include "gd32f3x0.h"
#define LED_PIN GPIO_PIN_13
#define LED_PORT GPIOC
#define PWM_CHANNEL TIMER_CH_0
#define PWM_PERIOD 1000
void pwm_init(void);
void dma_init(void);
int main(void)
{
/* 初始化PWM和DMA */
pwm_init();
dma_init();
/* 循环呼吸灯效果 */
uint16_t duty = 0;
uint8_t direction = 0;
while (1)
{
/* 根据呼吸灯方向调整占空比 */
if (direction == 0)
{
duty++;
if (duty == PWM_PERIOD)
{
direction = 1;
}
}
else
{
duty--;
if (duty == 0)
{
direction = 0;
}
}
/* 设置PWM占空比 */
timer_channel_output_pulse_value_config(TIMER0, PWM_CHANNEL, duty);
/* 等待一段时间 */
delay_1ms(10);
}
}
void pwm_init(void)
{
/* GPIO初始化 */
rcu_periph_clock_enable(RCU_GPIOC);
gpio_mode_set(LED_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, LED_PIN);
gpio_output_options_set(LED_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, LED_PIN);
gpio_af_set(LED_PORT, GPIO_AF_2, LED_PIN);
/* 定时器初始化 */
rcu_periph_clock_enable(RCU_TIMER0);
timer_prescaler_config(TIMER0, 71);
timer_auto_reload_value_config(TIMER0, PWM_PERIOD - 1);
timer_enable(TIMER0);
/* PWM输出配置 */
timer_channel_output_mode_config(TIMER0, PWM_CHANNEL, TIM_OC_MODE_PWM0);
timer_channel_output_pulse_value_config(TIMER0, PWM_CHANNEL, 0);
timer_channel_output_state_config(TIMER0, PWM_CHANNEL, TIM_OUTPUT_STATE_ENABLE);
timer_primary_output_config(TIMER0, ENABLE);
}
void dma_init(void)
{
/* DMA初始化 */
rcu_periph_clock_enable(RCU_DMA0);
dma_deinit(DMA0, DMA_CH1);
dma_init_struct.direction = DMA_MEMORY_TO_PERIPH;
dma_init_struct.memory_addr = (uint32_t)&PWM_DUTY_VAL;
dma_init_struct.memory_inc = DMA_MEMORY_INC_NONE;
dma_init_struct.memory_width = DMA_MEMORY_WIDTH_16BIT;
dma_init_struct.periph_addr = (uint32_t)&TIMER0->CCR0;
dma_init_struct.periph_inc = DMA_PERIPH_INC_NONE;
dma_init_struct.periph_width = DMA_PERIPHERAL_WIDTH_16BIT;
dma_init_struct.number = PWM_PERIOD;
dma_init_struct.priority = DMA_PRIORITY_MEDIUM;
dma_init(DMA0, DMA_CH1, &dma_init_struct);
/* 启动DMA */
dma_channel_enable(DMA0, DMA_CH1);
}
```
阅读全文