#include #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 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 = (uint32_t) &(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<SMPR2 = (7<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; /* DEBUG */ TIM1->DIER = TIM_DIER_CC1IE; NVIC_EnableIRQ(TIM1_CC_IRQn); NVIC_SetPriority(TIM1_CC_IRQn, 130); /* END DEBUG */ TIM1->CR1 = TIM_CR1_CEN; TIM1->EGR = TIM_EGR_UG; } void TIM1_CC_IRQHandler(void) { TIM1->SR &= ~TIM_SR_CC1IF; static int foo=0; foo++; if (foo == 500) { foo = 0; GPIOA->ODR ^= 1<<6; } } void DMA2_Stream0_IRQHandler(void) { uint8_t isr = (DMA2->LISR >> DMA_LISR_FEIF0_Pos) & 0x3f; GPIOA->ODR ^= 1<<7; GPIOA->BSRR = 1<<10; if (isr & DMA_LISR_TCIF0) { /* Transfer complete */ /* Check we're done processing the old buffer */ if (adc_fft_buf_ready_idx != -1) { /* FIXME DEBUG */ GPIOA->BSRR = 1<<10<<16; /* clear all flags */ adc_dma->LIFCR = isr<CR & DMA_SxCR_CT); adc_fft_buf_ready_idx = !ct; } if (isr & DMA_LISR_DMEIF0) /* Direct mode error */ panic(); if (isr & DMA_LISR_TEIF0) /* Transfer error */ panic(); GPIOA->BSRR = 1<<10<<16; /* clear all flags */ adc_dma->LIFCR = isr<