gd32f303定时器2通道0出发adc2中断,中断时间100微秒 ,代码
时间: 2024-03-10 14:49:19 浏览: 119
定时器中断
好的,以下是一个简单的基于GD32F303定时器2和ADC2的中断的代码示例,中断时间为100微秒:
```c
#include "gd32f30x.h"
void adc_config(void);
void timer_config(void);
uint16_t adc_value;
int main(void)
{
adc_config();
timer_config();
while(1);
}
void adc_config(void)
{
rcu_periph_clock_enable(RCU_ADC1);
rcu_adc_clock_config(RCU_CKADC_CKAPB2_DIV8);
adc_sync_mode_config(ADC_SYNC_MODE_INDEPENDENT);
adc_mode_config(ADC_MODE_FREE);
adc_data_alignment_config(ADC1, ADC_DATAALIGN_RIGHT);
adc_channel_length_config(ADC1, ADC_INSERTED_CHANNEL, 1);
adc_inserted_channel_config(ADC1, 0, ADC_CHANNEL_1, ADC_SAMPLETIME_55POINT5);
adc_external_trigger_source_config(ADC1, ADC_INSERTED_CHANNEL, ADC0_1_EXTTRIG_INSERTED_NONE);
adc_external_trigger_config(ADC1, ADC_INSERTED_CHANNEL, ENABLE);
adc_enable(ADC1);
}
void timer_config(void)
{
rcu_periph_clock_enable(RCU_TIMER2);
timer_oc_parameter_struct timer_ocinitpara;
timer_parameter_struct timer_initpara;
timer_ic_parameter_struct timer_icinitpara;
timer_deinit(TIMER2);
timer_struct_para_init(&timer_initpara);
timer_initpara.prescaler = 95; // 定时器分频系数
timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
timer_initpara.counterdirection = TIMER_COUNTER_UP;
timer_initpara.period = 1000; // 定时器重载值
timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
timer_init(TIMER2, &timer_initpara);
timer_struct_para_init(&timer_icinitpara);
timer_icinitpara.icpolarity = TIMER_IC_POLARITY_FALLING;
timer_icinitpara.icselection = TIMER_IC_SELECTION_DIRECTTI;
timer_icinitpara.icprescaler = TIMER_IC_PSC_DIV1;
timer_icinitpara.icfilter = 0x0;
timer_input_capture_config(TIMER2, TIMER_CH_0, &timer_icinitpara);
timer_struct_para_init(&timer_ocinitpara);
timer_ocinitpara.ocpolarity = TIMER_OC_POLARITY_HIGH;
timer_ocinitpara.ocoutputstate = TIMER_OC_OUTPUT_STATE_ENABLE;
timer_ocinitpara.ocidlestate = TIMER_OC_IDLE_STATE_RESET;
timer_ocinitpara.compare = 500; // 比较值
timer_output_compare_config(TIMER2, TIMER_CH_0, &timer_ocinitpara);
nvic_irq_enable(TIMER2_IRQn, 0, 0);
timer_interrupt_enable(TIMER2, TIMER_INT_CH0);
timer_enable(TIMER2);
}
void TIMER2_IRQHandler(void)
{
if (timer_interrupt_flag_get(TIMER2, TIMER_INT_CH0))
{
adc_software_trigger_enable(ADC1, ADC_INSERTED_CHANNEL); // ADC转换触发
while(!adc_flag_get(ADC1, ADC_FLAG_EOC));
adc_value = adc_inserted_data_read(ADC1, ADC_INSERTED_CHANNEL);
timer_interrupt_flag_clear(TIMER2, TIMER_INT_CH0);
}
}
```
在这个例子中,我们使用定时器2通道0的比较匹配来触发中断,ADC2在中断服务程序中进行转换并将结果存储在变量adc_value中。注意,在这个例子中,我们使用了一个简单的while循环来等待ADC转换完成,这可能会导致程序卡死。在实际应用中,您应该实现更好的等待ADC转换完成的方法,例如使用ADC转换完成中断。
阅读全文