示例#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 */

}
示例#2
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - 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: global MSP (MCU Support Package) initialization
     */
  HAL_Init();

  /* Configure the system clock to 144 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 ####*/
  /* Note: Considering IT occurring after each number of ADC conversions      */
  /*       (IT by DMA end of transfer), select sampling time and ADC clock    */
  /*       with sufficient duration to not create an overhead situation in    */
  /*        IRQHandler. */
  if (HAL_ADCEx_MultiModeStart_DMA(&AdcHandle1, (uint32_t *)aADCTripleConvertedValue, 3) != HAL_OK)
  {
    /* Start Error */
    Error_Handler();
  }

  /* Infinite loop */
  while (1)
  {
  }
}
示例#3
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* Enable the CPU Cache */
  CPU_CACHE_Enable();
	
  /* STM32F7xx HAL library initialization:
       - Configure the Flash ART accelerator on ITCM interface
       - 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 216 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)
  {
  }
}
示例#4
0
// --- Read one sample from the photo diode ---
uint16_t samplePD(void)
{
		uint16_t value = 0;
		
		HAL_ADC_Start(&hadc);

		while(HAL_ADC_PollForConversion(&hadc, HAL_MAX_DELAY) != HAL_OK) {}
		
		if (pdMode == 0)					// Analog
				value = HAL_ADC_GetValue(&hadc);
		else if (pdMode == 1)			// Digital
		{
				value = HAL_ADC_GetValue(&hadc);
				if (value >= onelevel)
						value = 1;
				else if (value <= zerolevel)
						value = 0;
				else
						value = round(rand()%1);
		}
			
		HAL_ADC_Stop(&hadc);
			
		return value;
}
示例#5
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;
}
示例#6
0
/**
  * @brief  Configures the ADC.
  * @param  None
  * @retval None
  */
static void ADC_Configuration(void)
{
  ADC_ChannelConfTypeDef sConfig;

  /* ADC3 Configuration ------------------------------------------------------*/
  hadc.Instance = ADC3;
  hadc.Init.ClockPrescaler = ADC_CLOCKPRESCALER_PCLK_DIV2;
  hadc.Init.Resolution = ADC_RESOLUTION_12B;
  hadc.Init.ScanConvMode = DISABLE;
  hadc.Init.ContinuousConvMode = ENABLE;
  hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T1_CC1; 
  hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc.Init.NbrOfConversion = 1;
  
  HAL_ADC_Init(&hadc);
  
  /* ADC3 Regular Channel Config */ 
  sConfig.Channel = ADC_CHANNEL_8;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_56CYCLES;
  sConfig.Offset = 0;
  HAL_ADC_ConfigChannel(&hadc, &sConfig);

  /* Enable EOC interupt */
  HAL_ADC_Start(&hadc);

}
示例#7
0
文件: AdcRead.c 项目: salinraj/NIBP
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);

}
示例#8
0
文件: main.cpp 项目: JBZ93/EchOpen
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()); 

}
示例#9
0
int32_t drv_adc_read(uint32_t ulPin)
{
  ADC_ChannelConfTypeDef sConfig;
  ADC_HandleTypeDef      *hADCx;
  uint32_t ulValue = 0;
  uint32_t ulChannel;
  uint32_t adc_pin;


  adc_pin = analogPinToChannel(ulPin);

  ulChannel = g_Pin2PortMapArray[adc_pin].adc_channel;

  if(ulChannel == NO_ADC)
      return -1;

  hADCx = g_Pin2PortMapArray[adc_pin].ADCx;

  sConfig.Channel      = ulChannel;
  sConfig.Rank         = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_41CYCLES_5;

  HAL_ADC_ConfigChannel(hADCx, &sConfig);

  HAL_ADC_Start(hADCx);
  HAL_ADC_PollForConversion(hADCx, 10);
  ulValue = HAL_ADC_GetValue(hADCx);

  return (int32_t)ulValue;
}
示例#10
0
//------------------------------------------------------
uint8_t read_batt()
{ uint32_t temp[3];
	//HAL_ADC_Start_IT(&hadc1);
	for(uint8_t i=0;i<3;i++)
	{
		HAL_ADC_Start(&hadc1);
		if (HAL_ADC_PollForConversion(&hadc1, 100) != HAL_OK)
			return 0;
		if ((HAL_ADC_GetState(&hadc1) & HAL_ADC_STATE_EOC_REG) == HAL_ADC_STATE_EOC_REG)
		{
			temp[i] = HAL_ADC_GetValue(&hadc1);
				if(temp[i]<batt_min)
					temp[i]=batt_min;
				if(temp[i]>batt_max)
					temp[i]=batt_max;
		}
		HAL_ADC_Stop(&hadc1);
	}
	temp[0]=(temp[0]+temp[1]+temp[2])/3;
	batt_status=(temp[0]-batt_min)*100/(batt_max-batt_min);
	SEGGER_RTT_printf(0,"power:%d\r\n",batt_status);			

	return 1;

}
/**
  * @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);
  }
}
示例#12
0
文件: adc.c 项目: DanielO/micropython
STATIC uint32_t adc_read_channel(ADC_HandleTypeDef *adcHandle) {
    HAL_ADC_Start(adcHandle);
    adc_wait_for_eoc_or_timeout(EOC_TIMEOUT);
    uint32_t value = ADCx->DR;
    HAL_ADC_Stop(adcHandle);
    return value;
}
示例#13
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(STM32F4) || defined(STM32F7)
            ADCx->CR2 |= (uint32_t)ADC_CR2_SWSTART;
#elif defined(STM32L4)
            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);
    }
 /*----------------------------------------------------------------------------
*      Implementation of the temperature checking thread
 *---------------------------------------------------------------------------*/
void Thread_check_temp (void const *argument) {
	
	float temperature = 0.0f;
	
	while(1){
		
		//Using a delay of 10ms so that the frequency of temperature sampling is 100Hz
		osDelay(10);
		
		//Start the ADC
		if (HAL_ADC_Start(&ADC1_Handle) != HAL_OK) {
			Error_Handler(ADC_START_FAIL);
		} 
		else {
			
			//Check for successful conversion of the polled analog value to a digital reading
			if(HAL_ADC_PollForConversion(&ADC1_Handle, 1000000) != HAL_OK) {
				Error_Handler(ADC_POLL_FAIL);
			} 
			else {
				//Measure temperature from sensor 
				temperature = get_data_from_sensor();
			}
			
			//Clear the EOC flag
			__HAL_ADC_CLEAR_FLAG(&ADC1_Handle,ADC_FLAG_EOC);
		}
		
		//Pass the temp value to the temperature checking function
		display_temp = temperature;
		check_temperature_status(display_temp);			
	}
}
示例#15
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;
}
示例#16
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;
	}
示例#17
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;
	}
示例#18
0
	void js_analogRead(CScriptVar *v, void *userdata){
		int type = v->getParameter("type")->getInt();
		int pin = v->getParameter("pin")->getInt();
		if(Types[type] == 0 || Pins[pin] ==0){
			v->getReturnVar()->setInt(0);
			return;
		}

		if(AdcHandle.Instance != ADC3){
		  AdcHandle.Instance          = ADC3;
		  AdcHandle.Init.ClockPrescaler        = ADC_CLOCKPRESCALER_PCLK_DIV2;
		  AdcHandle.Init.Resolution            = ADC_RESOLUTION12b;
		  AdcHandle.Init.ScanConvMode          = DISABLE;
		  AdcHandle.Init.ContinuousConvMode    = DISABLE;
		  AdcHandle.Init.DiscontinuousConvMode = DISABLE;
		  AdcHandle.Init.NbrOfDiscConversion   = 0;
		  AdcHandle.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
		  AdcHandle.Init.ExternalTrigConv      = ADC_EXTERNALTRIGCONV_T1_CC1;
		  AdcHandle.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
		  AdcHandle.Init.NbrOfConversion       = 1;
		  AdcHandle.Init.DMAContinuousRequests = DISABLE;
		  AdcHandle.Init.EOCSelection          = DISABLE;

		  if (HAL_ADC_Init(&AdcHandle) != HAL_OK)
		  {
			  v->getReturnVar()->setInt(0);
			  return;
		  }
		}
		  ADC_ChannelConfTypeDef sConfig;
		  sConfig.Channel      = Pins[pin];
		  sConfig.Rank         = 1;
		  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
		  sConfig.Offset       = 0;

		  if (HAL_ADC_ConfigChannel(&AdcHandle, &sConfig) != HAL_OK)
		  {
			  v->getReturnVar()->setInt(0);
			  return;
		  }
		  if (HAL_ADC_Start(&AdcHandle) != HAL_OK)
		  {
			  v->getReturnVar()->setInt(0);
			  return;
		  }

		  HAL_ADC_PollForConversion(&AdcHandle, 10);
		  if (HAL_ADC_GetState(&AdcHandle) == HAL_ADC_STATE_EOC_REG)
		  {
			  uhADCxConvertedValue = HAL_ADC_GetValue(&AdcHandle);
		  }

		  v->getReturnVar()->setInt(uhADCxConvertedValue);
		  return;
	}
示例#19
0
STATIC 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;
}
示例#20
0
文件: main.c 项目: jifwin/auk_project
int main(void)
{

  HAL_Init();

  SystemClock_Config();


  MX_GPIO_Init();
  MX_ADC1_Init();
  MX_DMA2D_Init();
  MX_FMC_Init();
  MX_I2C3_Init();
  MX_LTDC_Init();
  MX_RNG_Init();
  MX_SPI5_Init();

	BSP_LCD_Init();
	BSP_LCD_LayerDefaultInit(LCD_BACKGROUND_LAYER, LCD_FRAME_BUFFER);
	BSP_LCD_LayerDefaultInit(LCD_FOREGROUND_LAYER, LCD_FRAME_BUFFER);
	BSP_LCD_SelectLayer(LCD_FOREGROUND_LAYER);
	BSP_LCD_Clear(LCD_COLOR_BLACK);
	BSP_LCD_DisplayOn();
	uint8_t Button_Value;
	GPIO_InitTypeDef GPIO_InitStruct;
  GPIO_InitStruct.Pin |= GPIO_PIN_0;
  GPIO_InitStruct.Mode = 0x00;
  GPIO_InitStruct.Pull = 0x02;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
	while (1)
		{
		
		for(uint16_t i = 0; i < SIZE; i+=2) {
			HAL_ADC_Start(&hadc1);
			HAL_ADC_PollForConversion(&hadc1,1000); 
			samples[i] = HAL_ADC_GetValue(&hadc1);
			samples[i+1] = 0;
			HAL_ADC_Stop(&hadc1);
		}
		
		Button_Value = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0);
		if( Button_Value )
		{		
			fft();
			
		}
		else
		{
		
			display_samples(samples);

		}
	}
}
示例#21
0
文件: fm_adc.c 项目: JFDuval/FlexSEA
unsigned int adc_conv(void)
{
	unsigned int result = 0;

	HAL_ADC_Start(&hadc1);
	while(HAL_ADC_PollForConversion(&hadc1, 5000) != HAL_OK)
		;
	result = HAL_ADC_GetValue(&hadc1);

	return result;
}
示例#22
0
/**  ADC Configuration
   * @brief  Configures ADC1 Channel 16 so that temperature values can be read
   */
void ADC_config(void) {  // TODO: Make this configuration proper so that it actually works

	ADC_ChannelConfTypeDef ADC1_ch16;
	
	
	// Initialize values for ADC1 handle type def
	ADC1_Handle.Instance = ADC1;
	ADC1_Handle.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
	ADC1_Handle.Init.Resolution = ADC_RESOLUTION_12B;    									 
	ADC1_Handle.Init.DataAlign = ADC_DATAALIGN_RIGHT;         						
	ADC1_Handle.Init.ScanConvMode = DISABLE;           
	ADC1_Handle.Init.EOCSelection = DISABLE;         			
	ADC1_Handle.Init.ContinuousConvMode = ENABLE;      //
	ADC1_Handle.Init.DMAContinuousRequests = DISABLE;  
	ADC1_Handle.Init.NbrOfConversion = 1;       													
	ADC1_Handle.Init.DiscontinuousConvMode = DISABLE;  
	ADC1_Handle.Init.NbrOfDiscConversion = 0;    
	ADC1_Handle.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T1_CC1;       //
	ADC1_Handle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;  //
	
	
	// Initialize values for temperature sensor (Temperature analog channel is Ch16 of ADC1)
	ADC1_ch16.Channel = ADC_CHANNEL_16;
	ADC1_ch16.Rank = 1;
	ADC1_ch16.SamplingTime = ADC_SAMPLETIME_480CYCLES;
	ADC1_ch16.Offset = 0;
	
	
	// Enable ADC clock
	__ADC1_CLK_ENABLE();
	
	// Initialize clock with error handling

	if(HAL_ADC_Init(&ADC1_Handle)!=HAL_OK){
		//Error_Handler(ADC_INIT_FAIL);
		printf("adc init fail\n");
	}
	// Configure temperature sensor peripheral 
	HAL_ADC_ConfigChannel(&ADC1_Handle, &ADC1_ch16);
	
	HAL_ADC_Start(&ADC1_Handle);
	
	// Allot values to the kalman filtration struct for the temperature sensor
	kalman_temperature.q = 0.3;
	kalman_temperature.r = 1.2;
	kalman_temperature.x = 1000.0;
	kalman_temperature.p = 0.0;
	kalman_temperature.k = 0.0;
	
	// Initialize temperature sensor mutex
	temperatureMutex = osMutexCreate(temperatureMutexPtr);
	
}
示例#23
0
/// \method read_timed(buf, freq)
/// Read analog values into the given buffer at the given frequency. Buffer
/// can be bytearray or array.array for example. If a buffer with 8-bit elements
/// is used, sample resolution will be reduced to 8 bits.
///
/// Example:
///
///     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);
    int typesize = mp_binary_get_size('@', bufinfo.typecode, NULL);

    // Init TIM6 at the required frequency (in Hz)
    timer_tim6_init(mp_obj_get_int(freq_in));

    // Start timer
    HAL_TIM_Base_Start(&TIM6_Handle);

    // configure the ADC channel
    adc_config_channel(self);

    // 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(&TIM6_Handle, TIM_FLAG_UPDATE) == RESET) {
        }
        __HAL_TIM_CLEAR_FLAG(&TIM6_Handle, 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
            ADCx->CR2 |= (uint32_t)ADC_CR2_SWSTART;
        }

        // wait for sample to complete
        uint32_t tickstart = HAL_GetTick();
        while ((ADCx->SR & ADC_FLAG_EOC) != ADC_FLAG_EOC) {
            #define READ_TIMED_TIMEOUT (10) // in ms
            if (((HAL_GetTick() - tickstart ) > READ_TIMED_TIMEOUT)) {
                break; // 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);
    }
/**
  * @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 */
    HAL_ADC_PollForConversion(&hnucleo_Adc, 10);

    /* Check if the continuous 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;
    }

    /* Loop while a key is pressed */
    if(state != JOY_NONE)
    {
        keyconvertedvalue = HAL_ADC_GetValue(&hnucleo_Adc);
    }
    /* Return the code of the Joystick key pressed */
    return state;
}
示例#25
0
文件: adc.c 项目: MasterPrerov/PSDR
	void adcStartConversion()
	{
		if(HAL_ADC_Start(&AdcHandle1) != HAL_OK)
		{
			/* Start Conversation Error */
			//Error_Handler();
			wrongThings++;
		}

		if(HAL_ADC_Start(&AdcHandle2) != HAL_OK)
		{
			/* Start Conversation Error */
			//Error_Handler();
			wrongThings++;
		}

		if(HAL_ADC_Start(&AdcHandle3) != HAL_OK)
		{
			/* Start Conversation Error */
			//Error_Handler();
			wrongThings++;
		}
	}
示例#26
0
文件: aos_pd_adc.c 项目: OUWECAD/MOWE
/* --- Read one sample from the photo diode --- */
uint16_t SamplePD(void)
{
	uint16_t value = 0;
	
	HAL_ADC_Start(&hadc);

	while(HAL_ADC_PollForConversion(&hadc, HAL_MAX_DELAY) != HAL_OK) {}
	
	value = HAL_ADC_GetValue(&hadc);
		
	HAL_ADC_Stop(&hadc);
		
	return value;
}
示例#27
0
文件: main.c 项目: kqzca/prj
int readAdcChannel(uint32_t channel)
{
	int rtn = -1;
	
  HAL_ADC_Init(&hadc);
  ADC_ChannelConfTypeDef sConfig;
	
	static uint32_t channels[3] = {ADC_CHANNEL_7, ADC_CHANNEL_9, ADC_CHANNEL_9};
	for (int idx = 0; idx < 3; idx++)
	{
		sConfig.Channel = channels[idx];
		if (channel == sConfig.Channel)
		{
			sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;
		}
		else
		{
			sConfig.Rank = ADC_RANK_NONE;
		}
		HAL_ADC_ConfigChannel(&hadc, &sConfig);
	}
	
	int adcRead[3] = {-1, -1, -1};
	for (int i=0; i<3; i++)
	{
		if (HAL_ADC_Start(&hadc) == HAL_OK)
		{
			if (HAL_ADC_PollForConversion(&hadc, 1000) == HAL_OK)
			{
				adcRead[i] = (int)HAL_ADC_GetValue(&hadc);
				HAL_ADC_Stop(&hadc);
			}
			else
			{
				HAL_ADC_Stop(&hadc);
				break;
			}
		}
		else
		{
			break;
		}
	}
	
	if ((adcRead[0] >= 0) && (adcRead[1] >= 0) && (adcRead[2] >= 0))
	{
		rtn = (adcRead[0] + adcRead[1] + adcRead[2])/3;
	}
	return rtn;
}
示例#28
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;
}
示例#29
0
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//
// single sample
//
uint16 uni_adc_singleSample(void)
{
	uint16 val16 = 0;
  ADC_ChannelConfTypeDef sConfig;
  //sConfig.Channel = ADC_CHANNEL_VREFINT;
  sConfig.Channel = ADC_CHANNEL_1;
	sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES;
	sConfig.Rank = 1;
  HAL_ADC_ConfigChannel(&hadc1, &sConfig);
	if(HAL_ADC_Start(&hadc1) != HAL_OK) return 0;
	HAL_ADC_PollForConversion(&hadc1, 10); // timeout
	val16 = HAL_ADC_GetValue(&hadc1);
	HAL_ADC_Stop(&hadc1);
	return val16;
}
示例#30
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);
			}
	}