stm32f103c8t6使用PA和PA1进行ADC1的电压采样,使用DMA方式进行数据传输的代码
时间: 2023-03-30 11:00:57 浏览: 268
基于STM32F103C8T6--通过HAL库实现STM32的ADC+DMA
5星 · 资源好评率100%
你好,以下是使用PA和PA1进行ADC1的电压采样,使用DMA方式进行数据传输的代码:
首先,需要初始化GPIO和ADC1:
```
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN; // Enable GPIOA clock
RCC->APB2ENR |= RCC_APB2ENR_ADC1EN; // Enable ADC1 clock
GPIOA->CRL &= ~(GPIO_CRL_MODE | GPIO_CRL_CNF); // Configure PA as analog input
GPIOA->CRL |= GPIO_CRL_CNF_;
GPIOA->CRL &= ~(GPIO_CRL_MODE1 | GPIO_CRL_CNF1); // Configure PA1 as analog input
GPIOA->CRL |= GPIO_CRL_CNF1_;
ADC1->CR2 |= ADC_CR2_ADON; // Turn on ADC1
ADC1->CR2 |= ADC_CR2_CAL; // Calibrate ADC1
while (ADC1->CR2 & ADC_CR2_CAL); // Wait for calibration to complete
```
然后,需要配置DMA:
```
RCC->AHBENR |= RCC_AHBENR_DMA1EN; // Enable DMA1 clock
DMA1_Channel1->CPAR = (uint32_t)&ADC1->DR; // Set DMA source address to ADC1 data register
DMA1_Channel1->CMAR = (uint32_t)&adc_values; // Set DMA destination address to adc_values array
DMA1_Channel1->CNDTR = ADC_BUFFER_SIZE; // Set DMA transfer size to ADC_BUFFER_SIZE
DMA1_Channel1->CCR |= DMA_CCR1_MINC; // Enable memory increment mode
DMA1_Channel1->CCR |= DMA_CCR1_CIRC; // Enable circular mode
DMA1_Channel1->CCR |= DMA_CCR1_EN; // Enable DMA channel 1
```
最后,需要启动ADC1的转换和DMA传输:
```
ADC1->SQR3 |= ( << ADC_SQR3_SQ1_Pos) | (1 << ADC_SQR3_SQ2_Pos); // Set ADC1 channel sequence to PA and PA1
ADC1->CR2 |= ADC_CR2_DMA; // Enable DMA mode for ADC1
ADC1->CR2 |= ADC_CR2_CONT; // Enable continuous conversion mode for ADC1
ADC1->CR2 |= ADC_CR2_ADON; // Start ADC1 conversion
while (1) {
// Wait for DMA transfer to complete
while (!(DMA1->ISR & DMA_ISR_TCIF1));
DMA1->IFCR |= DMA_IFCR_CTCIF1; // Clear DMA transfer complete flag
// Process ADC values in adc_values array
// ...
// Restart DMA transfer
DMA1_Channel1->CCR &= ~DMA_CCR1_EN; // Disable DMA channel 1
DMA1_Channel1->CNDTR = ADC_BUFFER_SIZE; // Set DMA transfer size to ADC_BUFFER_SIZE
DMA1_Channel1->CCR |= DMA_CCR1_EN; // Enable DMA channel 1
}
```
希望对你有帮助!
阅读全文