#include #include #include "adc.h" #include "sr_global.h" uint16_t adc_fft_buf[2][FMEAS_FFT_LEN]; volatile int adc_fft_buf_ready_idx = -1; static DMA_TypeDef *const adc_dma = DMA2; static DMA_Stream_TypeDef *const mem_stream = DMA2_Stream1; static DMA_Stream_TypeDef *const adc_stream = DMA2_Stream0; static const int dma_adc_channel = 0; static const int adc_channel = 10; /* Configure ADC1 to sample channel 0. Trigger from TIM1 CC0 every 1ms. Transfer readings into alternating buffers * throug DMA. Enable DMA interrupts. * * We have two full FFT buffers. We always transfer data from the ADC to the back half of the active one, while a * DMA memcpy'es the latter half of the inactive one to the front half of the active one. This means at the end of the * ADC's DMA transfer, in the now-inactive buffer that the ADC results were just written to we have last half-period's * data sitting in front of this half-period's data like so: [old_adc_data, new_adc_data] * * This means we can immediately start running an FFT on ADC DMA transfer complete interrupt. */ void adc_init() { RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN | RCC_AHB1ENR_GPIOCEN; RCC->APB2ENR |= RCC_APB2ENR_ADC1EN | RCC_APB2ENR_TIM1EN; /* PC0 -> ADC1.ch10 */ GPIOC->MODER &= ~GPIO_MODER_MODER0_Msk; GPIOC->MODER |= (3<LIFCR |= 0x3f; adc_stream->CR = 0; /* disable */ while (adc_stream->CR & DMA_SxCR_EN) ; /* wait for stream to become available */ adc_stream->NDTR = FMEAS_FFT_LEN/2; adc_stream->PAR = &(ADC1->DR); adc_stream->M0AR = (uint32_t) (adc_fft_buf[0] + FMEAS_FFT_LEN/2); adc_stream->M1AR = (uint32_t) (adc_fft_buf[1] + FMEAS_FFT_LEN/2); adc_stream->CR = (dma_adc_channel<CR |= DMA_SxCR_EN; NVIC_EnableIRQ(DMA2_Stream0_IRQn); NVIC_SetPriority(DMA2_Stream0_IRQn, 128); ADC1->CR1 = (0<CR2 = (1<SQR3 = (adc_channel<SQR1 = (0<CR2 = (2<CCMR1 = (6<CCER = TIM_CCER_CC1E; TIM1->PSC = 84-1; /* 1us ticks @ f_APB2=84MHz */ TIM1->ARR = 1000-1; /* 1ms period */ TIM1->CCR1 = 500-1; TIM1->BDTR = TIM_BDTR_MOE; TIM1->CR1 = TIM_CR1_CEN; TIM1->EGR = TIM_EGR_UG; } void DMA2_Stream0_IRQHandler(void) { uint8_t isr = (DMA2->LISR >> DMA_LISR_FEIF0_Pos) & 0x3f; if (isr & DMA_LISR_TCIF0) { /* Transfer complete */ /* Check we're done processing the old buffer */ if (adc_fft_buf_ready_idx != -1) panic(); /* Kickoff memory DMA into new buffer */ if (mem_stream->CR & DMA_SxCR_EN) panic(); /* We should be long done by now. */ adc_dma->LIFCR = 0x3d<NDTR = FMEAS_FFT_LEN/2; int ct = !!(adc_stream->CR & DMA_SxCR_CT); /* back half of old buffer (that was just written) */ mem_stream->PAR = (uint32_t)(adc_fft_buf[!ct] + FMEAS_FFT_LEN/2); /* front half of current buffer (whose back half is being written now) */ mem_stream->M0AR = (uint32_t) (adc_fft_buf[ct] + 0); mem_stream->CR = (1<CR |= DMA_SxCR_EN; /* Kickoff FFT */ adc_fft_buf_ready_idx = !ct; } if (isr & DMA_LISR_DMEIF0) /* Direct mode error */ panic(); if (isr & DMA_LISR_TEIF0) /* Transfer error */ panic(); /* clear all flags */ adc_dma->LIFCR = isr<