#include "stm32l031xx.h"
volatile uint16_t adc_value;
void tim2_init_1khz(void){
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
TIM2->CR1 = 0;
TIM2->PSC = 15;
TIM2->ARR = 999;
TIM2->CNT = 0;
TIM2->CR1 &= ~(7U << 4);
TIM2->CR1 |= (2U << 4);
TIM2->EGR = TIM_EGR_UG;
TIM2->SR &= ~TIM_SR_UIF;
/* Enable timer */
TIM2->CR1 |= TIM_CR1_CEN;
}
void ADC_Init(void)
{
/* 1. Enable GPIOA clock */
RCC->IOPENR |= RCC_IOPENR_GPIOAEN;
/* 2. Enable ADC clock */
RCC->APB2ENR |= RCC_APB2ENR_ADCEN;
/* 3. Configure PA0 as analog input */
GPIOA->MODER &= ~(3U << (2U * 0));
GPIOA->MODER |= (3U << (2U * 0));
/* Disable pull-up/pull-down */
GPIOA->PUPDR &= ~(3U << (2U * 0));
/* 4. Ensure ADC is disabled before calibration */
ADC1->CR &= ~ADC_CR_ADEN;
/* 5. Start ADC calibration */
ADC1->CR |= ADC_CR_ADCAL;
/* Wait for calibration to complete */
while (ADC1->CR & ADC_CR_ADCAL)
{
}
/* 6. Select ADC channel 0 */
ADC1->CHSELR = (1U << 0);
/*
* Configure ADC external trigger:
*
* EXTSEL = 010 -> TIM2_TRGO
* EXTEN = 01 -> Rising edge
* CONT = 0 -> Single conversion per trigger
*/
ADC1->CFGR1 &= ~(ADC_CFGR1_EXTSEL |
ADC_CFGR1_EXTEN |
ADC_CFGR1_CONT);
ADC1->CFGR1 |= ADC_CFGR1_EXTSEL_1 |
ADC_CFGR1_EXTEN_0;
/* 7. Configure sampling time */
ADC1->SMPR = 7U;
/* 8. Enable ADC */
ADC1->CR |= ADC_CR_ADEN;
/* Wait until ADC is ready */
while (!(ADC1->ISR & ADC_ISR_ADRDY))
{
}
/* Clear ADC ready flag */
ADC1->ISR |= ADC_ISR_ADRDY;
}
uint16_t ADC_Read(void)
{
/* Start conversion */
ADC1->CR |= ADC_CR_ADSTART;
/* Wait for conversion to complete */
while (!(ADC1->ISR & ADC_ISR_EOC))
{
}
/* Read converted result */
return (uint16_t)ADC1->DR;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
ADC_Init();
tim2_init_1khz();
Serial.println("ADC sampling at 1 kHz");
}
void loop() {
if (ADC1->ISR & ADC_ISR_EOC)
{
adc_value = ADC1->DR;
}
/*
* Display the most recent sample at 20 Hz.
* We do not print every 1 kHz conversion.
*/
static uint32_t last_print = 0;
if (millis() - last_print >= 50)
{
last_print = millis();
Serial.print("ADC: ");
Serial.println(adc_value);
}
}
Loading
st-nucleo-l031k6
st-nucleo-l031k6