Darren Ulrich
/
Nucleo_F411RE_ADC_HAL
STM32F411RE WORKING HAL ADC EXAMPLE
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 #include "string" 00003 00004 #include "cmsis.h" 00005 #include "pinmap.h" 00006 #include "PeripheralPins.h" 00007 00008 00009 Serial pc(USBTX, USBRX); 00010 00011 uint32_t g_ADCValue; 00012 float g_ADC_Value_Volts; 00013 const float maxAdcBits = 4095.0f; // Using Float for clarity 00014 const float maxVolts = 3.3f; // Using Float for clarity 00015 const float voltsPerBit = (maxVolts / maxAdcBits); 00016 00017 int main() 00018 { 00019 //Start of initializing analog input on pin PC_1 00020 ADC_HandleTypeDef AdcHandle; 00021 GPIO_InitTypeDef gpioInit; 00022 //Start GPIO and ADC1 Clocks 00023 __GPIOC_CLK_ENABLE(); 00024 __ADC1_CLK_ENABLE(); 00025 //Define PC_1 which is Pin one of group C and connected to a 10K potentiometer. 00026 gpioInit.Pin = GPIO_PIN_1; 00027 gpioInit.Mode = GPIO_MODE_ANALOG; 00028 gpioInit.Pull = GPIO_NOPULL; 00029 HAL_GPIO_Init(GPIOC, &gpioInit); 00030 00031 // Configure ADC 00032 AdcHandle.Instance = ADC1; 00033 AdcHandle.Init.ClockPrescaler = ADC_CLOCKPRESCALER_PCLK_DIV2; 00034 AdcHandle.Init.Resolution = ADC_RESOLUTION12b; 00035 AdcHandle.Init.ScanConvMode = DISABLE; 00036 AdcHandle.Init.ContinuousConvMode = ENABLE; 00037 AdcHandle.Init.DiscontinuousConvMode = DISABLE; 00038 AdcHandle.Init.NbrOfDiscConversion = 0; 00039 AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; 00040 AdcHandle.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T1_CC1; 00041 AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT; 00042 AdcHandle.Init.NbrOfConversion = 1; 00043 AdcHandle.Init.DMAContinuousRequests = DISABLE; 00044 AdcHandle.Init.EOCSelection = DISABLE; 00045 00046 if (HAL_ADC_Init(&AdcHandle) != HAL_OK) { 00047 pc.printf("Cannot initialize ADC\n"); 00048 while(1){ 00049 } 00050 } 00051 ADC_ChannelConfTypeDef sConfig = {0}; 00052 // Configure ADC channel 00053 sConfig.Rank = 1; 00054 sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES; 00055 sConfig.Offset = 0; 00056 sConfig.Channel = ADC_CHANNEL_11; 00057 00058 if (HAL_ADC_ConfigChannel(&AdcHandle, &sConfig) != HAL_OK) { 00059 pc.printf("Cannot config channel\r\n"); 00060 while(1){ 00061 } 00062 } 00063 HAL_ADC_ConfigChannel(&AdcHandle, &sConfig); //Not sure why, but I have to do this twice? 00064 pc.printf("AnalogIn example\r\n"); 00065 HAL_ADC_Start(&AdcHandle); // Start conversion 00066 while(1) { 00067 g_ADCValue = 0; 00068 if (HAL_ADC_PollForConversion(&AdcHandle, 1000000) == HAL_OK) { 00069 g_ADCValue = HAL_ADC_GetValue(&AdcHandle); 00070 g_ADC_Value_Volts = g_ADCValue*voltsPerBit; 00071 pc.printf("Conversion ready \r\n"); 00072 printf("measure = %f V \r\n", g_ADC_Value_Volts); 00073 } else { 00074 pc.printf("Conversion not ready \r\n"); 00075 } 00076 wait(1.0); // 1 second 00077 } 00078 } 00079 00080 00081 00082 00083 00084 00085
Generated on Sat Jul 23 2022 10:41:07 by 1.7.2