nongye/STM32F103_App1/HardWare/ADC/adc.c

45 lines
1.2 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "adc.h"
#include <stdio.h>
ADC_HandleTypeDef hadc1;
void adcInit(void)
{
ADC_ChannelConfTypeDef sConfig = {0};
hadc1.Instance = ADC1;
hadc1.Init.ScanConvMode = ADC_SCAN_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();
sConfig.Channel = ADC_CHANNEL_0; /* PA0 */
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) Error_Handler();
}
uint16_t getAdc(void)
{
uint16_t adc_value = 0;
HAL_ADC_Start(&hadc1);
if (HAL_ADC_PollForConversion(&hadc1, 10) == HAL_OK) {
adc_value = HAL_ADC_GetValue(&hadc1);
}
HAL_ADC_Stop(&hadc1);
return adc_value;
}
/* 电池电量百分比0~100公式参数见 main.h BAT_* 宏 */
int battery_percent(void)
{
float v = getAdc() * (3.3f / 4096.0f);
v = v * BAT_DIV_RATIO + BAT_OFFSET_V;
float pct = 100.0f * (v - BAT_EMPTY_V) / (BAT_FULL_V - BAT_EMPTY_V);
if (pct < 0) pct = 0;
if (pct > 100) pct = 100;
return (int)pct;
}