Exemple #1
1
STATIC void adcx_init_periph(ADC_HandleTypeDef *adch, uint32_t resolution) {
    adcx_clock_enable();

    adch->Instance                   = ADCx;
    adch->Init.Resolution            = resolution;
    adch->Init.ContinuousConvMode    = DISABLE;
    adch->Init.DiscontinuousConvMode = DISABLE;
    #if !defined(STM32F0)
    adch->Init.NbrOfDiscConversion   = 0;
    adch->Init.NbrOfConversion       = 1;
    #endif
    adch->Init.EOCSelection          = ADC_EOC_SINGLE_CONV;
    adch->Init.ExternalTrigConv      = ADC_SOFTWARE_START;
    adch->Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
    #if defined(STM32F0) || defined(STM32F4) || defined(STM32F7)
    adch->Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV2;
    adch->Init.ScanConvMode          = DISABLE;
    adch->Init.DataAlign             = ADC_DATAALIGN_RIGHT;
    adch->Init.DMAContinuousRequests = DISABLE;
    #elif defined(STM32H7)
    adch->Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV4;
    adch->Init.BoostMode             = ENABLE;
    adch->Init.ScanConvMode          = DISABLE;
    adch->Init.LowPowerAutoWait      = DISABLE;
    adch->Init.Overrun               = ADC_OVR_DATA_OVERWRITTEN;
    adch->Init.OversamplingMode      = DISABLE;
    adch->Init.LeftBitShift          = ADC_LEFTBITSHIFT_NONE;
    adch->Init.ConversionDataManagement = ADC_CONVERSIONDATA_DR;
    #elif defined(STM32L4)
    adch->Init.ClockPrescaler        = ADC_CLOCK_ASYNC_DIV1;
    adch->Init.ScanConvMode          = ADC_SCAN_DISABLE;
    adch->Init.LowPowerAutoWait      = DISABLE;
    adch->Init.Overrun               = ADC_OVR_DATA_PRESERVED;
    adch->Init.OversamplingMode      = DISABLE;
    adch->Init.DataAlign             = ADC_DATAALIGN_RIGHT;
    adch->Init.DMAContinuousRequests = DISABLE;
    #else
    #error Unsupported processor
    #endif

    #if defined(STM32F0)
    adch->Init.SamplingTimeCommon = ADC_SAMPLETIME_71CYCLES_5;
    #endif

    HAL_ADC_Init(adch);

    #if defined(STM32H7)
    HAL_ADCEx_Calibration_Start(adch, ADC_CALIB_OFFSET, ADC_SINGLE_ENDED);
    #endif
    #if defined(STM32L4)
    HAL_ADCEx_Calibration_Start(adch, ADC_SINGLE_ENDED);
    #endif
}
int main(void) {
  char msg[20];
  uint16_t rawValues[3];
  float temp;

  HAL_Init();
  Nucleo_BSP_Init();

  /* Initialize all configured peripherals */
  MX_TIM1_Init();
  MX_ADC1_Init();

  HAL_ADCEx_Calibration_Start(&hadc1);

  HAL_TIM_Base_Start(&htim1);
  HAL_ADC_Start_DMA(&hadc1, (uint32_t*)rawValues, 1);

  while(1) {
    while(!convCompleted);

     for(uint8_t i = 0; i < 1; i++) {
      temp = ((float)rawValues[i]) / 4095 * 3300;
      temp = ((temp - 1430.0) / 4.3) + 25;

      sprintf(msg, "rawValue %d: %hu\r\n", i, rawValues[i]);
      HAL_UART_Transmit(&huart2, (uint8_t*) msg, strlen(msg), HAL_MAX_DELAY);

      sprintf(msg, "Temperature %d: %f\r\n",i,  temp);
      HAL_UART_Transmit(&huart2, (uint8_t*) msg, strlen(msg), HAL_MAX_DELAY);
    }
    convCompleted = 0;
  }
}
Exemple #3
0
uint16_t ADC_Get_Pulse(void)
{
	uint16_t adc_value;
	uint16_t adc_valuetest=0;
 ADC_Config_CH2();
	
	
	  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }
	
	#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Configure the TIM peripheral */
  TIM_Config();
#endif /* ADC_TRIGGER_FROM_TIMER */
	
	 /*## Enable peripherals ####################################################*/
#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Timer enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
#endif /* ADC_TRIGGER_FROM_TIMER */
  /* Note: This example, on some other STM32 boards, is performing            */
  /*       DAC signal generation here.                                        */
  /*       On STM32F103RB-Nucleo, the device has no DAC available,            */
  /*       therefore analog signal must be supplied externally.               */

  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
//   if (HAL_ADC_Start_DMA(&AdcHandle,
//                         (uint32_t *)aADCxConvertedValues,
//                         ADCCONVERTEDVALUES_BUFFER_SIZE
//                        ) != HAL_OK)
//   {
//     /* Start Error */
//     Error_Handler();
//   }
   if (HAL_ADC_Start(&AdcHandle) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
	
	if (HAL_ADC_PollForConversion(&AdcHandle,10) != HAL_OK)
		  {
    /* Start Error */
    Error_Handler();
			}
	
	adc_value= HAL_ADC_GetValue(&AdcHandle);

	return(adc_value);

}
/**
  * @brief  Configures joystick available on adafruit 1.8" TFT shield 
  *         managed through ADC to detect motion.
  * @param  None
  * @retval Joystickstatus (0=> success, 1=> fail) 
  */
uint8_t BSP_JOY_Init(void)
{
  uint8_t status = 1;
   
  ADCx_Init();
  
  /* Start ADC calibration */
  HAL_ADCEx_Calibration_Start(&hnucleo_Adc, ADC_SINGLE_ENDED);

#if defined(STM32F302x8) || defined(STM32F334x8)
  /* Select Channel 11 to be converted */
  sConfig.Channel      = ADC_CHANNEL_11;
#elif defined(STM32F303xE)
  /* Select Channel 12 to be converted */
  sConfig.Channel      = ADC_CHANNEL_12;
#endif
  sConfig.Rank         = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_19CYCLES_5;
  sConfig.SingleDiff   = ADC_SINGLE_ENDED;
  sConfig.Offset       = ADC_OFFSET_NONE;
  
  status = HAL_ADC_ConfigChannel(&hnucleo_Adc, &sConfig);
  
  /* Return Joystick initialization status */
  return status;
}
Exemple #5
0
/* ADC init function */
void MX_ADC_Init(void)
{

  //ADC_ChannelConfTypeDef sConfig;

    /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) 
    */
  hadc.Instance = ADC1;
  hadc.Init.OversamplingMode = DISABLE;
  hadc.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
  hadc.Init.Resolution = ADC_RESOLUTION12b;
  hadc.Init.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
  hadc.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD;
  hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc.Init.ContinuousConvMode = ENABLE;
  hadc.Init.DiscontinuousConvMode = DISABLE;
  hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIG_EDGE_NONE;
  hadc.Init.DMAContinuousRequests = DISABLE;
  hadc.Init.EOCSelection = EOC_SINGLE_CONV;
  hadc.Init.Overrun = OVR_DATA_PRESERVED;
  hadc.Init.LowPowerAutoWait = DISABLE;
  hadc.Init.LowPowerFrequencyMode = DISABLE;
  hadc.Init.LowPowerAutoPowerOff = DISABLE;
  HAL_ADC_Init(&hadc);

    /**Configure for the selected ADC regular channel to be converted. 
    */
  //sConfig.Channel = ADC_CHANNEL_11;
  //sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;
  //HAL_ADC_ConfigChannel(&hadc, &sConfig);
  HAL_ADCEx_Calibration_Start(&hadc, ADC_SINGLE_ENDED);

}
Exemple #6
0
void analogin_init(analogin_t *obj, PinName pin)
{
    uint32_t function = (uint32_t)NC;

    // ADC Internal Channels "pins"  (Temperature, Vref, Vbat, ...)
    //   are described in PinNames.h and PeripheralPins.c
    //   Pin value must be between 0xF0 and 0xFF
    if ((pin < 0xF0) || (pin >= 0x100)) {
        // Normal channels
        // Get the peripheral name from the pin and assign it to the object
        obj->handle.Instance = (ADC_TypeDef *)pinmap_peripheral(pin, PinMap_ADC);
        // Get the functions (adc channel) from the pin and assign it to the object
        function = pinmap_function(pin, PinMap_ADC);
        // Configure GPIO
        pinmap_pinout(pin, PinMap_ADC);
    } else {
        // Internal channels
        obj->handle.Instance = (ADC_TypeDef *)pinmap_peripheral(pin, PinMap_ADC_Internal);
        function = pinmap_function(pin, PinMap_ADC_Internal);
        // No GPIO configuration for internal channels
    }
    MBED_ASSERT(obj->handle.Instance != (ADC_TypeDef *)NC);
    MBED_ASSERT(function != (uint32_t)NC);

    obj->channel = STM_PIN_CHANNEL(function);

    // Save pin number for the read function
    obj->pin = pin;

    // Configure ADC object structures
    obj->handle.State = HAL_ADC_STATE_RESET;
    obj->handle.Init.OversamplingMode      = DISABLE;
    obj->handle.Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV1;
    obj->handle.Init.Resolution            = ADC_RESOLUTION_12B;
    obj->handle.Init.SamplingTime          = ADC_SAMPLETIME_160CYCLES_5;
    obj->handle.Init.ScanConvMode          = ADC_SCAN_DIRECTION_FORWARD;
    obj->handle.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
    obj->handle.Init.ContinuousConvMode    = DISABLE;
    obj->handle.Init.DiscontinuousConvMode = DISABLE;
    obj->handle.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIG_EDGE_NONE;
    obj->handle.Init.ExternalTrigConv      = ADC_EXTERNALTRIG0_T6_TRGO; // Not used here
    obj->handle.Init.DMAContinuousRequests = DISABLE;
    obj->handle.Init.EOCSelection          = EOC_SINGLE_CONV;
    obj->handle.Init.Overrun               = OVR_DATA_OVERWRITTEN;
    obj->handle.Init.LowPowerAutoWait      = ENABLE;
    obj->handle.Init.LowPowerFrequencyMode = DISABLE; // To be enabled only if ADC clock < 2.8 MHz
    obj->handle.Init.LowPowerAutoPowerOff  = DISABLE;

    __HAL_RCC_ADC1_CLK_ENABLE();

    if (HAL_ADC_Init(&obj->handle) != HAL_OK) {
        error("Cannot initialize ADC");
    }

    if (!HAL_ADCEx_Calibration_GetValue(&obj->handle, ADC_SINGLE_ENDED)) {
        HAL_ADCEx_Calibration_Start(&obj->handle, ADC_SINGLE_ENDED);
    }

    __HAL_ADC_ENABLE(&obj->handle);
}
Exemple #7
0
/**
  * @brief  Configure ADC1 for being used with HRTIM
  * @param  None
  * @retval None
  */
static void ADC_Config(void)
{
    ADC_MultiModeTypeDef MultiModeConfig;
    ADC_InjectionConfTypeDef InjectionConfig;

    AdcHandle.Instance = ADC1;

    /* ADC2 is working independently */
    MultiModeConfig.DMAAccessMode = ADC_DMAACCESSMODE_DISABLED;
    MultiModeConfig.Mode = ADC_MODE_INDEPENDENT;
    MultiModeConfig.TwoSamplingDelay = ADC_TWOSAMPLINGDELAY_1CYCLE;
    HAL_ADCEx_MultiModeConfigChannel(&AdcHandle, &MultiModeConfig);

    /* ADC2 global initialization */
    /* 12-bit right-aligned format, discontinuous scan mode, running from PLL */
    AdcHandle.Init.ClockPrescaler = ADC_CLOCK_ASYNC;
    AdcHandle.Init.Resolution = ADC_RESOLUTION12b;
    AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT;
    AdcHandle.Init.ScanConvMode = ENABLE;
    AdcHandle.Init.EOCSelection = EOC_SINGLE_CONV;
    AdcHandle.Init.LowPowerAutoWait = DISABLE;
    AdcHandle.Init.ContinuousConvMode = DISABLE;
    AdcHandle.Init.NbrOfConversion = 1;
    AdcHandle.Init.DiscontinuousConvMode = DISABLE;
    AdcHandle.Init.NbrOfDiscConversion = 1;
    AdcHandle.Init.ExternalTrigConv = ADC_SOFTWARE_START;
    AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
    AdcHandle.Init.DMAContinuousRequests = DISABLE;
    AdcHandle.Init.Overrun = OVR_DATA_OVERWRITTEN;
    HAL_ADC_Init(&AdcHandle);

    /* Discontinuous injected mode: 1st injected conversion for Vin on Ch2 */
    InjectionConfig.InjectedChannel = ADC_CHANNEL_2;
    InjectionConfig.InjectedRank = ADC_INJECTED_RANK_1;
    InjectionConfig.InjectedSamplingTime = ADC_SAMPLETIME_7CYCLES_5;
    InjectionConfig.InjectedSingleDiff = ADC_SINGLE_ENDED;
    InjectionConfig.InjectedOffsetNumber = ADC_OFFSET_NONE;
    InjectionConfig.InjectedOffset = 0;
    InjectionConfig.InjectedNbrOfConversion = 2;
    InjectionConfig.InjectedDiscontinuousConvMode = DISABLE;
    InjectionConfig.AutoInjectedConv = DISABLE;
    InjectionConfig.QueueInjectedContext = DISABLE;
    InjectionConfig.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_HRTIM_TRG2;
    InjectionConfig.ExternalTrigInjecConvEdge = ADC_EXTERNALTRIGINJECCONV_EDGE_RISING;
    HAL_ADCEx_InjectedConfigChannel(&AdcHandle, &InjectionConfig);

    /* Configure the 2nd injected conversion for Vout on Ch4 */
    InjectionConfig.InjectedChannel = ADC_CHANNEL_4;
    InjectionConfig.InjectedRank = ADC_INJECTED_RANK_2;
    InjectionConfig.InjectedSamplingTime = ADC_SAMPLETIME_19CYCLES_5;
    HAL_ADCEx_InjectedConfigChannel(&AdcHandle, &InjectionConfig);

    /* Run the ADC calibration in single-ended mode */
    HAL_ADCEx_Calibration_Start(&AdcHandle, ADC_SINGLE_ENDED);

    /* Start ADC2 Injected Conversions */
    HAL_ADCEx_InjectedStart(&AdcHandle);

}
Exemple #8
0
/*====================================================================================================*/
void ADC_Config( void )
{
  ADC_ChannelConfTypeDef ADC_ChannelConfStruct;
  HAL_StatusTypeDef state;

  /* Config ADC *****************************************************************/
  ADC_HandleStruct.Instance = ADCx;
  ADC_HandleStruct.Init.ClockPrescaler        = ADC_CLOCK_ASYNC_DIV1;
  ADC_HandleStruct.Init.Resolution            = ADC_RESOLUTION_12B;
  ADC_HandleStruct.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
  ADC_HandleStruct.Init.ScanConvMode          = ENABLE;
  ADC_HandleStruct.Init.EOCSelection          = ADC_EOC_SINGLE_CONV;
  ADC_HandleStruct.Init.LowPowerAutoWait      = DISABLE;
  ADC_HandleStruct.Init.ContinuousConvMode    = ENABLE;
  ADC_HandleStruct.Init.NbrOfConversion       = ADC_BUF_CHENNAL;
  ADC_HandleStruct.Init.DiscontinuousConvMode = ENABLE;
  ADC_HandleStruct.Init.NbrOfDiscConversion   = 1;
  ADC_HandleStruct.Init.ExternalTrigConv      = ADC_SOFTWARE_START;
  ADC_HandleStruct.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
  ADC_HandleStruct.Init.DMAContinuousRequests = ENABLE;
  ADC_HandleStruct.Init.Overrun               = ADC_OVR_DATA_OVERWRITTEN;
  HAL_ADC_DeInit(&ADC_HandleStruct);
  state = HAL_ADC_Init(&ADC_HandleStruct);
  if(state != HAL_OK)
    while(1) { ; }

  /* Config ADC Chennal **********************************************************/
  ADC_ChannelConfStruct.SamplingTime = ADC_SAMPLETIME_601CYCLES_5;
  ADC_ChannelConfStruct.SingleDiff   = ADC_SINGLE_ENDED;
  ADC_ChannelConfStruct.OffsetNumber = ADC_OFFSET_NONE;
  ADC_ChannelConfStruct.Offset       = 0;

  // ADC1_CH1 Channel
  ADC_ChannelConfStruct.Channel = ADCx_CHANNEL;
  ADC_ChannelConfStruct.Rank    = ADC_REGULAR_RANK_1;
  state = HAL_ADC_ConfigChannel(&ADC_HandleStruct, &ADC_ChannelConfStruct);
  if(state != HAL_OK)
    while(1) { ; }

  // ADC1_CH2 Channel
//  ADC_ChannelConfStruct.Channel = ADCx_2_CHANNEL;
//  ADC_ChannelConfStruct.Rank    = ADC_REGULAR_RANK_2;
//  state = HAL_ADC_ConfigChannel(&ADC_HandleStruct, &ADC_ChannelConfStruct);
//  if(state != HAL_OK)
//    while(1) { ; }

  /* Setup ADC *******************************************************************/
  state = HAL_ADCEx_Calibration_Start(&ADC_HandleStruct, ADC_SINGLE_ENDED);
  if(state != HAL_OK)
    while(1) { ; }
  state = HAL_ADC_Start_DMA(&ADC_HandleStruct, (uint32_t *)ADC_DMA_ConvBuf, ADC_BUF_SIZE * ADC_BUF_CHENNAL);
  if(state != HAL_OK)
    while(1) { ; }
}
/**
  * @brief  Configures joystick available on adafruit 1.8" TFT shield 
  *         managed through ADC to detect motion.
  * @param  None
  * @retval Joystickstatus (0=> success, 1=> fail) 
  */
uint8_t BSP_JOY_Init(void)
{
  uint8_t status = 1;
   
  ADCx_Init();
   
  /* Start ADC calibration */
  HAL_ADCEx_Calibration_Start(&hnucleo_Adc, ADC_SINGLE_ENDED);
  
  /* Select Channel 0 to be converted */
  sConfig.Channel = ADC_CHANNEL_8;    
  status = HAL_ADC_ConfigChannel(&hnucleo_Adc, &sConfig);
  
  /* Return Joystick initialization status */
  return status;
}
Exemple #10
0
uint16_t temperature(){
		float									temp,Vdd_voltage,temp30,sense,x=0.8058608;
		int32_t                			f**k,vrefint_data; 												//VREFINT measured value
		int16_t											vrefint_cal_temp,vrefint_cal_int; 				//VREFINT calibration value
		ADC_ChannelConfTypeDef        sConfig;

		vrefint_cal_temp= *((int32_t*)0x1FFFF7B8);						
		vrefint_cal_int= *((int32_t*)0x1FFFF7BA);	
		ADC->CCR |= ADC_CCR_TSEN;
		
		HAL_Delay(50);
	//MX_ADC_Init();
	//HAL_ADC_Init(&hadc);
		HAL_ADCEx_Calibration_Start(&hadc);
	
		sConfig.Channel      = ADC_CHANNEL_VREFINT;
		sConfig.Rank         = ADC_RANK_CHANNEL_NUMBER;
		sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5 ;		
		hadc.Instance->CHSELR = (uint32_t)(ADC_CHSELR_CHSEL17);
		HAL_ADC_ConfigChannel(&hadc,&sConfig);
		
		HAL_ADC_Start(&hadc);
		HAL_ADC_PollForConversion(&hadc,1000);
		vrefint_data = (int32_t)HAL_ADC_GetValue(&hadc);								//vint beolvasott digitális érték
		HAL_ADC_Stop(&hadc);

		sConfig.Channel      =  ADC_CHANNEL_TEMPSENSOR;
		hadc.Instance->CHSELR = (uint32_t)(ADC_CHSELR_CHSEL16);		
		HAL_ADC_ConfigChannel(&hadc,&sConfig);	
		
		HAL_ADC_Start(&hadc);
		HAL_ADC_PollForConversion(&hadc,1000);
		f**k = (int32_t)HAL_ADC_GetValue(&hadc);										//temerature sensor
		HAL_ADC_Stop(&hadc);

		sense=(float)((float)vrefint_cal_int*(float)f**k);
		sense=(float)(sense/(float)vrefint_data);
		sense=(float)(sense*x);
		temp30=(3300*vrefint_cal_temp)/4095;
		temp=temp30-sense+30;
		PutString("Temperature:");
		PutNumber((uint32_t)temp);
		PutString("\n");

	//	HAL_ADC_DeInit(&hadc);
		return (uint16_t)temp;
}
Exemple #11
0
	uint16_t voltage_read(uint32_t channel, float voltage_div ){
		//TIM_CHANNEL_2 -> Battery voltage, div=2.0
		
		//ADC_voltage = (Vcal*vrefint_cal* ADC_data) / (vrefint_data*FULL_SCALE)
		
		float												voltage,x=0.80586;												//x=3300/4095
		uint32_t                			aResult;						//a mért csdatorna értéke
		uint16_t											vrefint_cal; 				//VREFINT calibration value,gyári kalibrációs érték(3,3V on)  vrefint
		uint32_t 											vrefint_data; 			//VREFINT measured value, tényleges vrefint
		ADC->CCR |= ADC_CCR_VREFEN;
		vrefint_cal= *((uint16_t*)VREFINT_CAL_ADDR);
		ADC_ChannelConfTypeDef        sConfig;

		//MX_ADC_Init();
		//HAL_ADC_Init(&hadc);

		sConfig.Channel      = ADC_CHANNEL_VREFINT;
		sConfig.Rank         = ADC_RANK_CHANNEL_NUMBER;
		sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;		
		hadc.Instance->CHSELR = (uint32_t)(ADC_CHSELR_CHSEL17);	
		HAL_ADC_ConfigChannel(&hadc,&sConfig);
	
		HAL_ADCEx_Calibration_Start(&hadc);
		
		HAL_ADC_Start(&hadc);
		HAL_ADC_PollForConversion(&hadc,1000);
		vrefint_data = HAL_ADC_GetValue(&hadc);								//vrefint beolvasott digitális érték
		HAL_ADC_Stop(&hadc);

		hadc.Instance->CHSELR = (uint32_t)(ADC_CHSELR_CHSEL2);	
		sConfig.Channel      = channel;								
		HAL_ADC_ConfigChannel(&hadc,&sConfig);		
		
		HAL_ADC_Start(&hadc);	
		HAL_ADC_PollForConversion(&hadc,100);
		aResult = HAL_ADC_GetValue(&hadc);										//aksifesz beolvasás
		HAL_ADC_Stop(&hadc);
		
		voltage = (((float)vrefint_cal/(float)vrefint_data))* (float)aResult*x;		//feszültség kiszámolása mV-ban
		voltage *=voltage_div;

		PutString("voltage=");
		PutNumber((uint32_t)voltage);	
		PutString("mV\n");
		return (uint16_t)voltage;
	}
Exemple #12
0
uint16_t battery_voltage_read(){												//PA2 lábon, chanel_2
		float												voltage,x=0.80586;
		uint32_t                			aResult;
		uint16_t											vrefint_cal; 				//VREFINT calibration value
		uint32_t 											vrefint_data; 			//VREFINT measured value
		ADC->CCR |= ADC_CCR_VREFEN;
		vrefint_cal= *((uint16_t*)VREFINT_CAL_ADDR);
		ADC_ChannelConfTypeDef        sConfig;

		//MX_ADC_Init();
		//HAL_ADC_Init(&hadc);

		sConfig.Channel      = ADC_CHANNEL_VREFINT;
		sConfig.Rank         = ADC_RANK_CHANNEL_NUMBER;
		sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;		
		hadc.Instance->CHSELR = (uint32_t)(ADC_CHSELR_CHSEL17);	
		HAL_ADC_ConfigChannel(&hadc,&sConfig);
	
		HAL_ADCEx_Calibration_Start(&hadc);
		
		HAL_ADC_Start(&hadc);
		HAL_ADC_PollForConversion(&hadc,1000);
		vrefint_data = HAL_ADC_GetValue(&hadc);								//vrefint beolvasott digitális érték
		HAL_ADC_Stop(&hadc);

		hadc.Instance->CHSELR = (uint32_t)(ADC_CHSELR_CHSEL2);	
		sConfig.Channel      = ADC_CHANNEL_2;									//aksifesz bemenet 
		HAL_ADC_ConfigChannel(&hadc,&sConfig);		
		
		HAL_ADC_Start(&hadc);	
		HAL_ADC_PollForConversion(&hadc,100);
		aResult = HAL_ADC_GetValue(&hadc);										//aksifesz beolvasás
		HAL_ADC_Stop(&hadc);
		
		voltage = (((float)vrefint_cal/(float)vrefint_data))* (float)aResult*x;		//feszültség kiszámolása mV-ban
		voltage *=2;

		PutString("battery voltage=");
		PutNumber((uint32_t)voltage);	
		PutString("mV");
		PutString("\n");

	//	HAL_ADC_DeInit(&hadc);
		return (uint32_t)voltage;
	}
Exemple #13
0
int drv_adc_init()
{
  hADC1.Instance                   = ADC1;
  hADC1.Init.ScanConvMode          = DISABLE;
  hADC1.Init.ContinuousConvMode    = DISABLE;
  hADC1.Init.DiscontinuousConvMode = DISABLE;
  hADC1.Init.NbrOfDiscConversion   = 0;
  hADC1.Init.ExternalTrigConv      = ADC_SOFTWARE_START;
  hADC1.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
  hADC1.Init.NbrOfConversion       = 1;

  if (HAL_ADC_Init(&hADC1) != HAL_OK)
  {
    return -1;
  }

  HAL_ADCEx_Calibration_Start(&hADC1);

  return 0;
}
Exemple #14
0
/**
  * @brief  Initializes ADC HAL.
  * @retval None
  */
static HAL_StatusTypeDef ADCx_Init(void)
{
  /* Set ADC instance */
  hnucleo_Adc.Instance                   = NUCLEO_ADCx;
  
  if(HAL_ADC_GetState(&hnucleo_Adc) == HAL_ADC_STATE_RESET)
  {
    /* ADC Config */
    hnucleo_Adc.Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV4;      /* ADC clock of STM32F0 must not exceed 14MHz */
    hnucleo_Adc.Init.Resolution            = ADC_RESOLUTION_12B;
    hnucleo_Adc.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
    hnucleo_Adc.Init.ScanConvMode          = ADC_SCAN_DIRECTION_FORWARD;    /* Sequencer will convert the number of channels configured below, successively from the lowest to the highest channel number */
    hnucleo_Adc.Init.EOCSelection          = ADC_EOC_SINGLE_CONV;
    hnucleo_Adc.Init.LowPowerAutoWait      = DISABLE;
    hnucleo_Adc.Init.LowPowerAutoPowerOff  = DISABLE;
    hnucleo_Adc.Init.ContinuousConvMode    = DISABLE;                       /* Continuous mode disabled to have only 1 conversion at each conversion trig */
    hnucleo_Adc.Init.DiscontinuousConvMode = DISABLE;                       /* Parameter discarded because sequencer is disabled */
    hnucleo_Adc.Init.ExternalTrigConv      = ADC_SOFTWARE_START;            /* Software start to trig the 1st conversion manually, without external event */
    hnucleo_Adc.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE; /* Parameter discarded because trig by software start */
    hnucleo_Adc.Init.DMAContinuousRequests = DISABLE;
    hnucleo_Adc.Init.Overrun               = ADC_OVR_DATA_OVERWRITTEN;
    hnucleo_Adc.Init.SamplingTimeCommon    = ADC_SAMPLETIME_41CYCLES_5;
    
    /* Initialize MSP related to ADC */
    ADCx_MspInit(&hnucleo_Adc);
    
    /* Initialize ADC */
    if (HAL_ADC_Init(&hnucleo_Adc) != HAL_OK)
    {
      return HAL_ERROR;
    }

    /* Run ADC calibration */
    if (HAL_ADCEx_Calibration_Start(&hnucleo_Adc) != HAL_OK)
    {
      return HAL_ERROR;
    }
  }
  
  return HAL_OK;
}
/**
  * @brief  Initializes ADC HAL.
  * @retval None
  */
static HAL_StatusTypeDef ADCx_Init(void)
{
  if(HAL_ADC_GetState(&hnucleo_Adc) == HAL_ADC_STATE_RESET)
  {
    /* ADC Config */
    hnucleo_Adc.Instance                    = NUCLEO_ADCx;
    hnucleo_Adc.Init.ClockPrescaler         = ADC_CLOCK_ASYNC_DIV8; /* (must not exceed 16MHz) */
    hnucleo_Adc.Init.Resolution             = ADC_RESOLUTION_12B;
    hnucleo_Adc.Init.DataAlign              = ADC_DATAALIGN_RIGHT;
    hnucleo_Adc.Init.ScanConvMode           = DISABLE;
    hnucleo_Adc.Init.EOCSelection           = ADC_EOC_SINGLE_CONV;
    hnucleo_Adc.Init.LowPowerAutoWait       = ENABLE;
    hnucleo_Adc.Init.ContinuousConvMode     = DISABLE;
    hnucleo_Adc.Init.NbrOfConversion        = 1;
    hnucleo_Adc.Init.DiscontinuousConvMode  = DISABLE;
    hnucleo_Adc.Init.NbrOfDiscConversion    = 1;
    hnucleo_Adc.Init.ExternalTrigConv       = ADC_SOFTWARE_START;
    hnucleo_Adc.Init.ExternalTrigConvEdge   = ADC_EXTERNALTRIGCONVEDGE_NONE;
    hnucleo_Adc.Init.DMAContinuousRequests  = DISABLE;
    hnucleo_Adc.Init.Overrun                = ADC_OVR_DATA_PRESERVED;
    hnucleo_Adc.Init.OversamplingMode       = DISABLE;
    
    ADCx_MspInit(&hnucleo_Adc);
    if (HAL_ADC_Init(&hnucleo_Adc) != HAL_OK)
    {
      return HAL_ERROR;
    }
    
    if (HAL_ADCEx_Calibration_Start(&hnucleo_Adc,ADC_SINGLE_ENDED) != HAL_OK)
    {
      return HAL_ERROR;
    }
  }

  return HAL_OK;
}  
Exemple #16
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 48 MHz */
  SystemClock_Config();
  
  
  /*## Configure peripherals #################################################*/
  
  /* Initialize LED on board */
  BSP_LED_Init(LED2);
  
  /* Configure User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);
  
  /* Configure the ADCx peripheral */
  ADC_Config();
  
  /* Run the ADC calibration */
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }

#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Configure the TIM peripheral */
  TIM_Config();
#endif /* ADC_TRIGGER_FROM_TIMER */

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
  /* Configure the DAC peripheral and generate a constant voltage of Vdda/2.  */
  WaveformVoltageGenerationForTest_Config();
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */
  
  
  /*## Enable peripherals ####################################################*/
  
#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Timer enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
#endif /* ADC_TRIGGER_FROM_TIMER */
  
  
  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
  if (HAL_ADC_Start_DMA(&AdcHandle,
                        (uint32_t *)aADCxConvertedValues,
                        ADCCONVERTEDVALUES_BUFFER_SIZE
                       ) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  
  /* Infinite loop */
  while (1)
  {
  
    /* Turn-on/off LED2 in function of ADC conversion result */
    /* - Turn-off if voltage is into AWD window */
    /* - Turn-on if voltage is out of AWD window */

    /* Variable of analog watchdog status is set into analog watchdog         */
    /* interrupt callback                                                     */
    if (ubAnalogWatchdogStatus == RESET)
    {
      BSP_LED_Off(LED2);
    }
    else
    {
      BSP_LED_On(LED2);
      
      /* Reset analog watchdog status for next loop iteration */
      ubAnalogWatchdogStatus = RESET;
    }
  
    /* For information: ADC conversion results are stored into array          */
    /* "aADCxConvertedValues" (for debug: check into watch window)            */
  
  
    /* Wait for event on push button to perform following actions */
    while ((ubUserButtonClickEvent) == RESET)
    {
    }
    /* Reset variable for next loop iteration */
    ubUserButtonClickEvent = RESET;

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
    /* Modifies the voltage level incrementally from 0V to Vdda at each call. */
    /* Circular waveform of ramp: When the maximum level is reaches,          */
    /* restart from 0V.                                                       */
    WaveformVoltageGenerationForTest_Update();
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */
  }
}
Exemple #17
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F103xB HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 64 MHz */
  SystemClock_Config();
  
  /*## Configure peripherals #################################################*/
  
  /* Initialize LED on board */
  BSP_LED_Init(LED2);
  
  /* Configure User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);
  
  /* Configure the ADC peripheral */
  ADC_Config();
  
  /* Run the ADC calibration */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }

#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Configure the TIM peripheral */
  TIM_Config();
#endif /* ADC_TRIGGER_FROM_TIMER */

  /* Note: This example, on some other STM32 boards, is performing            */
  /*       DAC configuration here.                                            */
  /*       On STM32F103RB-Nucleo, the device has no DAC available,            */
  /*       therefore analog signal must be supplied externally.               */

  /*## Enable peripherals ####################################################*/
#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Timer enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
#endif /* ADC_TRIGGER_FROM_TIMER */

  /* Note: This example, on some other STM32 boards, is performing            */
  /*       DAC signal generation here.                                        */
  /*       On STM32F103RB-Nucleo, the device has no DAC available,            */
  /*       therefore analog signal must be supplied externally.               */

  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
  if (HAL_ADC_Start_DMA(&AdcHandle,
                        (uint32_t *)aADCxConvertedValues,
                        ADCCONVERTEDVALUES_BUFFER_SIZE
                       ) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  
  /* Infinite loop */
  while (1)
  {
    /* Turn-on/off LED2 in function of ADC conversion result */
    /*  - Turn-off if voltage is into AWD window */ 
    /*  - Turn-on if voltage is out of AWD window */

    /* Variable of analog watchdog status is set into analog watchdog         */
    /* interrupt callback                                                     */
    if (ubAnalogWatchdogStatus == RESET)
    {
      BSP_LED_Off(LED2);
    }
    else
    {
      BSP_LED_On(LED2);
      
      /* Reset analog watchdog status for next loop iteration */
      ubAnalogWatchdogStatus = RESET;
    }
  
    /* For information: ADC conversion results are stored into array          */
    /* "aADCxConvertedValues" (for debug: check into watch window)            */
  
  
    /* Wait for event on push button to perform following actions */
    while ((ubUserButtonClickEvent) == RESET)
    {
    }
    /* Reset variable for next loop iteration */
    ubUserButtonClickEvent = RESET;

    /* Note: This example, on some other STM32 boards, is performing          */
    /*       DAC signal generation here.                                      */
    /*       On STM32F103RB-Nucleo, the device has no DAC available,          */
    /*       therefore analog signal must be supplied externally.             */
  }
}
Exemple #18
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F1xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 24 MHz */
  SystemClock_Config();
  
  /*## Configure peripherals #################################################*/
  
  /* Initialize LEDs on board */
  BSP_LED_Init(LED4);
  BSP_LED_Init(LED3);
  
  /* Configure User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);
  
  /* Configure the ADC peripheral */
  ADC_Config();
  
  /* Run the ADC calibration */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }

#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Configure the TIM peripheral */
  TIM_Config();
#endif /* ADC_TRIGGER_FROM_TIMER */
#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
  /* Configure the DAC peripheral */
  DAC_Config();
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */

  /*## Enable peripherals ####################################################*/
#if defined(ADC_TRIGGER_FROM_TIMER)
  /* Timer enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
#endif /* ADC_TRIGGER_FROM_TIMER */

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
  /* Set DAC Channel data register: channel corresponding to ADC channel CHANNELa */
  /* Set DAC output to 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
  if (HAL_DAC_SetValue(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa, DAC_ALIGN_12B_R, RANGE_12BITS/2) != HAL_OK)
  {
    /* Setting value Error */
    Error_Handler();
  }
  
  /* Enable DAC Channel: channel corresponding to ADC channel CHANNELa */
  if (HAL_DAC_Start(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */

  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
  if (HAL_ADC_Start_DMA(&AdcHandle,
                        (uint32_t *)aADCxConvertedValues,
                        ADCCONVERTEDVALUES_BUFFER_SIZE
                       ) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  
  /* Infinite loop */
  while (1)
  {

    /* Wait for event on push button to perform following actions */
    while ((ubUserButtonClickEvent) == RESET)
    {
    }
    /* Reset variable for next loop iteration */
    ubUserButtonClickEvent = RESET;
    
    /* Start ADC conversion on injected group */
    if (HAL_ADCEx_InjectedStart_IT(&AdcHandle) != HAL_OK)
    {
      /* Start Conversation Error */
      Error_Handler();
    }
    

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
    /* Set DAC voltage on channel corresponding to ADCx_CHANNELa              */
    /* in function of user button clicks count.                               */
    /* Set DAC output successively to:                                        */
    /*  - minimum of full range (0 <=> ground 0V)                             */
    /*  - 1/4 of full range (4095 <=> Vdda=3.3V): 1023 <=> 0.825V             */
    /*  - 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
    /*  - 3/4 of full range (4095 <=> Vdda=3.3V): 3071 <=> 2.475V             */
    /*  - maximum of full range (4095 <=> Vdda=3.3V)                          */
    if (HAL_DAC_SetValue(&DacHandle,
                         DACx_CHANNEL_TO_ADCx_CHANNELa,
                         DAC_ALIGN_12B_R,
                         (RANGE_12BITS * ubUserButtonClickCount / USERBUTTON_CLICK_COUNT_MAX)
                        ) != HAL_OK)
    {
      /* Start Error */
      Error_Handler();
    }
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */

    /* Wait for acquisition time of ADC samples on regular and injected       */
    /* groups:                                                                */
    /* wait time to let 1/2 buffer of regular group to be filled (in ms)      */
    HAL_Delay(16);
    
    /* Turn-on/off LED3 in function of ADC conversion result */
    /* - Turned-off if voltage measured by injected group is below voltage    */
    /*   measured by regular group (average of results table)                 */
    /* - Turned-off if voltage measured by injected group is above voltage    */
    /*   measured by regular group (average of results table)                 */
    
    /* Variables of conversions results are updated into ADC conversions      */
    /* interrupt callback.                                                    */
    if (uhADCxConvertedValue_Injected < *puhADCxConvertedValue_Regular_Avg)
    {
      BSP_LED_Off(LED3);
    }
    else
    {
      BSP_LED_On(LED3);
    }
  
    /* For information: ADC conversion results are stored into array          */
    /* "aADCxConvertedValues" (for debug: check into watch window)            */
    
  }
}
Exemple #19
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure LED1 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);
  
  /* Configure the system clock to 72 MHz */
  SystemClock_Config();


  /*## Configuration of peripherals ##########################################*/
  /* Configure the ADCx and ADCy peripherals */
  ADC_Config();

  /* Run the ADC calibration in single-ended mode */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle_master, ADC_SINGLE_ENDED) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }
  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle_slave, ADC_SINGLE_ENDED) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }
  
  /*## Enable peripherals ####################################################*/

  /* Enable ADC slave */
  if (HAL_ADC_Start(&AdcHandle_slave) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }

  /*## Start ADC conversions #################################################*/
  
  /* Start ADCx and ADCy multimode conversion with interruption */
  if (HAL_ADCEx_MultiModeStart_DMA(&AdcHandle_master, (uint32_t *)aADCDualConvertedValue, 256) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }

  /* Array "aADCDualConvertedValue" contains both ADC results on 16 bits:     */
  /*  - ADC master results in the 8 LSB [7:0]                                 */
  /*  - ADC slave results in the 8 MSB [15:8]                                 */
  
  /* Infinite loop */
  while (1)
  {
    if(aADCDualConversionDone == 1)
    {
      /* Toggle LED1: Conversions results are available                           */
      /* The toggle frequency depends on Conversion Value link to RV2 position    */
      /* In the case of this example:                                             */
      /* HAL_ADC_ConvCpltCallback() is called when DMA Transfer process is        */
      /* completed.                                                               */
      /* Since ADC and DMA are configured in continuous and circular mode, this   */
      /* function will be called each time the DMA buffer length is reached.      */
      BSP_LED_Toggle(LED1);
      HAL_Delay(aADCDualConversionValue*10);
      aADCDualConversionDone = 0;
    }
  }
}
Exemple #20
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 64 MHz */
  SystemClock_Config();
  
  /*## Configure peripherals #################################################*/
  /* Initialize LED on board */
  BSP_LED_Init(LED2);

  /* Configure User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);

  /* Configure the ADC peripheral */
  ADC_Config();
  
  /* Run the ADC calibration in single-ended mode */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle, ADC_SINGLE_ENDED) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }

  /* Configure the TIM peripheral */
  TIM_Config();
  
  /* Configure the DAC peripheral */
  DAC_Config();
  

  /*## Enable peripherals ####################################################*/

  /* Timer counter enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
  
  /* Set DAC Channel data register: channel corresponding to ADC channel CHANNELa */
  /* Set DAC output to 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
  if (HAL_DAC_SetValue(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa, DAC_ALIGN_12B_R, RANGE_12BITS/2) != HAL_OK)
  {
    /* Setting value Error */
    Error_Handler();
  }
  
  /* Enable DAC Channel: channel corresponding to ADC channel CHANNELa */
  if (HAL_DAC_Start(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
    
  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
  if (HAL_ADC_Start_DMA(&AdcHandle,
                        (uint32_t *)aADCxConvertedValues,
                        ADCCONVERTEDVALUES_BUFFER_SIZE
                       ) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  
  /* Infinite loop */
  while (1)
  {
    /* Turn-on/off LED2 in function of ADC conversion result */
    /*  - Turn-off if voltage is into AWD window */ 
    /*  - Turn-on if voltage is out of AWD window */

    /* Variable of analog watchdog status is set into analog watchdog         */
    /* interrupt callback                                                     */
    if (ubAnalogWatchdogStatus == RESET)
    {
      BSP_LED_Off(LED2);
    }
    else
    {
      BSP_LED_On(LED2);
      
      /* Reset analog watchdog status for next loop iteration */
      ubAnalogWatchdogStatus = RESET;
    }
  
    /* For information: ADC conversion results are stored into array          */
    /* "aADCxConvertedValues" (for debug: check into watch window)            */
  
  
    /* Wait for event on push button to perform following actions */
    while ((ubUserButtonClickEvent) == RESET)
    {
      __NOP();
    }
    /* Reset variable for next loop iteration */
    ubUserButtonClickEvent = RESET;

    /* Set DAC voltage on channel corresponding to ADCx_CHANNELa              */
    /* in function of user button clicks count.                               */
    /* Set DAC output successively to:                                        */
    /*  - minimum of full range (0 <=> ground 0V)                             */
    /*  - 1/4 of full range (4095 <=> Vdda=3.3V): 1023 <=> 0.825V             */
    /*  - 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
    /*  - 3/4 of full range (4095 <=> Vdda=3.3V): 3071 <=> 2.475V             */
    /*  - maximum of full range (4095 <=> Vdda=3.3V)                          */
    if (HAL_DAC_SetValue(&DacHandle,
                         DACx_CHANNEL_TO_ADCx_CHANNELa,
                         DAC_ALIGN_12B_R,
                         (RANGE_12BITS * ubUserButtonClickCount / USERBUTTON_CLICK_COUNT_MAX)
                        ) != HAL_OK)
    {
      /* Start Error */
      Error_Handler();
    }
  }
}
Exemple #21
0
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_ADC_Init();
  MX_I2C1_Init();
  MX_RTC_Init();
  MX_USART1_UART_Init();
  MX_SPI2_Init();

  /* Initialize interrupts */
  MX_NVIC_Init();

  /* USER CODE BEGIN 2 */

  HAL_ADCEx_Calibration_Start(&hadc, ADC_SINGLE_ENDED);

    /* Enable Ultra low power mode */
    HAL_PWREx_EnableUltraLowPower();
    __HAL_RCC_WAKEUPSTOP_CLK_CONFIG(RCC_STOP_WAKEUPCLOCK_HSI);

    /* Buffer used for transmission on USART1 */
    char tx1_buffer[120];


    RFM95_init(&hspi2);

    uint8_t payload_buff[14];
    PAYLOAD_Garden payload_garden;
    payload_garden.MessageType = 50;
    payload_garden.MessageId = 0;


    // Start in sensing mode.
    state = MAIN_STATE_SENSE;

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
    while (1) {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

        /* Do some work */
        if (state == MAIN_STATE_SENSE) {
            HAL_ADC_Start(&hadc);
            // junk readings
            payload_garden.Temperature = TEMPERATURE_external();
            payload_garden.CpuTemperature = TEMPERATURE_cpu();

            HAL_GPIO_WritePin(GPIOA, LED_Pin, GPIO_PIN_SET);

            payload_garden.MessageId++;
            payload_garden.VCC = BATTERY_vcc();
            payload_garden.ChargeMv = BATTERY_ChargeMv();
            payload_garden.ChargeMa = BATTERY_ChargeMa();



            /* Get the light reading while the adc gets ready */
            payload_garden.Light = LIGHT_lux();

            payload_garden.Temperature = TEMPERATURE_external();
            payload_garden.CpuTemperature = TEMPERATURE_cpu();
            HAL_ADC_Stop(&hadc);

            sprintf(tx1_buffer, "id:%d, vcc:%d, mv:%d, ma:%d, C:%d, cpuC:%d, lux:%d\n",
                    payload_garden.MessageId,
                    payload_garden.VCC,
                    payload_garden.ChargeMv,
                    payload_garden.ChargeMa,
                    payload_garden.Temperature,
                    payload_garden.CpuTemperature,
                    payload_garden.Light);
            HAL_UART_Transmit(&huart1, (uint8_t*) tx1_buffer, strlen(tx1_buffer), 1000);

            PAYLOAD_Garden_serialize(payload_garden, payload_buff);
            RFM95_send(&hspi2, payload_buff, 14);

            state = MAIN_STATE_TX;
        }

        /* Do nothing while the transmission is in progress */
        else if (state == MAIN_STATE_TX) {
            if (dio0_action == 1) {
                RFM95_setMode(&hspi2, RFM95_MODE_SLEEP);
                state = MAIN_STATE_SLEEP;
            }

            //TMP while interrupts are investigated
            //HAL_Delay(30);
            //state = MAIN_STATE_SLEEP;
        }

        /* Now that all the work is done, sleep until its time to do it all again */
        else if (state == MAIN_STATE_SLEEP) {
            HAL_GPIO_WritePin(GPIOA, LED_Pin, GPIO_PIN_RESET);

            //TMP while RFM is diabled
            //HAL_Delay(1000);

            /* Turn off the pin interrupts */
            HAL_NVIC_DisableIRQ(EXTI4_15_IRQn);

            HAL_SuspendTick();

            /* Enter Stop Mode */
            HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, 60,
            RTC_WAKEUPCLOCK_CK_SPRE_16BITS);
            HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
            HAL_RTCEx_DeactivateWakeUpTimer(&hrtc);
            HAL_ResumeTick();

            /* Turn on the pin interrupts */
            HAL_NVIC_EnableIRQ(EXTI4_15_IRQn);

            state = MAIN_STATE_SENSE;
        }

    }
  /* USER CODE END 3 */

}
Exemple #22
0
/* ADC init function */
void MX_ADC_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    /* Peripheral clock enable */
    __ADC1_CLK_ENABLE();
    /* DMA controller clock enable */
    __DMA1_CLK_ENABLE();

    /**ADC GPIO Configuration
    PA0-WKUP     ------> ADC_IN0
    */
    GPIO_InitStruct.Pin = GPIO_PIN_0;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* Peripheral DMA init*/

    DmaHandle.Instance = DMA1_Channel1;
    DmaHandle.Init.Request = DMA_REQUEST_0;
    DmaHandle.Init.Direction = DMA_PERIPH_TO_MEMORY;
    DmaHandle.Init.PeriphInc = DMA_PINC_DISABLE;
    DmaHandle.Init.MemInc = DMA_MINC_ENABLE;
    DmaHandle.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
    DmaHandle.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
    DmaHandle.Init.Mode = DMA_CIRCULAR;
    DmaHandle.Init.Priority = DMA_PRIORITY_MEDIUM;
    HAL_DMA_DeInit(&DmaHandle);
    HAL_DMA_Init(&DmaHandle);

    __HAL_LINKDMA(&AdcHandle, DMA_Handle, DmaHandle);

    /* DMA interrupt init */
    HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 1, 0);
    HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);

    ADC_ChannelConfTypeDef sConfig;
    ADC_AnalogWDGConfTypeDef AnalogWDGConfig;

    /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
    */
    AdcHandle.Instance = ADC1;
    AdcHandle.Init.OversamplingMode = DISABLE;
    AdcHandle.Init.ClockPrescaler = ADC_CLOCKPRESCALER_PCLK_DIV1;
    AdcHandle.Init.Resolution = ADC_RESOLUTION8b;
    AdcHandle.Init.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
    AdcHandle.Init.ScanDirection = ADC_SCAN_DIRECTION_UPWARD;
    AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT;
    AdcHandle.Init.ContinuousConvMode = ENABLE;
    AdcHandle.Init.DiscontinuousConvMode = DISABLE;
    AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIG_EDGE_NONE;
    AdcHandle.Init.DMAContinuousRequests = ENABLE;
    AdcHandle.Init.EOCSelection = EOC_SINGLE_CONV;
    AdcHandle.Init.Overrun = OVR_DATA_PRESERVED;
    AdcHandle.Init.LowPowerAutoWait = DISABLE;
    AdcHandle.Init.LowPowerFrequencyMode = DISABLE;
    AdcHandle.Init.LowPowerAutoOff = DISABLE;

    HAL_ADC_Init(&AdcHandle);
    HAL_ADCEx_Calibration_Start(&AdcHandle, ADC_SINGLE_ENDED);

    sConfig.Channel = ADC_CHANNEL_0;
    HAL_ADC_ConfigChannel(&AdcHandle, &sConfig);

    /**Configure the analog watchdog
    */
    AnalogWDGConfig.WatchdogMode = ADC_ANALOGWATCHDOG_SINGLE_REG;
    AnalogWDGConfig.Channel = ADC_CHANNEL_0;
    AnalogWDGConfig.ITMode = ENABLE;
    AnalogWDGConfig.HighThreshold = 0;
    AnalogWDGConfig.LowThreshold = 0;
    HAL_ADC_AnalogWDGConfig(&AdcHandle, &AnalogWDGConfig);

    HAL_ADC_Start_DMA(&AdcHandle, &resultDMA, DMA_BUFFER_SIZE);

}
/** \brief 温度控制硬件初始化
 *
 * \return void
 */
void hw_TemperatureManageInit(void)
{
    ///ADC配置,ADC1,in10,in11,in12,in13
    GPIO_InitTypeDef    GPIO_InitStruct;
    TIM_OC_InitTypeDef  TIM_InitStruct;
    ADC_ChannelConfTypeDef sConfig;

    ADC_HandleStruct.Instance                       = ADC1;

    if (HAL_ADC_DeInit(&ADC_HandleStruct) != HAL_OK)
    {
        return;
    }

    ADC_HandleStruct.Init.ScanConvMode              = ADC_SCAN_ENABLE;
    ADC_HandleStruct.Init.ContinuousConvMode        = ENABLE;
    ADC_HandleStruct.Init.DiscontinuousConvMode     = DISABLE;
    ADC_HandleStruct.Init.DataAlign                 = ADC_DATAALIGN_RIGHT;
    ADC_HandleStruct.Init.ExternalTrigConv          = ADC_SOFTWARE_START;
    ADC_HandleStruct.Init.NbrOfConversion           = HEATER_COUNT;

    init_BeforeADC();
    HAL_ADC_Init(&ADC_HandleStruct);


    sConfig.Channel = ADC_CHANNEL_10;                        ///Channel_Extruder_0
    sConfig.Rank = 1;
    sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
    HAL_ADC_ConfigChannel(&ADC_HandleStruct, &sConfig);

#ifdef HEATBED_ENABLED
    sConfig.Channel = ADC_CHANNEL_11;                        ///Channel_bed
    sConfig.Rank = 2;
    sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
    HAL_ADC_ConfigChannel(&ADC_HandleStruct, &sConfig);
#endif
#ifdef EXTRUDER_2_ENABLED
    sConfig.Channel = ADC_CHANNEL_12;                        ///Channel_Extruder_1
    sConfig.Rank = 3;
    sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
    HAL_ADC_ConfigChannel(&ADC_HandleStruct, &sConfig);
#endif
#ifdef EXTRUDER_3_ENABLED
    sConfig.Channel = ADC_CHANNEL_13;                        ///Channel_Extruder_2
    sConfig.Rank = 4;
    sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
    HAL_ADC_ConfigChannel(&ADC_HandleStruct, &sConfig);
#endif
    HAL_ADCEx_Calibration_Start(&ADC_HandleStruct);

    ///ADC时钟配置  采样周期100ms
    __HAL_RCC_TIM6_CLK_ENABLE();
    TIM_ADC_HandleStruct.Instance           = TIM6;
    TIM_ADC_HandleStruct.Init.Period        = 1000 - 1;
    TIM_ADC_HandleStruct.Init.Prescaler     = (uint32_t) (SystemCoreClock/2/10000) - 1;
    TIM_ADC_HandleStruct.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    TIM_ADC_HandleStruct.Init.CounterMode   = TIM_COUNTERMODE_UP;
    HAL_TIM_Base_Init(&TIM_ADC_HandleStruct);
    __HAL_TIM_SET_COUNTER(&TIM_ADC_HandleStruct, 0);

    HAL_NVIC_SetPriority(TIM6_IRQn, 4, 0);
    HAL_NVIC_EnableIRQ(TIM6_IRQn);

    ///加热PWM配置  PB6,7,8,9
    __HAL_RCC_GPIOB_CLK_ENABLE();

    GPIO_InitStruct.Pin = GPIO_PIN_6;
#ifdef HEATBED_ENABLED
    GPIO_InitStruct.Pin |= GPIO_PIN_7;
#endif
#ifdef EXTRUDER_2_ENABLED
    GPIO_InitStruct.Pin |= GPIO_PIN_8;
#endif
#ifdef EXTRUDER_3_ENABLED
    GPIO_InitStruct.Pin |= GPIO_PIN_9;
#endif
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;             ///内部不做上下拉电阻
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    ///PWM时钟配置
    __HAL_RCC_TIM4_CLK_ENABLE();
    TIM_PWM_HandleStruct.Instance = TIM4;
    TIM_PWM_HandleStruct.Init.Prescaler = (uint32_t) (SystemCoreClock/2/250000) - 1;
    TIM_PWM_HandleStruct.Init.Period = 254;         ///总共255
    TIM_PWM_HandleStruct.Init.ClockDivision = 0;
    TIM_PWM_HandleStruct.Init.CounterMode = TIM_COUNTERMODE_UP;
    HAL_TIM_PWM_Init(&TIM_PWM_HandleStruct);

    TIM_InitStruct.OCMode = TIM_OCMODE_PWM1;
    TIM_InitStruct.OCPolarity = TIM_OCPOLARITY_HIGH;
    TIM_InitStruct.OCFastMode = TIM_OCFAST_DISABLE;
    TIM_InitStruct.Pulse = 0;

    HAL_TIM_PWM_ConfigChannel(&TIM_PWM_HandleStruct, &TIM_InitStruct, TIM_CHANNEL_1);
#ifdef HEATBED_ENABLED
    HAL_TIM_PWM_ConfigChannel(&TIM_PWM_HandleStruct, &TIM_InitStruct, TIM_CHANNEL_2);
#endif
#ifdef EXTRUDER_2_ENABLED
    HAL_TIM_PWM_ConfigChannel(&TIM_PWM_HandleStruct, &TIM_InitStruct, TIM_CHANNEL_3);
#endif
#ifdef EXTRUDER_3_ENABLED
    HAL_TIM_PWM_ConfigChannel(&TIM_PWM_HandleStruct, &TIM_InitStruct, TIM_CHANNEL_4);
#endif
}
Exemple #24
0
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC_Init();
  APP_ADC_Init(&hadc);

#ifdef USE_COMPARATORS
  MX_COMP1_Init();
  MX_COMP2_Init();
#endif
  MX_DAC_Init();
  MX_USART2_UART_Init();

  /* USER CODE BEGIN 2 */


  HAL_UART_Transmit(&huart2,str,strlen((const char *) str),1000);
  HAL_UART_Transmit(&huart2,heading,strlen((const char *) heading),1000);

  dacConfig.DAC_Trigger =  DAC_TRIGGER_NONE;
  dacConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_DISABLE;
  HAL_DAC_ConfigChannel(&hdac,&dacConfig,DAC_CHANNEL_1);
  HAL_DAC_SetValue(&hdac,DAC_CHANNEL_1,DAC_ALIGN_12B_R,2048);
  HAL_DAC_Start(&hdac,DAC_CHANNEL_1);


  /* Initialize ADC peripheral according to the passed parameters */
  if (HAL_ADC_Init(&hadc) != HAL_OK)
  {
    while(-1);
  }


  /* ### - 2 - Start calibration ############################################ */
  if (HAL_ADCEx_Calibration_Start(&hadc, ADC_SINGLE_ENDED) != HAL_OK)
  {
	  while(-1);
  }

  /* ### - 3 - Channel configuration ######################################## */
  /* Select Channel 0 to be converted */
  ///sConfig.Channel = ADC_CHANNEL_0;
  //if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
  //{
  //  Error_Handler();
  //}

  /* ### - 4 - Start conversion in DMA mode ################################# */
  if (HAL_ADC_Start_DMA(&hadc, (uint32_t *) adcBuf,ADC_BUFSIZE) != HAL_OK)
  {
	  while(-1);
  }
  compValues[0]= '-';
  compValues[1]= '-';

#ifdef USE_COMPARATORS

  HAL_COMP_Start_IT(&hcomp1);
  HAL_COMP_Start_IT(&hcomp2);
#endif

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  uint16_t cnt=0;
  uint16_t dacValue = 0;
  memset(dataline, ' ', sizeof(dataline));
  dataline[sizeof(dataline)-1] = 0;

  while (1)
  {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */
	  HAL_DAC_SetValue(&hdac,DAC_CHANNEL_1,DAC_ALIGN_12B_R,dacValue);


#ifdef WAIT_BEFORE_READING
	  int i;
	  for(i=0; i < 10000; i++);
#endif
	  itoa (cnt,(char *) &dataline[0],5);
	  itoa (dacValue,(char *)&dataline[10],5);

	  itoa (adcBuf[0],(char *)&dataline[20],4);
	  dataline[25] = '/';
	  itoa (adcBuf[2],(char *)&dataline[25],4);

	  itoa (adcBuf[1],(char *)&dataline[40],4);
	  dataline[45] = '/';
	  itoa (adcBuf[3],(char *)&dataline[45],4);

#ifdef USE_COMPARATORS
	  dataline[60] =  compValues[0];
	  dataline[65] =  compValues[1];
#else
//	  memcpy("Not Used",dataline[60],8);
#endif
	  dataline[70] =  (HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_6)==GPIO_PIN_SET)?'X':'0';
	  dataline[75] =  (HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_7)==GPIO_PIN_SET)?'X':'0';

	  dataline[87] = '\r';
	  dataline[88] = '\n';
	  dataline[89] = 0;

	  HAL_UART_Transmit(&huart2,dataline,strlen((const char *) dataline),1000);
	  cnt++;

	  dacValue = (dacValue >= (4096-DAC_STEPSIZE))?0:dacValue+DAC_STEPSIZE;
  }
  /* USER CODE END 3 */

}
Exemple #25
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
   
  /* Configure the system clock to 72 MHz */
  SystemClock_Config();
  
  /*## Configuration of peripherals ##########################################*/
  /* Initialize LEDs on board */
  BSP_LED_Init(LED2);
  BSP_LED_Init(LED3);
  
  /* Initialize the User Button in Interrupt mode */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
  
  /* Configure external lines 9 to 5 in interrupt mode */
  EXTILine9_5_Config();  

  /* Configuration of ADC peripheral */
  ADC_Config();
  
  /* Run the ADC calibration in differential mode */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle, ADC_DIFFERENTIAL_ENDED) != HAL_OK)
  {
    /* Start Conversation Error */
    Error_Handler();
  }
  
  /* Configuration of DAC peripheral */
  DAC_Config();
  

  /*## Enable peripherals ####################################################*/
  
  /* Set DAC Channel data register: channel corresponding to ADC channel ADCx_CHANNEL_DIFF_HIGH */
  /* Set DAC output to 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V */
  if (HAL_DAC_SetValue(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNEL_DIFF_HIGH, DAC_ALIGN_12B_R, RANGE_12BITS/2) != HAL_OK)
  {
    /* Setting value Error */
    Error_Handler();
  }

  /* Set DAC Channel data register: channel corresponding to ADC channel ADCx_CHANNEL_DIFF_LOW */
      /* Set DAC output to minimum of full range (0 <=> ground 0V) */
  if (HAL_DAC_SetValue(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNEL_DIFF_LOW, DAC_ALIGN_12B_R, 0) != HAL_OK)
  {
    /* Setting value Error */
    Error_Handler();
  }
  
  /* Enable DAC Channel: channel corresponding to ADC channel ADCx_CHANNEL_DIFF_HIGH */
  if (HAL_DAC_Start(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNEL_DIFF_HIGH) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  /* Enable DAC Channel: channel corresponding to ADC channel ADCx_CHANNEL_DIFF_LOW */
  if (HAL_DAC_Start(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNEL_DIFF_LOW) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with interruption */
  if (HAL_ADC_Start_IT(&AdcHandle) != HAL_OK)
  {
    /* Start Conversation Error */
    Error_Handler();
  }
    
  
  /* Infinite loop */
  while (1)
  {
    /* Set DAC voltage on channel corresponding to ADC channel ADCx_CHANNEL_DIFF_LOW */
    /* in function of user button clicks count.                               */
    /* Set DAC output succesively to:                                         */
    /*  - minimum of full range (0 <=> ground 0V)                             */
    /*  - 1/4 of full range (4095 <=> Vdda=3.3V): 1023 <=> 0.825V             */
    /*  - 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
    /*  - 3/4 of full range (4095 <=> Vdda=3.3V): 3071 <=> 2.475V             */
    /*  - maximum of full range (4095 <=> Vdda=3.3V)                          */
    if (HAL_DAC_SetValue(&DacHandle,
	                 DACx_CHANNEL_TO_ADCx_CHANNEL_DIFF_LOW, DAC_ALIGN_12B_R,
	                 (RANGE_12BITS * uwUserButtonClickCount / USERBUTTON_CLICK_COUNT_MAX)
	                 ) != HAL_OK)
    {
      /* Start Error */
      Error_Handler();
    }
    
    /* ADC Differential conversion result calculation:                        */
    /*  - An offset of half of full range is added to keep the full dynamic   */
    /*    range of differential voltage.                                      */
    /*  - Channels voltage is divided by 2, resolution is lowered of 1 bit.   */
    /*  => Diff conversion result = mid-range + (channel_high-channel_low)/2  */

    /* Turn-on/off LED2 in function of ADC differential conversion result */
    /*  - Turn-on LED2 if differential voltage is positive */
    /*  - Turn-off LED2 if differential voltage is negative */
    if (uhADCxConvertedValue > RANGE_12BITS/2)
    {
      BSP_LED_On(LED2);
    }
    else
    {
      BSP_LED_Off(LED2);
    }
  }
}
Exemple #26
0
void analogin_init(analogin_t *obj, PinName pin)
{
    uint32_t function = (uint32_t)NC;

    // ADC Internal Channels "pins"  (Temperature, Vref, Vbat, ...)
    //   are described in PinNames.h and PeripheralPins.c
    //   Pin value must be between 0xF0 and 0xFF
    if ((pin < 0xF0) || (pin >= 0x100)) {
        // Normal channels
        // Get the peripheral name from the pin and assign it to the object
        obj->handle.Instance = (ADC_TypeDef *)pinmap_peripheral(pin, PinMap_ADC);
        // Get the functions (adc channel) from the pin and assign it to the object
        function = pinmap_function(pin, PinMap_ADC);
        // Configure GPIO
        pinmap_pinout(pin, PinMap_ADC);
    } else {
        // Internal channels
        obj->handle.Instance = (ADC_TypeDef *)pinmap_peripheral(pin, PinMap_ADC_Internal);
        function = pinmap_function(pin, PinMap_ADC_Internal);
        // No GPIO configuration for internal channels
    }
    MBED_ASSERT(obj->handle.Instance != (ADC_TypeDef *)NC);
    MBED_ASSERT(function != (uint32_t)NC);

    obj->channel = STM_PIN_CHANNEL(function);

    // Save pin number for the read function
    obj->pin = pin;

    // Configure ADC object structures
    obj->handle.State = HAL_ADC_STATE_RESET;
    obj->handle.Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV2;
    obj->handle.Init.Resolution            = ADC_RESOLUTION_12B;
    obj->handle.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
    obj->handle.Init.ScanConvMode          = DISABLE;
    obj->handle.Init.EOCSelection          = ADC_EOC_SINGLE_CONV;
    obj->handle.Init.LowPowerAutoWait      = DISABLE;
    obj->handle.Init.ContinuousConvMode    = DISABLE;
    obj->handle.Init.NbrOfConversion       = 1;
    obj->handle.Init.DiscontinuousConvMode = DISABLE;
    obj->handle.Init.NbrOfDiscConversion   = 0;
    obj->handle.Init.ExternalTrigConv      = ADC_EXTERNALTRIGCONV_T1_CC1;
    obj->handle.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
    obj->handle.Init.DMAContinuousRequests = DISABLE;
    obj->handle.Init.Overrun               = ADC_OVR_DATA_OVERWRITTEN;

#if defined(ADC1)
    if ((ADCName)obj->handle.Instance == ADC_1) {
        __HAL_RCC_ADC1_CLK_ENABLE();
    }
#endif
#if defined(ADC2)
    if ((ADCName)obj->handle.Instance == ADC_2) {
        __HAL_RCC_ADC2_CLK_ENABLE();
    }
#endif
#if defined(ADC3)
    if ((ADCName)obj->handle.Instance == ADC_3) {
        __HAL_RCC_ADC34_CLK_ENABLE();
    }
#endif
#if defined(ADC4)
    if ((ADCName)obj->handle.Instance == ADC_4) {
        __HAL_RCC_ADC34_CLK_ENABLE();
    }
#endif

    if (HAL_ADC_Init(&obj->handle) != HAL_OK) {
        error("Cannot initialize ADC\n");
    }

    if (!HAL_ADCEx_Calibration_GetValue(&obj->handle, ADC_SINGLE_ENDED)) {
        HAL_ADCEx_Calibration_Start(&obj->handle, ADC_SINGLE_ENDED);
    }
}
Exemple #27
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
 /* This sample code shows how to convert an analog input and read the converted
    data using DMA transfer.
    To proceed, 4 steps are required: */
   
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();

  /* No LED3 to Init */

  /* Configure the system clock to 48 MHz */
  SystemClock_Config();

  /* ### - 1 - Initialize ADC peripheral #################################### */
  /*
   *  Instance                  = ADC1.
   *  ClockPrescaler            = PCLK divided by 4.
   *  LowPowerAutoWait          = Disabled
   *  LowPowerAutoPowerOff      = Disabled
   *  Resolution                = 12 bit (increased to 16 bit with oversampler)
   *  ScanConvMode              = ADC_SCAN_ENABLE 
   *  DataAlign                 = Right
   *  ContinuousConvMode        = Enabled
   *  DiscontinuousConvMode     = Enabled
   *  ExternalTrigConv          = ADC_SOFTWARE_START
   *  ExternalTrigConvEdge      = None (Software start)
   *  EOCSelection              = End Of Conversion event
   *  DMAContinuousRequests     = ENABLE
   */

  AdcHandle.Instance = ADC1;
  
  AdcHandle.Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV4;
  AdcHandle.Init.LowPowerAutoWait      = DISABLE;
  AdcHandle.Init.LowPowerAutoPowerOff  = DISABLE;
  AdcHandle.Init.Resolution            = ADC_RESOLUTION_12B;
  AdcHandle.Init.ScanConvMode          = ADC_SCAN_ENABLE;
  AdcHandle.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
  AdcHandle.Init.ContinuousConvMode    = ENABLE;
  AdcHandle.Init.DiscontinuousConvMode = DISABLE;
  AdcHandle.Init.ExternalTrigConv      = ADC_SOFTWARE_START;
  AdcHandle.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
  AdcHandle.Init.EOCSelection          = ADC_EOC_SINGLE_CONV;
  AdcHandle.Init.DMAContinuousRequests = ENABLE;
  AdcHandle.Init.Overrun               = ADC_OVR_DATA_OVERWRITTEN;
 
  /* Initialize ADC peripheral according to the passed parameters */
  if (HAL_ADC_Init(&AdcHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
  
  /* ### - 2 - Start calibration ############################################ */
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
  /* ### - 3 - Channel configuration ######################################## */
  /* Select Channel 0 to be converted */
  sConfig.Channel      = ADC_CHANNEL_0;
  sConfig.Rank         = ADC_RANK_CHANNEL_NUMBER;
  sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
  if (HAL_ADC_ConfigChannel(&AdcHandle, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  
  /* ### - 4 - Start conversion in DMA mode ################################# */
  if (HAL_ADC_Start_DMA(&AdcHandle, &aResultDMA, 1) != HAL_OK)
  {
    Error_Handler();
  }
  /* Infinite Loop */
  while (1)
  { 
  }
}
Exemple #28
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F103xG HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 72 MHz */
  SystemClock_Config();
  
  /*## Configure peripherals #################################################*/
  
  /* Initialize LEDs on board */
  BSP_LED_Init(LED3);
  BSP_LED_Init(LED1);
  
  /* Configure Key push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
  
  /* Configure the ADC peripheral */
  ADC_Config();
  
  /* Run the ADC calibration */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }


#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
  /* Configure the DAC peripheral */
  DAC_Config();
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */
  

  /*## Enable peripherals ####################################################*/
  
#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
  /* Set DAC Channel data register: channel corresponding to ADC channel CHANNELa */
  /* Set DAC output to 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
  if (HAL_DAC_SetValue(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa, DAC_ALIGN_12B_R, RANGE_12BITS/2) != HAL_OK)
  {
    /* Setting value Error */
    Error_Handler();
  }
  
  /* Enable DAC Channel: channel corresponding to ADC channel CHANNELa */
  if (HAL_DAC_Start(&DacHandle, DACx_CHANNEL_TO_ADCx_CHANNELa) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */

  /*## Start ADC conversions #################################################*/
  
  /* Start ADC conversion on regular group with transfer by DMA */
  if (HAL_ADC_Start_DMA(&AdcHandle,
                        (uint32_t *)aADCxConvertedValues,
                        ADCCONVERTEDVALUES_BUFFER_SIZE
                       ) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }
  
  
  /* Infinite loop */
  while (1)
  {

    /* Wait for event on push button to perform following actions */
    while ((ubUserButtonClickEvent) == RESET)
    {
    }
    /* Reset variable for next loop iteration */
    ubUserButtonClickEvent = RESET;

#if defined(WAVEFORM_VOLTAGE_GENERATION_FOR_TEST)
    /* Set DAC voltage on channel corresponding to ADCx_CHANNELa              */
    /* in function of user button clicks count.                               */
    /* Set DAC output successively to:                                        */
    /*  - minimum of full range (0 <=> ground 0V)                             */
    /*  - 1/4 of full range (4095 <=> Vdda=3.3V): 1023 <=> 0.825V             */
    /*  - 1/2 of full range (4095 <=> Vdda=3.3V): 2048 <=> 1.65V              */
    /*  - 3/4 of full range (4095 <=> Vdda=3.3V): 3071 <=> 2.475V             */
    /*  - maximum of full range (4095 <=> Vdda=3.3V)                          */
    if (HAL_DAC_SetValue(&DacHandle,
                         DACx_CHANNEL_TO_ADCx_CHANNELa,
                         DAC_ALIGN_12B_R,
                         (RANGE_12BITS * ubUserButtonClickCount / USERBUTTON_CLICK_COUNT_MAX)
                        ) != HAL_OK)
    {
      /* Start Error */
      Error_Handler();
    }
#endif /* WAVEFORM_VOLTAGE_GENERATION_FOR_TEST */

    /* Wait for DAC settling time */
    HAL_Delay(1);
    
    /* Start ADC conversion */
    /* Since sequencer is enabled in discontinuous mode, this will perform    */
    /* the conversion of the next rank in sequencer.                          */
    /* Note: For this example, conversion is triggered by software start,     */
    /*       therefore "HAL_ADC_Start()" must be called for each conversion.  */
    /*       Since DMA transfer has been initiated previously by function     */
    /*       "HAL_ADC_Start_DMA()", this function will keep DMA transfer      */
    /*       active.                                                          */
    HAL_ADC_Start(&AdcHandle);
      
    /* Wait for conversion completion before conditional check hereafter */
    HAL_ADC_PollForConversion(&AdcHandle, 1);
    
    /* Turn-on/off LED1 in function of ADC sequencer status */
    /* - Turn-off if sequencer has not yet converted all ranks */    
    /* - Turn-on if sequencer has converted all ranks */
    if (ubSequenceCompleted == RESET)
    {
      BSP_LED_Off(LED1);
    }
    else
    {
      BSP_LED_On(LED1);
      
      /* Computation of ADC conversions raw data to physical values */
      /* Note: ADC results are transferred into array "aADCxConvertedValues"  */
      /*       in the order of their rank in ADC sequencer.                   */
      uhADCChannelToDAC_mVolt    = COMPUTATION_DIGITAL_12BITS_TO_VOLTAGE(aADCxConvertedValues[0]);
      uhVrefInt_mVolt            = COMPUTATION_DIGITAL_12BITS_TO_VOLTAGE(aADCxConvertedValues[2]);
      wTemperature_DegreeCelsius = COMPUTATION_TEMPERATURE_STD_PARAMS(aADCxConvertedValues[1]);

      /* Reset variable for next loop iteration */
      ubSequenceCompleted = RESET;
    }
  }
}
Exemple #29
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
 /* This sample code shows how to convert an analog input and read the converted
    data using polling mode. */
   
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure the system clock to 48 MHz */
  SystemClock_Config();

  /* Initialize LEDs on board */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);

  
  /* Configure Tamper push-button in non-interrupt mode */
  BSP_PB_Init(BUTTON_TAMPER, BUTTON_MODE_GPIO);

  /* LCD Display init  */
  Display_Init();
  
  /* Configure the ADC peripheral */
  ADC_Config();

  /* Run the ADC calibration */  
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) != HAL_OK)
  {
    /* Calibration Error */
    Error_Handler();
  }

  /* Configure the TIM peripheral */
  TIM_Config();  

  /*## Enable peripherals ####################################################*/

  /* Timer counter enable */
  if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
  {
    /* Counter Enable Error */
    Error_Handler();
  }
  
  /* For this example purpose, enable ADC overrun interruption. */
  /* In this ADC LowPower example, ADC overrun is not considered as an error, */
  /* but as a way to watch the ADC low power modes effectiveness.             */
  /* Note: Enabling overrun has no usefulness except for this example purpose:*/
  /*       ADC overrun cannot occur with ADC low power mode "auto-wait"       */
  /*       Usually, in normal application, overrun is enabled automatically   */
  /*       by HAL ADC driver with functions "HAL_ADC_Start_IT()" or           */
  /*       "HAL_ADC_Start_DMA()", but this is not compliant with low power    */
  /*       modes. Refer to comments of parameter "LowPowerAutoWait" in HAL    */
  /*       ADC driver definition file.                                        */
  __HAL_ADC_ENABLE_IT(&AdcHandle, (ADC_IT_OVR));

  /* Start ADC conversion */
  HAL_ADC_Start(&AdcHandle);
  
  /* Wait for the first ADC conversion to be completed (timeout unit: ms) */
  HAL_ADC_PollForConversion(&AdcHandle, (1000/TIMER_FREQUENCY_HZ));
  
  /* Infinite loop */
  while (1)
  {
    /* Wait for at least 2 ADC conversions elapsed time, to let time for      */
    /* potential overrun event to occur (unit: ms)                            */
    HAL_Delay(2* (1000/TIMER_FREQUENCY_HZ));
  
    /* Manage LED1 status in function of ADC overrun event */
    if (ubADC_overrun_status != RESET)
    {
      /* Turn on LED1 to indicate ADC overrun event */
      BSP_LED_On(LED1);
      
      /* Reset overrun status variable for next iteration loop */ 
      ubADC_overrun_status = RESET;
    }
    else
    {
      /* Turn off LED1 to indicate no ADC overrun event */
      BSP_LED_Off(LED1);
    }
  
    /* Press Tamper push-button on STM32091C-EVAL to get the converted data */
    while(BSP_PB_GetState(BUTTON_TAMPER) != GPIO_PIN_RESET);
    while(BSP_PB_GetState(BUTTON_TAMPER) != GPIO_PIN_SET);
    
    /* Get ADC1 converted data */
    /* If ADC low power mode auto-wait is enabled, this release the ADC */
    /* from idle mode: a new conversion will start at the next trigger  */
    /* event.                                                           */
    uhADCxConvertedValue = HAL_ADC_GetValue(&AdcHandle);
    
    /* Compute the voltage */
    uhADCxConvertedVoltage = COMPUTATION_DIGITAL_12BITS_TO_VOLTAGE(uhADCxConvertedValue);
    
    /* Display converted data on the LCD */
    Display();
  }
}
Exemple #30
-41
/**
  * @brief  This function will set the ADC to the required value
  * @param  pin : the pin to use
  * @retval the value of the adc
  */
uint16_t adc_read_value(PinName pin)
{
  ADC_HandleTypeDef AdcHandle = {};
  ADC_ChannelConfTypeDef  AdcChannelConf = {};
  __IO uint16_t uhADCxConvertedValue = 0;

  AdcHandle.Instance = pinmap_peripheral(pin, PinMap_ADC);

  if (AdcHandle.Instance == NP) return 0;

#ifndef STM32F1xx
  AdcHandle.Init.ClockPrescaler        = ADC_CLOCK_DIV;          /* Asynchronous clock mode, input ADC clock divided */
  AdcHandle.Init.Resolution            = ADC_RESOLUTION_12B;            /* 12-bit resolution for converted data */
  AdcHandle.Init.EOCSelection          = ADC_EOC_SINGLE_CONV;           /* EOC flag picked-up to indicate conversion end */
  AdcHandle.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE; /* Parameter discarded because software trigger chosen */
  AdcHandle.Init.DMAContinuousRequests = DISABLE;                       /* DMA one-shot mode selected (not applied to this example) */
#endif
  AdcHandle.Init.DataAlign             = ADC_DATAALIGN_RIGHT;           /* Right-alignment for converted data */
  AdcHandle.Init.ScanConvMode          = DISABLE;                       /* Sequencer disabled (ADC conversion on only 1 channel: channel set on rank 1) */
  AdcHandle.Init.ContinuousConvMode    = DISABLE;                       /* Continuous mode disabled to have only 1 conversion at each conversion trig */
  AdcHandle.Init.DiscontinuousConvMode = DISABLE;                       /* Parameter discarded because sequencer is disabled */
  AdcHandle.Init.ExternalTrigConv      = ADC_SOFTWARE_START;            /* Software start to trig the 1st conversion manually, without external event */
  AdcHandle.State = HAL_ADC_STATE_RESET;
#if defined (STM32F0xx) || defined (STM32L0xx)
  AdcHandle.Init.LowPowerAutoWait      = DISABLE;                       /* Auto-delayed conversion feature disabled */
  AdcHandle.Init.LowPowerAutoPowerOff  = DISABLE;                       /* ADC automatically powers-off after a conversion and automatically wakes-up when a new conversion is triggered */
  AdcHandle.Init.Overrun               = ADC_OVR_DATA_OVERWRITTEN;      /* DR register is overwritten with the last conversion result in case of overrun */
#ifdef STM32F0xx
  AdcHandle.Init.SamplingTimeCommon    = SAMPLINGTIME;
#else // STM32L0
  //LowPowerFrequencyMode to enable if clk freq < 2.8Mhz
  AdcHandle.Init.SamplingTime          = SAMPLINGTIME;
#endif
#else
#ifdef STM32F3xx
  AdcHandle.Init.LowPowerAutoWait      = DISABLE;                       /* Auto-delayed conversion feature disabled */
#endif
  AdcHandle.Init.NbrOfConversion       = 1;                             /* Specifies the number of ranks that will be converted within the regular group sequencer. */
  AdcHandle.Init.NbrOfDiscConversion   = 0;                             /* Parameter discarded because sequencer is disabled */
#endif

  g_current_pin = pin; /* Needed for HAL_ADC_MspInit*/

  if (HAL_ADC_Init(&AdcHandle) != HAL_OK) {
    return 0;
  }

  AdcChannelConf.Channel      = get_adc_channel(pin);             /* Specifies the channel to configure into ADC */
#ifdef STM32L4xx
  if (!IS_ADC_CHANNEL(&AdcHandle, AdcChannelConf.Channel)) return 0;
#else
  if (!IS_ADC_CHANNEL(AdcChannelConf.Channel)) return 0;
#endif
  AdcChannelConf.Rank         = ADC_REGULAR_RANK_1;               /* Specifies the rank in the regular group sequencer */
#ifndef STM32L0xx
  AdcChannelConf.SamplingTime = SAMPLINGTIME;                     /* Sampling time value to be set for the selected channel */
#endif
#if defined (STM32F3xx) || defined (STM32L4xx)
  AdcChannelConf.SingleDiff   = ADC_SINGLE_ENDED;                 /* Single-ended input channel */
  AdcChannelConf.OffsetNumber = ADC_OFFSET_NONE;                  /* No offset subtraction */
  AdcChannelConf.Offset = 0;                                      /* Parameter discarded because offset correction is disabled */
#endif
  /*##-2- Configure ADC regular channel ######################################*/
  if (HAL_ADC_ConfigChannel(&AdcHandle, &AdcChannelConf) != HAL_OK)
  {
    /* Channel Configuration Error */
    return 0;
  }

#if defined (STM32F0xx) || defined (STM32F1xx) || defined (STM32F3xx) || defined (STM32L0xx) || defined (STM32L4xx)
  /*##-2.1- Calibrate ADC then Start the conversion process ####################*/
#if defined (STM32F0xx) || defined (STM32F1xx)
  if (HAL_ADCEx_Calibration_Start(&AdcHandle) !=  HAL_OK)
#else
  if (HAL_ADCEx_Calibration_Start(&AdcHandle, ADC_SINGLE_ENDED) !=  HAL_OK)
#endif
  {
    /* ADC Calibration Error */
    return 0;
  }
#endif

  /*##-3- Start the conversion process ####################*/
  if (HAL_ADC_Start(&AdcHandle) != HAL_OK)
  {
    /* Start Conversation Error */
    return 0;
  }

  /*##-4- Wait for the end of conversion #####################################*/
  /*  For simplicity reasons, this example is just waiting till the end of the
      conversion, but application may perform other tasks while conversion
      operation is ongoing. */
  if (HAL_ADC_PollForConversion(&AdcHandle, 10) != HAL_OK)
  {
    /* End Of Conversion flag not set on time */
    return 0;
  }

  /* Check if the continous conversion of regular channel is finished */
  if ((HAL_ADC_GetState(&AdcHandle) & HAL_ADC_STATE_REG_EOC) == HAL_ADC_STATE_REG_EOC)
  {
    /*##-5- Get the converted value of regular channel  ########################*/
    uhADCxConvertedValue = HAL_ADC_GetValue(&AdcHandle);
  }

  if (HAL_ADC_Stop(&AdcHandle) != HAL_OK)
  {
    /* Stop Conversation Error */
    return 0;
  }

  if(HAL_ADC_DeInit(&AdcHandle) != HAL_OK) {
    return 0;
  }

  return uhADCxConvertedValue;
}