T05 - ADC

Write a program for Nucleo STM32F401RE to measure voltage using ADC.

Instructions:

  1. See template, how to use ADC.
  2. Modify template to send measured data to PC via USART.
  3. Modify template to show measured value on display.

Lecture

Template

Project: adc.zip

#define BIT8
#define LOSAMP
 
void initGPIO()
{
    RCC->AHB1ENR |= 0x01;
 
    /* configure PA0 as ADC_IN0 */
    GPIOA->MODER   |=  0x03;     /* analog mode */
    GPIOA->OSPEEDR |=  0x03;     /* high speed */
}
 
void initADC1()
{
    // initialize the HSI clock
    setbit(RCC->CR, 0);         // enable HSI
    while (!getbit(RCC->CR, 1));// wait until HSI stable
 
    // initialize the ADC
    setbit(RCC->APB2ENR, 8);     // enable ADC1 peripheral clock
    ADC->CCR = 0;                 // disable temperature sensor, ADC prescaler = HSI/2
    clearbit(ADC1->SQR3, 0);    // 1st conversion in regular sequence will be from channel0
    clearbit(ADC1->SQR3, 1);    // reset state - all conversions from channel0 (PA_0)
    clearbit(ADC1->SQR3, 2);    // this is just an example
    clearbit(ADC1->SQR3, 3);
    clearbit(ADC1->SQR3, 4);
#ifdef BIT12
    clearbit(ADC1->CR1, 24);     // 12-bit resolution (Tconv = 15 ADCCLK cycles)
    clearbit(ADC1->CR1, 25);    // reset state
#endif
#ifdef BIT10
    setbit(ADC1->CR1, 24);        // 10-bit resolution (Tconv = 13 ADCCLK cycles)
#endif
#ifdef BIT8
    setbit(ADC1->CR1, 25);         // 8-bit resolution (Tconv =  11 ADCCLK cycles)
#endif
    clearbit(ADC1->CR2, 11);     // right alignment, reset state
#ifdef LOSAMP
    clearbit(ADC1->SMPR2, 0);    // channel0 sample rate: 3 cycles
    clearbit(ADC1->SMPR2, 1);    // reset state
    clearbit(ADC1->SMPR2, 2);
#endif
#ifdef HISAMP
    setbit(ADC1->SMPR2, 0);     // channel0 sample rate: 480 cycles
    setbit(ADC1->SMPR2, 1);
    setbit(ADC1->SMPR2, 2);
#endif
    setbit(ADC1->CR2, 0); // enable the ADC
}
 
void delay(int x)
{
    volatile int i;
    for (i = 0; i < 1000*x; i++);
}
 
int main()
{
    int i = 0;
 
    initGPIO();
    initADC1();
 
    while(1)
    {
        // single conversion mode, sec. 11.3.4 in RM (p. 841)
        setbit(ADC1->CR2, 30);             // software ADC start
        while (!getbit(ADC1->SR, 1));     // wait until conversion end
        i = ADC1->DR;
        delay(10);
    }
}

courses/be2m37mam/tasks/task05.txt · Last modified: 2020/11/26 12:56 by viteks