gd32f303定时器2通道0触发adc2中断代码
时间: 2024-03-10 10:49:21 浏览: 205
定时器中断驱动源代码
好的,以下是一个基于GD32F303定时器2和ADC2的中断的代码示例,定时器2通道0触发ADC2中断:
```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);
adc_interrupt_enable(ADC1, ADC_INT_EOC);
}
void timer_config(void)
{
rcu_periph_clock_enable(RCU_TIMER2);
timer_oc_parameter_struct timer_ocinitpara;
timer_parameter_struct timer_initpara;
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_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 ADC1_IRQHandler()
{
if(adc_flag_get(ADC1, ADC_FLAG_EOC))
{
adc_value = adc_regular_data_read(ADC1);
adc_flag_clear(ADC1, ADC_FLAG_EOC);
}
}
void TIMER2_IRQHandler(void)
{
if (timer_interrupt_flag_get(TIMER2, TIMER_INT_CH0))
{
adc_software_trigger_enable(ADC1, ADC_INSERTED_CHANNEL); // ADC转换触发
timer_interrupt_flag_clear(TIMER2, TIMER_INT_CH0);
}
}
```
在这个例子中,我们使用定时器2通道0的比较匹配来触发中断,然后在中断服务程序中触发ADC转换。注意,在这个例子中,我们使用了ADC转换完成中断来等待ADC转换完成,这比等待ADC转换完成的while循环更好。同时注意,我们也为ADC1启用了转换完成中断。
阅读全文