Darren Ulrich
/
Nucleo_F411RE_ADC_HAL
STM32F411RE WORKING HAL ADC EXAMPLE
#include "mbed.h" #include "string" #include "cmsis.h" #include "pinmap.h" #include "PeripheralPins.h" Serial pc(USBTX, USBRX); uint32_t g_ADCValue; float g_ADC_Value_Volts; const float maxAdcBits = 4095.0f; // Using Float for clarity const float maxVolts = 3.3f; // Using Float for clarity const float voltsPerBit = (maxVolts / maxAdcBits); int main() { //Start of initializing analog input on pin PC_1 ADC_HandleTypeDef AdcHandle; GPIO_InitTypeDef gpioInit; //Start GPIO and ADC1 Clocks __GPIOC_CLK_ENABLE(); __ADC1_CLK_ENABLE(); //Define PC_1 which is Pin one of group C and connected to a 10K potentiometer. gpioInit.Pin = GPIO_PIN_1; gpioInit.Mode = GPIO_MODE_ANALOG; gpioInit.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOC, &gpioInit); // Configure ADC AdcHandle.Instance = ADC1; AdcHandle.Init.ClockPrescaler = ADC_CLOCKPRESCALER_PCLK_DIV2; AdcHandle.Init.Resolution = ADC_RESOLUTION12b; AdcHandle.Init.ScanConvMode = DISABLE; AdcHandle.Init.ContinuousConvMode = ENABLE; AdcHandle.Init.DiscontinuousConvMode = DISABLE; AdcHandle.Init.NbrOfDiscConversion = 0; AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; AdcHandle.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T1_CC1; AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT; AdcHandle.Init.NbrOfConversion = 1; AdcHandle.Init.DMAContinuousRequests = DISABLE; AdcHandle.Init.EOCSelection = DISABLE; if (HAL_ADC_Init(&AdcHandle) != HAL_OK) { pc.printf("Cannot initialize ADC\n"); while(1){ } } ADC_ChannelConfTypeDef sConfig = {0}; // Configure ADC channel sConfig.Rank = 1; sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES; sConfig.Offset = 0; sConfig.Channel = ADC_CHANNEL_11; if (HAL_ADC_ConfigChannel(&AdcHandle, &sConfig) != HAL_OK) { pc.printf("Cannot config channel\r\n"); while(1){ } } HAL_ADC_ConfigChannel(&AdcHandle, &sConfig); //Not sure why, but I have to do this twice? pc.printf("AnalogIn example\r\n"); HAL_ADC_Start(&AdcHandle); // Start conversion while(1) { g_ADCValue = 0; if (HAL_ADC_PollForConversion(&AdcHandle, 1000000) == HAL_OK) { g_ADCValue = HAL_ADC_GetValue(&AdcHandle); g_ADC_Value_Volts = g_ADCValue*voltsPerBit; pc.printf("Conversion ready \r\n"); printf("measure = %f V \r\n", g_ADC_Value_Volts); } else { pc.printf("Conversion not ready \r\n"); } wait(1.0); // 1 second } }