帮我写个代码,GD32F427定时器2的输入捕获,通过串口打印
时间: 2024-01-01 12:06:04 浏览: 79
GD32AppF303-Demo程序源码
好的,以下是基于GD32F427芯片的定时器2输入捕获的代码,并通过串口打印:
```c
#include "gd32f4xx.h"
#include "systick.h"
#include "stdio.h"
void gpio_config(void);
void usart_config(void);
void timer_config(void);
void nvic_config(void);
void delay_us(uint32_t nus);
void delay_ms(uint32_t nms);
uint32_t capture_value = 0;
int main(void)
{
gpio_config();
usart_config();
timer_config();
nvic_config();
while (1)
{
printf("Capture Value: %lu us\n", capture_value);
delay_ms(1000);
}
}
void gpio_config(void)
{
rcu_periph_clock_enable(RCU_GPIOB);
gpio_init(GPIOB, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_10);
gpio_pin_remap_config(GPIO_TIM2_CH2_IRC_REMAP, ENABLE);
}
void usart_config(void)
{
rcu_periph_clock_enable(RCU_USART0);
rcu_periph_clock_enable(RCU_GPIOA);
gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);
gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_10);
usart_deinit(USART0);
usart_baudrate_set(USART0, 115200U);
usart_word_length_set(USART0, USART_WL_8BIT);
usart_stop_bit_set(USART0, USART_STB_1BIT);
usart_parity_config(USART0, USART_PM_NONE);
usart_hardware_flow_rts_config(USART0, USART_RTS_DISABLE);
usart_hardware_flow_cts_config(USART0, USART_CTS_DISABLE);
usart_receive_config(USART0, USART_RECEIVE_ENABLE);
usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
usart_enable(USART0);
}
void timer_config(void)
{
rcu_periph_clock_enable(RCU_TIMER2);
timer_deinit(TIMER2);
timer_ic_parameter_struct timer_icinitpara;
timer_icinitpara.ic_polarity = TIMER_IC_POLARITY_RISING;
timer_icinitpara.ic_selection = TIMER_IC_SELECTION_DIRECTTI;
timer_icinitpara.ic_prescaler = TIMER_IC_PSC_DIV1;
timer_icinitpara.ic_filter = 0;
timer_input_capture_config(TIMER2, TIMER_CH_2, &timer_icinitpara);
timer_enable(TIMER2);
}
void nvic_config(void)
{
nvic_priority_group_set(NVIC_PRIGROUP_PRE2_SUB2);
nvic_irq_enable(TIMER2_IRQn, 0, 0);
}
void delay_us(uint32_t nus)
{
uint32_t ticks;
uint32_t told, tnow, tcnt = 0;
uint32_t reload = SysTick->LOAD;
ticks = nus * (SystemCoreClock / 1000000);
tcnt = 0;
told = SysTick->VAL;
while (1)
{
tnow = SysTick->VAL;
if (tnow != told)
{
if (tnow < told)
tcnt += told - tnow;
else
tcnt += reload - tnow + told;
told = tnow;
if (tcnt >= ticks)
break;
}
}
}
void delay_ms(uint32_t nms)
{
uint32_t i;
for (i = 0; i < nms; i++)
delay_us(1000);
}
void TIMER2_IRQHandler(void)
{
if (timer_interrupt_flag_get(TIMER2, TIMER_CH_2) != RESET)
{
capture_value = timer_channel_capture_value_register_get(TIMER2, TIMER_CH_2) / (SystemCoreClock / 1000000);
timer_interrupt_flag_clear(TIMER2, TIMER_CH_2);
}
}
```
在此代码中,我们使用了定时器2的输入捕获功能,通过调用timer_input_capture_config()函数配置了定时器2的通道2为输入捕获模式,并在TIMER2_IRQHandler()中处理输入捕获事件。在主函数中,我们通过串口打印输入捕获到的值。
注意:在此代码中使用的是USART0串口,如果您使用的是其他串口,请相应修改代码。
阅读全文