Example #1
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_ADC_Init();
  MX_USART1_UART_Init();

  /* USER CODE BEGIN 2 */
  char ch;
  ch = 'x';
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 100);

  sprintf(strbuf,"Hello\n");

  uint32_t adcvals[5];
  HAL_ADC_Start(&hadc);

  /* USER CODE END 2 */

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

  /* USER CODE BEGIN 3 */
  	HAL_ADC_Start(&hadc);
	for (int i=0;i<3;i++){
		while(HAL_IS_BIT_CLR(hadc.Instance->ISR, (ADC_FLAG_EOC|ADC_FLAG_EOS))){}
		adcvals[i] = hadc.Instance->DR;
	}
	for (int i=0;i<5;i++){
		sprintf(strbuf,"i:%d,adc:%4d	",i,adcvals[i]);
		HAL_UART_Transmit(&huart1,strbuf,strlen(strbuf),1000);
	}
	
	sprintf(strbuf,"\n");
	HAL_UART_Transmit(&huart1,strbuf,strlen(strbuf),1000);
	HAL_Delay(1000);


  }
  /* USER CODE END 3 */

}
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F4xx 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 180 MHz */
  SystemClock_Config();

  /* Configure LED1 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);
  
  /*##-1- Configure ADC1, ADC2 and ADC3 peripherals ################################*/
  ADC_Config();

  /*##-2- Enable ADC3 ########################################################*/
  if(HAL_ADC_Start(&AdcHandle3) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }

  /*##-3- Enable ADC2 ########################################################*/
  if (HAL_ADC_Start(&AdcHandle2) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }

  /*##-4- Start ADC1 and ADC2 multimode conversion process and enable DMA ####*/
  if (HAL_ADCEx_MultiModeStart_DMA(&AdcHandle1, (uint32_t *)aADCTripleConvertedValue, 3) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #3
0
void test2(){
    //premier temps: Single mode //977us
    myanalogin_init(&adc,A1);
    wait_ms(10);
    HAL_ADC_Start(&myAdcHandle); // pour le continuous mode uniquement
    uint32_t tempo2[480]; // pour le continuous mode uniquement
    float tempo[480]; // 480 nb echantillons pendant 200us en theorie
    temp.start();
    for (int i = 0; i < 480; i++){
    //tempo[i]=myanalogin_read(&adc); // single mode
    //tempo2[i]=HAL_ADC_GetValue(&myAdcHandle); // continuous mode // 104us -> la conversion ne se fait probablement pas entierement -> changer le sampletime
        //HAL_ADC_Start(&myAdcHandle);
        tempo2[i]=HAL_ADC_GetValue(&myAdcHandle); // single mode V2 // 456us-> dememe on ne garanti que la conversion est faire entierement
        //while(!(__HAL_ADC_GET_FLAG(&myAdcHandle, ADC_FLAG_EOC)));
        HAL_ADC_PollForConversion(&myAdcHandle, 5);
        //wait_us(1);
    }
    temp.stop();
    printf("*********************");
    for (int i = 0; i < 480; i++){
        printf("%f \n",((float)tempo2[i] * (1.0f / (float)0xFFF))*3300);    
    }
    
    printf("duree: %d us \n", temp.read_us()); 

}
Example #4
0
uint32_t adc_read(uint32_t u32_adc_chan)
{
	ADC_ChannelConfTypeDef sConfigADC;
	uint32_t u32_adc_result = 0;
	uint8_t j = 0;
	uint8_t u8_num_conv = 10;

	/* Configure channel */
	sConfigADC.Rank = ADC_RANK_CHANNEL_NUMBER;
	sConfigADC.Channel = u32_adc_chan;
	hstat = HAL_ADC_ConfigChannel(&hadc, &sConfigADC);

	/* Perform conversion */
	hstat = HAL_ADC_Start(&hadc);
	while(j<u8_num_conv)
	{
		hstat = HAL_ADC_PollForConversion(&hadc, 10);
		u32_adc_result = u32_adc_result + HAL_ADC_GetValue(&hadc);
		j++;
	}
	u32_adc_result = u32_adc_result / u8_num_conv;
	hstat = HAL_ADC_Stop(&hadc);

	/* Disable channel */
	sConfigADC.Rank = ADC_RANK_NONE;
	hstat = HAL_ADC_ConfigChannel(&hadc, &sConfigADC);

	return u32_adc_result;
}
/**
  * @brief Temperature monitoring thread
  * @param none
  * @retval none
  */
void Thread_Temperature (void const *argument) {

  while(1) {
    HAL_ADC_Start(&ADC1_Handle);                                        /* start ADC conversion */

    if (HAL_ADC_PollForConversion(&ADC1_Handle, 10000) == HAL_OK) {     /* wait for the conversion to be done and get data */
      adc_val = HAL_ADC_GetValue(&ADC1_Handle);                         /* get the value */
      kalmanUpdate(&adcState, adc_val);                                 /* filter the data and update the filter parameters */
      temperature = convertTemp(adcState.x);
      __HAL_ADC_CLEAR_FLAG(&ADC1_Handle, ADC_FLAG_EOC);
    }


    // check if the alarm needs to be triggered
    if (temperature > THRESHHOLD_TEMP_URGENT) {
      flash_alarm = 2;
    } else if (temperature > THRESHHOLD_TEMP) {
      flash_alarm = 1;
    } else {
      flash_alarm = 0;
    }

    osDelay(TEMP_DELAY);
  }
}
Example #6
0
/// \method read_timed(buf, timer)
///
/// Read analog values into `buf` at a rate set by the `timer` object.
///
/// `buf` can be bytearray or array.array for example.  The ADC values have
/// 12-bit resolution and are stored directly into `buf` if its element size is
/// 16 bits or greater.  If `buf` has only 8-bit elements (eg a bytearray) then
/// the sample resolution will be reduced to 8 bits.
///
/// `timer` should be a Timer object, and a sample is read each time the timer
/// triggers.  The timer must already be initialised and running at the desired
/// sampling frequency.
///
/// To support previous behaviour of this function, `timer` can also be an
/// integer which specifies the frequency (in Hz) to sample at.  In this case
/// Timer(6) will be automatically configured to run at the given frequency.
///
/// Example using a Timer object (preferred way):
///
///     adc = pyb.ADC(pyb.Pin.board.X19)    # create an ADC on pin X19
///     tim = pyb.Timer(6, freq=10)         # create a timer running at 10Hz
///     buf = bytearray(100)                # creat a buffer to store the samples
///     adc.read_timed(buf, tim)            # sample 100 values, taking 10s
///
/// Example using an integer for the frequency:
///
///     adc = pyb.ADC(pyb.Pin.board.X19)    # create an ADC on pin X19
///     buf = bytearray(100)                # create a buffer of 100 bytes
///     adc.read_timed(buf, 10)             # read analog values into buf at 10Hz
///                                         #   this will take 10 seconds to finish
///     for val in buf:                     # loop over all values
///         print(val)                      # print the value out
///
/// This function does not allocate any memory.
STATIC mp_obj_t adc_read_timed(mp_obj_t self_in, mp_obj_t buf_in, mp_obj_t freq_in) {
    pyb_obj_adc_t *self = self_in;

    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE);
    size_t typesize = mp_binary_get_size('@', bufinfo.typecode, NULL);

    TIM_HandleTypeDef *tim;
    #if defined(TIM6)
    if (mp_obj_is_integer(freq_in)) {
        // freq in Hz given so init TIM6 (legacy behaviour)
        tim = timer_tim6_init(mp_obj_get_int(freq_in));
        HAL_TIM_Base_Start(tim);
    } else
    #endif
    {
        // use the supplied timer object as the sampling time base
        tim = pyb_timer_get_handle(freq_in);
    }

    // configure the ADC channel
    adc_config_channel(&self->handle, self->channel);

    // This uses the timer in polling mode to do the sampling
    // TODO use DMA

    uint nelems = bufinfo.len / typesize;
    for (uint index = 0; index < nelems; index++) {
        // Wait for the timer to trigger so we sample at the correct frequency
        while (__HAL_TIM_GET_FLAG(tim, TIM_FLAG_UPDATE) == RESET) {
        }
        __HAL_TIM_CLEAR_FLAG(tim, TIM_FLAG_UPDATE);

        if (index == 0) {
            // for the first sample we need to turn the ADC on
            HAL_ADC_Start(&self->handle);
        } else {
            // for subsequent samples we can just set the "start sample" bit
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
            ADCx->CR2 |= (uint32_t)ADC_CR2_SWSTART;
#elif defined(MCU_SERIES_L4)
            SET_BIT(ADCx->CR, ADC_CR_ADSTART);
#else
            #error Unsupported processor
#endif
        }

        // wait for sample to complete
        #define READ_TIMED_TIMEOUT (10) // in ms
        adc_wait_for_eoc_or_timeout(READ_TIMED_TIMEOUT);

        // read value
        uint value = ADCx->DR;

        // store value in buffer
        if (typesize == 1) {
            value >>= 4;
        }
        mp_binary_set_val_array_from_int(bufinfo.typecode, bufinfo.buf, index, value);
    }
Example #7
0
uint32_t adc_read_channel(ADC_HandleTypeDef *adcHandle) {
    uint32_t rawValue = 0;

    HAL_ADC_Start(adcHandle);
    if (HAL_ADC_PollForConversion(adcHandle, 10) == HAL_OK && HAL_ADC_GetState(adcHandle) == HAL_ADC_STATE_EOC_REG) {
        rawValue = HAL_ADC_GetValue(adcHandle);
    }
    HAL_ADC_Stop(adcHandle);

    return rawValue;
}
Example #8
0
/**
  * @brief  ADC_Handler : SSI handler for ADC page
  */
u16_t ADC_Handler(int iIndex, char *pcInsert, int iInsertLen)
{
  /* We have only one SSI handler iIndex = 0 */
  if (iIndex ==0)
  {
    char Digit1=0, Digit2=0, Digit3=0, Digit4=0;
    uint32_t ADCVal = 0;

     /* configure ADC if not yet configured */
     if (ADC_not_configured ==1)
     {
//        BSP_ADC_Init(&hadc_bsp1,ADC_IN1,1,Indepenent_Mode);
        HAL_ADC_Start(&hadc_bsp1);
        ADC_not_configured=0;
     }

     HAL_ADC_PollForConversion(&hadc_bsp1, 10);  // check the port pin

     /* Check if the continuous conversion of regular channel is finished */
     if(HAL_ADC_GetState(&hadc_bsp1) == HAL_ADC_STATE_EOC_REG)
     {
       /* get ADC conversion value */
       ADCVal = HAL_ADC_GetValue(&hadc_bsp1);
     }
//     HAL_ADC_PollForConversion(&hadc_bsp1, 10);
     /* get ADC conversion value */
//     ADCVal =  HAL_ADC_GetValue(&hadc_bsp1);

     /* convert to Voltage,  step = 0.8 mV */
     ADCVal = (uint32_t)(ADCVal * 0.8);

     /* get digits to display */

     Digit1= ADCVal/1000;
     Digit2= (ADCVal-(Digit1*1000))/100;
     Digit3= (ADCVal-((Digit1*1000)+(Digit2*100)))/10;
     Digit4= ADCVal -((Digit1*1000)+(Digit2*100)+ (Digit3*10));

     /* prepare data to be inserted in html */
     *pcInsert       = (char)(Digit1+0x30);
     *(pcInsert + 1) = (char)(Digit2+0x30);
     *(pcInsert + 2) = (char)(Digit3+0x30);
     *(pcInsert + 3) = (char)(Digit4+0x30);

    /* 4 characters need to be inserted in html*/
    return 4;
  }
  return 0;
}
 /*----------------------------------------------------------------------------
*      Thread  'LED_Thread': Toggles LED
 *---------------------------------------------------------------------------*/
	void Thread_Temp (void const *argument) {
	
		while(1){
						osDelay(1000);
						HAL_ADC_Start(&ADCHandleinit);
						HAL_ADC_PollForConversion(&ADCHandleinit, 10);
						rawValue = HAL_ADC_GetValue(&ADCHandleinit);
						convertedValue[0] = tempConv(rawValue);
						if(convertedValue[0] > 38)
							overHeat = 1;
						else 
							overHeat = 0;
						__HAL_ADC_CLEAR_FLAG(&ADCHandleinit,ADC_FLAG_EOC);
			}
	}
uint16_t AdcMcuRead( Adc_t *obj, uint8_t channel )
{
    ADC_HandleTypeDef *hadc;
    ADC_ChannelConfTypeDef adcConf;
    uint16_t adcData = 0;

    hadc = &obj->Adc;

    /* Enable HSI */
    __HAL_RCC_HSI_ENABLE();

    /* Wait till HSI is ready */
    while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET)
    {
    }

    __HAL_RCC_ADC1_CLK_ENABLE( );

    adcConf.Channel = channel;
    adcConf.Rank = ADC_REGULAR_RANK_1;
    adcConf.SamplingTime = ADC_SAMPLETIME_192CYCLES;

    HAL_ADC_ConfigChannel( hadc, &adcConf);

    /* Enable ADC1 */
    __HAL_ADC_ENABLE( hadc) ;

    /* Start ADC1 Software Conversion */
    HAL_ADC_Start( hadc);

    HAL_ADC_PollForConversion( hadc, HAL_MAX_DELAY );

    adcData = HAL_ADC_GetValue ( hadc);

    __HAL_ADC_DISABLE( hadc) ;

    if( ( adcConf.Channel == ADC_CHANNEL_TEMPSENSOR ) || ( adcConf.Channel == ADC_CHANNEL_VREFINT ) )
    {
        HAL_ADC_DeInit( hadc );
    }
    __HAL_RCC_ADC1_CLK_DISABLE( );

    /* Disable HSI */
    __HAL_RCC_HSI_DISABLE();

    return adcData;
}
/**
  * @brief  Returns the Joystick key pressed.
  * @note   To know which Joystick key is pressed we need to detect the voltage
  *         level on each key output
  *           - None  : 3.3 V / 4095
  *           - SEL   : 1.055 V / 1308
  *           - DOWN  : 0.71 V / 88
  *           - LEFT  : 3.0 V / 3720 
  *           - RIGHT : 0.595 V / 737
  *           - UP    : 1.65 V / 2046
  * @retval JOYState_TypeDef: Code of the Joystick key pressed.
  */
JOYState_TypeDef BSP_JOY_GetState(void)
{
  JOYState_TypeDef state = JOY_NONE;
  uint16_t  keyconvertedvalue = 0; 

 /* Start the conversion process */
  HAL_ADC_Start(&hnucleo_Adc);
  
  /* Wait for the end of conversion */
  HAL_ADC_PollForConversion(&hnucleo_Adc, 10);
  
  /* Check if the continous conversion of regular channel is finished */
  if(HAL_ADC_GetState(&hnucleo_Adc) == HAL_ADC_STATE_EOC_REG)
  {
    /* Get the converted value of regular channel */
    keyconvertedvalue = HAL_ADC_GetValue(&hnucleo_Adc);
  }
  
  if((keyconvertedvalue > 2010) && (keyconvertedvalue < 2090))
  {
    state = JOY_UP;
  }
  else if((keyconvertedvalue > 680) && (keyconvertedvalue < 780))
  {
    state = JOY_RIGHT;
  }
  else if((keyconvertedvalue > 1270) && (keyconvertedvalue < 1350))
  {
    state = JOY_SEL;
  }
  else if((keyconvertedvalue > 50) && (keyconvertedvalue < 130))
  {
    state = JOY_DOWN;
  }
  else if((keyconvertedvalue > 3680) && (keyconvertedvalue < 3760))
  {
    state = JOY_LEFT;
  }
  else
  {
    state = JOY_NONE;
  }
  
  /* Return the code of the Joystick key pressed*/
  return state;
}
float STM32AdcChannel::GetVoltage ()
{
    float result = 0;

    HAL_ADC_ConfigChannel (adc.adcHandle, &channelConfig);

    HAL_Delay (1);

    HAL_ADC_Start (adc.adcHandle);
    HAL_ADC_PollForConversion (adc.adcHandle, 10);

    if (HAL_ADC_GetState (adc.adcHandle) == HAL_ADC_STATE_EOC_REG)
    {
        result = HAL_ADC_GetValue (adc.adcHandle) * scaleFactor;
    }

    return result;
}
Example #13
0
void BSP_ADC_Init(void) {

	ADC_ChannelConfTypeDef ChannelConfStruct;
	GPIO_InitTypeDef GPIO_InitStruct;

	EXP_BOARD_POT_PIN_CLK_ENABLE()
	;
	EXP_BOARD_POT_ADC_CLK_ENABLE()
	;

	ADC_HandleStruct.Instance = ADC1;

	ADC_HandleStruct.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
	ADC_HandleStruct.Init.Resolution = ADC_RESOLUTION_12B;
	ADC_HandleStruct.Init.DataAlign = ADC_DATAALIGN_RIGHT;
	ADC_HandleStruct.Init.ScanConvMode = DISABLE;
	ADC_HandleStruct.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
	ADC_HandleStruct.Init.ContinuousConvMode = ENABLE;
	ADC_HandleStruct.Init.NbrOfConversion = 1;
	ADC_HandleStruct.Init.DiscontinuousConvMode = DISABLE;
	ADC_HandleStruct.Init.ExternalTrigConv = ADC_SOFTWARE_START;
	ADC_HandleStruct.Init.DMAContinuousRequests = DISABLE;
	ADC_HandleStruct.Init.NbrOfDiscConversion = 0;
	ADC_HandleStruct.Init.ExternalTrigConvEdge =
	ADC_EXTERNALTRIGCONVEDGE_NONE;
	ADC_HandleStruct.Init.EOCSelection = DISABLE;

	GPIO_InitStruct.Pin = EXP_BOARD_POT_PIN;
	GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_FAST;

	HAL_GPIO_Init(EXP_BOARD_POT_PORT, &GPIO_InitStruct);

	ChannelConfStruct.Channel = EXP_BOARD_POT_CHANNEL;
	ChannelConfStruct.Offset = 0;
	ChannelConfStruct.Rank = 1;
	ChannelConfStruct.SamplingTime = ADC_SAMPLETIME_15CYCLES;

	HAL_ADC_Init(&ADC_HandleStruct);
	HAL_ADC_ConfigChannel(&ADC_HandleStruct, &ChannelConfStruct);
	HAL_ADC_Start(&ADC_HandleStruct);

}
Example #14
0
/**
  * @brief  Returns the Joystick key pressed.
  * @note   To know which Joystick key is pressed we need to detect the voltage
  *         level on each key output
  *           - None  : 3.3 V / 4095
  *           - SEL   : 1.055 V / 1308
  *           - DOWN  : 0.71 V / 88
  *           - LEFT  : 3.0 V / 3720 
  *           - RIGHT : 0.595 V / 737
  *           - UP    : 1.65 V / 2046
  * @retval JOYState_TypeDef: Code of the Joystick key pressed.
  */
JOYState_TypeDef BSP_JOY_GetState(void)
{
  JOYState_TypeDef state;
  uint16_t  KeyConvertedValue = 0;
  
 /* Start the conversion process */
  HAL_ADC_Start(&hnucleo_Adc);
  
  /* Wait for the end of conversion */
  if (HAL_ADC_PollForConversion(&hnucleo_Adc, 10) != HAL_TIMEOUT)
  {
    /* Get the converted value of regular channel */
    KeyConvertedValue = HAL_ADC_GetValue(&hnucleo_Adc);
  }
  
  if((KeyConvertedValue > 2010) && (KeyConvertedValue < 2090))
  {
    state = JOY_UP;
  }
  else if((KeyConvertedValue > 680) && (KeyConvertedValue < 780))
  {
    state = JOY_RIGHT;
  }
  else if((KeyConvertedValue > 1270) && (KeyConvertedValue < 1350))
  {
    state = JOY_SEL;
  }
  else if((KeyConvertedValue > 50) && (KeyConvertedValue < 130))
  {
    state = JOY_DOWN;
  }
  else if((KeyConvertedValue > 3680) && (KeyConvertedValue < 3760))
  {
    state = JOY_LEFT;
  }
  else
  {
    state = JOY_NONE;
  }
  
  /* Return the code of the Joystick key pressed */
  return state;
}
Example #15
0
void InitAll()
{
  __disable_irq();
  TimInit();
  PWMStart();
  InputDecoder();
  UartInit();
  
  FlashInit();
  SDFatFSInit();
  
  printf("mpu6050 id:0x%x\r\n",MPU6050_Init());
  IMU_Init();
  
  UIInit();
  sys.status = READY;
  HAL_ADC_Start(&hadc1);
  printf("init finish!\r\n");
  __enable_irq();
}
Example #16
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();

  /* System interrupt init*/
  /* Sets the priority grouping field */
  HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_0);
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_ADC1_Init();
  MX_DAC_Init();
  MX_TIM2_Init();

  /* USER CODE BEGIN 2 */
  HAL_ADC_Start(&hadc1);
  HAL_DAC_Start(&hdac, DAC_CHANNEL_1);

  /* USER CODE END 2 */

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

  }
  /* USER CODE END 3 */

}
Example #17
0
uint16_t adc_read(analogin_t *obj)
{
    ADC_ChannelConfTypeDef sConfig = {0};

    // Configure ADC channel
    sConfig.Rank         = 1;
    sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES;
    sConfig.Offset       = 0;

    switch (obj->channel) {
        case 0:
            sConfig.Channel = ADC_CHANNEL_0;
            break;
        case 1:
            sConfig.Channel = ADC_CHANNEL_1;
            break;
        case 2:
            sConfig.Channel = ADC_CHANNEL_2;
            break;
        case 3:
            sConfig.Channel = ADC_CHANNEL_3;
            break;
        case 4:
            sConfig.Channel = ADC_CHANNEL_4;
            break;
        case 5:
            sConfig.Channel = ADC_CHANNEL_5;
            break;
        case 6:
            sConfig.Channel = ADC_CHANNEL_6;
            break;
        case 7:
            sConfig.Channel = ADC_CHANNEL_7;
            break;
        case 8:
            sConfig.Channel = ADC_CHANNEL_8;
            break;
        case 9:
            sConfig.Channel = ADC_CHANNEL_9;
            break;
        case 10:
            sConfig.Channel = ADC_CHANNEL_10;
            break;
        case 11:
            sConfig.Channel = ADC_CHANNEL_11;
            break;
        case 12:
            sConfig.Channel = ADC_CHANNEL_12;
            break;
        case 13:
            sConfig.Channel = ADC_CHANNEL_13;
            break;
        case 14:
            sConfig.Channel = ADC_CHANNEL_14;
            break;
        case 15:
            sConfig.Channel = ADC_CHANNEL_15;
            break;
        case 16:
            sConfig.Channel = ADC_CHANNEL_TEMPSENSOR;
            break;
        case 17:
            sConfig.Channel = ADC_CHANNEL_VREFINT;
            /*  From experiment, measurement needs max sampling time to be valid */
            sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
            break;
        case 18:
            sConfig.Channel = ADC_CHANNEL_VBAT;
            /*  From experiment, measurement needs max sampling time to be valid */
            sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
            break;
        default:
            return 0;
    }

    // Measuring VBAT sets the ADC_CCR_VBATE bit in ADC->CCR, and there is not
    // possibility with the ST HAL driver to clear it. If it isn't cleared,
    // VBAT remains connected to the ADC channel in preference to temperature,
    // so VBAT readings are returned in place of temperature.
    ADC->CCR &= ~(ADC_CCR_VBATE | ADC_CCR_TSVREFE);

    HAL_ADC_ConfigChannel(&obj->handle, &sConfig);

    HAL_ADC_Start(&obj->handle); // Start conversion

    // Wait end of conversion and get value
    if (HAL_ADC_PollForConversion(&obj->handle, 10) == HAL_OK) {
        return (uint16_t)HAL_ADC_GetValue(&obj->handle);
    } else {
        return 0;
    }
}
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  ADC_ChannelConfTypeDef sConfig;

  /* STM32F4xx 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 180 MHz */
  SystemClock_Config();

  /* Configure LED3 */
  BSP_LED_Init(LED3);

  /*##-1- Configure the ADC peripheral #######################################*/
  AdcHandle.Instance          = ADCx;
  
  if (HAL_ADC_DeInit(&AdcHandle) != HAL_OK)
  {
    /* ADC de-initialization Error */
    Error_Handler();
  }
  

  AdcHandle.Init.ClockPrescaler        = ADC_CLOCKPRESCALER_PCLK_DIV2;          /* Asynchronous clock mode, input ADC clock not divided */
  AdcHandle.Init.Resolution            = ADC_RESOLUTION_12B;             /* 12-bit resolution for converted data */
  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.EOCSelection          = DISABLE;           			/* EOC flag picked-up to indicate conversion end */
  AdcHandle.Init.ContinuousConvMode    = DISABLE;                       /* Continuous mode disabled to have only 1 conversion at each conversion trig */
  AdcHandle.Init.NbrOfConversion       = 1;                             /* Parameter discarded because sequencer is disabled */
  AdcHandle.Init.DiscontinuousConvMode = DISABLE;                       /* Parameter discarded because sequencer is disabled */
  AdcHandle.Init.NbrOfDiscConversion   = 0;                             /* Parameter discarded because sequencer is disabled */
  AdcHandle.Init.ExternalTrigConv      = ADC_EXTERNALTRIGCONV_T1_CC1;            /* Software start to trig the 1st conversion manually, without external event */
  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) */

  if (HAL_ADC_Init(&AdcHandle) != HAL_OK)
  {
    /* ADC initialization Error */
    Error_Handler();
  }

  /*##-2- Configure ADC regular channel ######################################*/

  sConfig.Channel      = ADCx_CHANNEL;                /* Sampled channel number */
  sConfig.Rank         = 1;          /* Rank of sampled channel number ADCx_CHANNEL */
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;    /* Sampling time (number of clock cycles unit) */
  sConfig.Offset = 0;                                 /* Parameter discarded because offset correction is disabled */

  if (HAL_ADC_ConfigChannel(&AdcHandle, &sConfig) != HAL_OK)
  {
    /* Channel Configuration Error */
    Error_Handler();
  }


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

  /*##-4- Wait for the end of conversion #####################################*/
  /*  Before starting a new conversion, you need to check the current state of
       the peripheral; if it’s busy you need to wait for the end of current
       conversion before starting a new one.
       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 */
    Error_Handler();
  }

/* Check if the continuous conversion of regular channel is finished */
  if ((HAL_ADC_GetState(&AdcHandle) & HAL_ADC_STATE_EOC_REG) == HAL_ADC_STATE_EOC_REG)
  {
    /*##-5- Get the converted value of regular channel  ########################*/
    uhADCxConvertedValue = HAL_ADC_GetValue(&AdcHandle);
  }
  /* Infinite loop */
  while (1)
  {
  }
}
Example #19
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.
    To proceed, 5 steps are required: */

  /* STM32L0xx 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 2 MHz */
  SystemClock_Config();

  /* ### - 1 - Initialize ADC peripheral #################################### */
  /*
   *  Instance                  = ADC1.
   *  OversamplingMode          = Disabled
   *  ClockPrescaler            = PCLK clock with no division.
   *  LowPowerAutoPowerOff      = Disabled (For this exemple continuous mode is enabled with software start)
   *  LowPowerFrequencyMode     = Enabled (To be enabled only if ADC clock is lower than 2.8MHz) 
   *  LowPowerAutoWait          = Disabled (New conversion starts only when the previous conversion is completed)       
   *  Resolution                = 12 bit (increased to 16 bit with oversampler)
   *  SamplingTime              = 7.5 cycles od ADC clock.
   *  ScanConvMode              = Forward
   *  DataAlign                 = Right
   *  ContinuousConvMode        = Enabled
   *  DiscontinuousConvMode     = Disabled
   *  ExternalTrigConvEdge      = None (Software start)
   *  EOCSelection              = End Of Conversion event
   *  DMAContinuousRequests     = DISABLE
   */

  AdcHandle.Instance = ADC1;
  
  AdcHandle.Init.OversamplingMode      = DISABLE;
  
  AdcHandle.Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV1;
  AdcHandle.Init.LowPowerAutoPowerOff  = DISABLE;
  AdcHandle.Init.LowPowerFrequencyMode = ENABLE;
  AdcHandle.Init.LowPowerAutoWait      = DISABLE;
    
  AdcHandle.Init.Resolution            = ADC_RESOLUTION_12B;
  AdcHandle.Init.SamplingTime          = ADC_SAMPLETIME_7CYCLES_5;
  AdcHandle.Init.ScanConvMode          = ADC_SCAN_DIRECTION_FORWARD;
  AdcHandle.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
  AdcHandle.Init.ContinuousConvMode    = ENABLE;
  AdcHandle.Init.DiscontinuousConvMode = DISABLE;
  AdcHandle.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
  AdcHandle.Init.EOCSelection          = ADC_EOC_SINGLE_CONV;
  AdcHandle.Init.DMAContinuousRequests = DISABLE;
  
  /* 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, ADC_SINGLE_ENDED) != HAL_OK)
  {
    Error_Handler();
  }

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

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

  /* Infinite loop */
  while (1)
  {
    /*##- 5- Wait for the end of conversion #####################################*/  
    /*  Before starting a new conversion, you need to check the current state of
         the peripheral; if it’s busy you need to wait for the end of current
         conversion before starting a new one.
         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. */
    HAL_ADC_PollForConversion(&AdcHandle, 10);
  
    /* 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)
    {
      /*##-6- Get the converted value of regular channel  ########################*/
      uwADCxConvertedValue = HAL_ADC_GetValue(&AdcHandle);
    }
  }
}
Example #20
0
static inline uint16_t adc_read(analogin_t *obj) {
  ADC_ChannelConfTypeDef sConfig;
  
  AdcHandle.Instance = (ADC_TypeDef *)(obj->adc);

  // Configure ADC channel
  sConfig.Rank         = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  sConfig.Offset       = 0;

  switch (obj->pin) {
      case PA_0:
          sConfig.Channel = ADC_CHANNEL_0;
          break;
      case PA_1:
          sConfig.Channel = ADC_CHANNEL_1;
          break;
      case PA_2:
          sConfig.Channel = ADC_CHANNEL_2;
          break;
      case PA_3:
          sConfig.Channel = ADC_CHANNEL_3;
          break;
      case PA_4:
          sConfig.Channel = ADC_CHANNEL_4;
          break;
      case PA_5:
          sConfig.Channel = ADC_CHANNEL_5;
          break;
      case PA_6:
          sConfig.Channel = ADC_CHANNEL_6;
          break;
      case PA_7:
          sConfig.Channel = ADC_CHANNEL_7;
          break;
      case PB_0:
          sConfig.Channel = ADC_CHANNEL_8;
          break;
      case PB_1:
          sConfig.Channel = ADC_CHANNEL_9;
          break;
      case PC_0:
          sConfig.Channel = ADC_CHANNEL_10;
          break;
      case PC_1:
          sConfig.Channel = ADC_CHANNEL_11;
          break;
      case PC_2:
          sConfig.Channel = ADC_CHANNEL_12;
          break;
      case PC_3:
          sConfig.Channel = ADC_CHANNEL_13;
          break;
      case PC_4:
          sConfig.Channel = ADC_CHANNEL_14;
          break;
      case PC_5:
          sConfig.Channel = ADC_CHANNEL_15;
          break;
      default:
          return 0;
  }
  
  HAL_ADC_ConfigChannel(&AdcHandle, &sConfig);
    
  HAL_ADC_Start(&AdcHandle); // Start conversion
  
  HAL_ADC_PollForConversion(&AdcHandle, 10); // Wait end of conversion
  
  if (HAL_ADC_GetState(&AdcHandle) == HAL_ADC_STATE_EOC_REG)
  {
      return(HAL_ADC_GetValue(&AdcHandle)); // Get conversion value
  }
  else
  {
      return 0;
  }
}
Example #21
0
uint16_t BSP_ADC_GetValue(void){
	HAL_ADC_Start(&ADC_HandleStruct);
		return HAL_ADC_GetValue(&ADC_HandleStruct);
}
Example #22
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();
  }
}
Example #23
0
uint16_t adc_read(analogin_t *obj)
{
    ADC_ChannelConfTypeDef sConfig = {0};

    // Configure ADC channel
    sConfig.Rank         = 1;
    sConfig.SamplingTime = ADC_SAMPLETIME_56CYCLES;
    sConfig.Offset       = 0;

    switch (obj->channel) {
        case 0:
            sConfig.Channel = ADC_CHANNEL_0;
            break;
        case 1:
            sConfig.Channel = ADC_CHANNEL_1;
            break;
        case 2:
            sConfig.Channel = ADC_CHANNEL_2;
            break;
        case 3:
            sConfig.Channel = ADC_CHANNEL_3;
            break;
        case 4:
            sConfig.Channel = ADC_CHANNEL_4;
            break;
        case 5:
            sConfig.Channel = ADC_CHANNEL_5;
            break;
        case 6:
            sConfig.Channel = ADC_CHANNEL_6;
            break;
        case 7:
            sConfig.Channel = ADC_CHANNEL_7;
            break;
        case 8:
            sConfig.Channel = ADC_CHANNEL_8;
            break;
        case 9:
            sConfig.Channel = ADC_CHANNEL_9;
            break;
        case 10:
            sConfig.Channel = ADC_CHANNEL_10;
            break;
        case 11:
            sConfig.Channel = ADC_CHANNEL_11;
            break;
        case 12:
            sConfig.Channel = ADC_CHANNEL_12;
            break;
        case 13:
            sConfig.Channel = ADC_CHANNEL_13;
            break;
        case 14:
            sConfig.Channel = ADC_CHANNEL_14;
            break;
        case 15:
            sConfig.Channel = ADC_CHANNEL_15;
            break;
        case 16:
            sConfig.Channel = ADC_CHANNEL_TEMPSENSOR;
            sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
            break;
        case 17:
            sConfig.Channel = ADC_CHANNEL_VREFINT;
            sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
            break;
        case 18:
            sConfig.Channel = ADC_CHANNEL_VBAT;
            sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
            break;
        default:
            return 0;
    }

    HAL_ADC_ConfigChannel(&obj->handle, &sConfig);

    HAL_ADC_Start(&obj->handle); // Start conversion

    // Wait end of conversion and get value
    if (HAL_ADC_PollForConversion(&obj->handle, 10) == HAL_OK) {
        return (uint16_t)HAL_ADC_GetValue(&obj->handle);
    } else {
        return 0;
    }
}