用HAL库写GET_ADC(uint8_t ch)函数,实现读取PA3 PA4口
时间: 2023-07-12 14:47:25 浏览: 121
好的,下面是用HAL库写GET_ADC(uint8_t ch)函数的代码实现:
```c
#include "stm32f1xx_hal.h"
ADC_HandleTypeDef hadc1;
/**
* @brief Initializes the ADC MSP.
* @param hadc: ADC handle
* @retval None
*/
void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(hadc->Instance==ADC1)
{
/* Peripheral clock enable */
__HAL_RCC_ADC1_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**ADC1 GPIO Configuration
PA3 ------> ADC1_IN3
PA4 ------> ADC1_IN4
*/
GPIO_InitStruct.Pin = GPIO_PIN_3|GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
}
/**
* @brief DeInitializes the ADC MSP.
* @param hadc: ADC handle
* @retval None
*/
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
{
if(hadc->Instance==ADC1)
{
/* Peripheral clock disable */
__HAL_RCC_ADC1_CLK_DISABLE();
/**ADC1 GPIO Configuration
PA3 ------> ADC1_IN3
PA4 ------> ADC1_IN4
*/
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_3|GPIO_PIN_4);
}
}
/**
* @brief Get ADC value.
* @param ch: ADC channel.
* @retval ADC value.
*/
uint16_t GET_ADC(uint8_t ch)
{
ADC_ChannelConfTypeDef sConfig = {0};
uint16_t adc_value;
/* Initialize ADC */
hadc1.Instance = ADC1;
hadc1.Init.ScanConvMode = DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 1;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/* Configure ADC channel */
sConfig.Channel = ch == 0 ? ADC_CHANNEL_3 : ADC_CHANNEL_4;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_13CYCLES_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* Start ADC conversion */
if (HAL_ADC_Start(&hadc1) != HAL_OK)
{
Error_Handler();
}
/* Wait for ADC conversion to complete */
if (HAL_ADC_PollForConversion(&hadc1, 100) != HAL_OK)
{
Error_Handler();
}
/* Get ADC value */
adc_value = HAL_ADC_GetValue(&hadc1);
/* Stop ADC conversion */
if (HAL_ADC_Stop(&hadc1) != HAL_OK)
{
Error_Handler();
}
/* De-initialize ADC */
HAL_ADC_DeInit(&hadc1);
return adc_value;
}
```
调用方式为:
```c
uint16_t adc_value1, adc_value2;
adc_value1 = GET_ADC(0); // 读取PA3口的ADC值
adc_value2 = GET_ADC(1); // 读取PA4口的ADC值
```
这段代码会初始化ADC,并通过GET_ADC函数读取指定的ADC通道上的值。
阅读全文