轮询模式:
#include
#include
main.c
/* USER CODE BEGIN 2 */
uint32_t iOrder = 0;
uint8_t aTxBuffer[100] = { 0 };
HAL_ADCEx_Calibration_Start(&hadc1);
/* USER CODE END 2 */
while (1)
{
/* USER CODE END WHILE */
iOrder ++;
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1, 100);
uint16_t adc_value = HAL_ADC_GetValue(&hadc1);
float voltage = (float)adc_value / 4096 * 3.3;
sprintf((char*)aTxBuffer,"Ord:%d Voltage: %.2f\n", iOrder, voltage);
HAL_UART_Transmit(&huart1,aTxBuffer,strlen((char*)aTxBuffer),0xFFFF);
HAL_Delay(100);
/* USER CODE BEGIN 3 */
}
中断模式:
#include
#include
/**
* @brief The application entry point.
* @retval int
*/
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_ADC1_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
HAL_ADCEx_Calibration_Start(&hadc1);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_ADC_Start_IT(&hadc1);
HAL_Delay(100);
}
/* USER CODE END 3 */
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) //ADC转换完成回调
{
static uint32_t iOrder = 0;
iOrder ++;
uint8_t aTxBuffer[100] = { 0 };
HAL_ADC_Stop_IT(&hadc1); //关闭ADC
uint16_t adc_value = HAL_ADC_GetValue(&hadc1);
float voltage = (float)adc_value / 4096 * 3.3;
sprintf((char*)aTxBuffer,"Ord:%d Voltage: %.2f\n", iOrder, voltage);
HAL_UART_Transmit(&huart1,aTxBuffer,strlen((char*)aTxBuffer),0xFFFF);
}